I'm trying to integrate a paypal payment to my JavaEE web application.
Every time I try to make a payment, it throw a 403 Error.
Here is the servlet I'm using:
#WebServlet(name="PaypalPayment", urlPatterns={"/paypal-payment.html"})
public class Paypal_Payment extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
OAuthTokenCredential token;
String accessToken;
APIContext apiContext;
Map<String, String> sdkConfig = new HashMap<String, String>();
sdkConfig.put("mode", "sandbox");
sdkConfig.put("service.EndPoint", "https://api.sandbox.paypal.com");
sdkConfig.put("client_id", Constantes.PAYPAL_CLIENT_ID);
sdkConfig.put("secret", Constantes.PAYPAL_CLIENT_SECRET);
try{
token = new OAuthTokenCredential(Constantes.PAYPAL_CLIENT_ID, Constantes.PAYPAL_CLIENT_SECRET, sdkConfig);
accessToken = token.getAccessToken();
apiContext = new APIContext(accessToken);
apiContext.setConfigurationMap(sdkConfig);
Amount amount = new Amount();
amount.setCurrency("EUR");
amount.setTotal("25");
Transaction transaction = new Transaction();
transaction.setDescription("Creating Payment");
transaction.setAmount(amount);
List<Transaction> transactions = new ArrayList<Transaction>();
transactions.add(transaction);
Payer payer = new Payer();
payer.setPaymentMethod("paypal");
Payment payment = new Payment();
payment.setIntent("sale");
payment.setPayer(payer);
payment.setTransactions(transactions);
RedirectUrls redirectUrls = new RedirectUrls();
redirectUrls.setCancelUrl("http://example.com/a-vos-cas-JSP/paypal-payment.html");
redirectUrls.setReturnUrl("http://example.com/a-vos-cas-JSP/paypal-payment.html");
payment.setRedirectUrls(redirectUrls);
Payment createdPayment = payment.create(apiContext);
System.out.println("createdPayment : " + createdPayment);
}catch(PayPalRESTException e){
e.printStackTrace();
}
getServletContext().getNamedDispatcher(Constantes.VUE_PAYPAL_RESPONSE).forward(request, response);
}
}
here is the console output:
14:26:15,550 INFO [stdout] (http--0.0.0.0-8080-6) curl command:
14:26:15,551 INFO [stdout] (http--0.0.0.0-8080-6) curl -v
'https://api.sandbox.paypal.com/v1/oauth2/token' \ 14:26:15,552 INFO
[stdout] (http--0.0.0.0-8080-6) -H "Authorization: Basic
QWJHQTFSQXVpeVA0RDVvQmt5d1o3dTBCanJJWkt0dm9CaVhTcDZ0QWFINlM4LXRFdzByX2hyRzNfbUZMOkVBRmhVQkJkZWRqTmJfTXV6SlNpbVI1YnY3SThQVzdwUldibGQ2aE9seThMZlNnRlhhbS1LaHJtRVZmZA=="
\ 14:26:15,552 INFO [stdout] (http--0.0.0.0-8080-6) -H "User-Agent:
PayPalSDK/paypal-core-java 1.5.0
(lang=Java;v=1.7.0_55;bit=64;os=Mac_OS_X 10.9.2)" \ 14:26:15,553 INFO
[stdout] (http--0.0.0.0-8080-6) -H "Accept: application/json" \
14:26:15,553 INFO [stdout] (http--0.0.0.0-8080-6) -d
'grant_type=client_credentials' 14:26:16,878 INFO [stdout]
(http--0.0.0.0-8080-6) curl command: 14:26:16,879 INFO [stdout]
(http--0.0.0.0-8080-6) curl -v
'https://api.sandbox.paypal.com/v1/payments/payment' \ 14:26:16,879
INFO [stdout] (http--0.0.0.0-8080-6) -H "Authorization: Bearer
A015iJYDQHdb7TJXzJzVIW-eSm1lP8NObGmlJkTzx2wVREo" \ 14:26:16,879 INFO
[stdout] (http--0.0.0.0-8080-6) -H "User-Agent:
PayPalSDK/rest-sdk-java 0.9.0 (lang=Java;v=1.7.0_55;bit=64;os=Mac_OS_X
10.9.2)" \ 14:26:16,880 INFO [stdout] (http--0.0.0.0-8080-6) -H "PayPal-Request-Id: 7b42030f-9b96-4027-9257-0c1311082fa2" \
14:26:16,880 INFO [stdout] (http--0.0.0.0-8080-6) -H "Content-Type:
application/json" \ 14:26:16,880 INFO [stdout] (http--0.0.0.0-8080-6)
-d '{ 14:26:16,880 INFO [stdout] (http--0.0.0.0-8080-6) "intent": "sale", 14:26:16,880 INFO [stdout] (http--0.0.0.0-8080-6) "payer":
{ 14:26:16,881 INFO [stdout] (http--0.0.0.0-8080-6)
"payment_method": "paypal" 14:26:16,881 INFO [stdout]
(http--0.0.0.0-8080-6) }, 14:26:16,881 INFO [stdout]
(http--0.0.0.0-8080-6) "transactions": [ 14:26:16,881 INFO [stdout]
(http--0.0.0.0-8080-6) { 14:26:16,881 INFO [stdout]
(http--0.0.0.0-8080-6) "amount": { 14:26:16,882 INFO [stdout]
(http--0.0.0.0-8080-6) "currency": "EUR", 14:26:16,882 INFO
[stdout] (http--0.0.0.0-8080-6) "total": "25" 14:26:16,882
INFO [stdout] (http--0.0.0.0-8080-6) }, 14:26:16,882 INFO
[stdout] (http--0.0.0.0-8080-6) "description": "Creating
Payment" 14:26:16,882 INFO [stdout] (http--0.0.0.0-8080-6) }
14:26:16,883 INFO [stdout] (http--0.0.0.0-8080-6) ], 14:26:16,883
INFO [stdout] (http--0.0.0.0-8080-6) "redirect_urls": {
14:26:16,883 INFO [stdout] (http--0.0.0.0-8080-6) "return_url":
"http://example.com/a-vos-cas-JSP/paypal-response.html",
14:26:16,883 INFO [stdout] (http--0.0.0.0-8080-6) "cancel_url":
"http://example.com/a-vos-cas-JSP/paypal-cancel.html" 14:26:16,884
INFO [stdout] (http--0.0.0.0-8080-6) } 14:26:16,884 INFO [stdout]
(http--0.0.0.0-8080-6) }' 14:26:17,909 Grave [class
com.paypal.core.HttpConnection] (http--0.0.0.0-8080-6) Error code :
403 with response : {"name":"REQUIRED_SCOPE_MISSING","message":"Access
token does not have required
scope","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#REQUIRED_SCOPE_MISSING","debug_id":"e066fbac38f41"}
14:26:17,911 ERROR [stderr] (http--0.0.0.0-8080-6)
com.paypal.core.rest.PayPalRESTException: Error code : 403 with
response : {"name":"REQUIRED_SCOPE_MISSING","message":"Access token
does not have required
scope","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#REQUIRED_SCOPE_MISSING","debug_id":"e066fbac38f41"}
So, there is a message saying that the scope could not be found, but I was not able to get any information about this error. I think I missed something in this servlet, but I can't find what. Any help would be appreciated :D
Thanks a lot
The answer is contained in this response:
{"name":"REQUIRED_SCOPE_MISSING",
"message":"Access token does not have required scope",
"information_link":"https://developer.paypal.com/webapps/developer/docs/api/#REQUIRED_SCOPE_MISSING",
"debug_id":"e066fbac38f41"}
There's some attribute in your app's configuration that's missing. Your best bet is to contact support with the debug_id listed. They can help get your account configured correctly.
Related
I work on simple authentication app using spring security & encounter by an access denied error. I must mention that registration works perfectly & I've already created 1 record with bcrypted password but on login I'm failed to understand that what did I miss. Grateful for the help
User.java
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String username;
private String email;
private String password;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JsonIgnore
private Set<UserRole> userRoles = new HashSet<>();
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Set<GrantedAuthority>authorities = new HashSet<>();
userRoles.forEach(ur -> authorities.add(new
Authority(ur.getRole().getName())));
return authorities;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private UserSecurityService userSecurityService;
public SecurityConfig(UserSecurityService userSecurityService) {
this.userSecurityService = userSecurityService;
}
#Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers("/api/auth/**").permitAll()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.userDetailsService(userSecurityService).passwordEncoder
(passwordEncoder());
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws
Exception {return super.authenticationManagerBean();
}
}
UserSecurityService (loaduser)
#Service
public class UserSecurityService implements UserDetailsService {
private static final Logger LOG =
LoggerFactory.getLogger(UserSecurityService.class);
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws
UsernameNotFoundException {
User user = userRepository.findUserByUsername(username);
if (null == user) {
LOG.warn("Username {} not found", username);
throw new UsernameNotFoundException("Username " + username + "
not found");
}
return user;
}
}
AuthController
#RestController
#RequestMapping("/api/auth")
public class AuthController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private PasswordEncoder passwordEncoder;
#Autowired
private UserService userService;
#PostMapping("/register")
public ResponseEntity<User> register(#RequestBody User user) throws Exception {
return new ResponseEntity<>(userService.register(user), HttpStatus.OK);
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody String username, String password ) throws
Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
username, password
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
}
Error
2022-01-14 14:49:13.604 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Starting
BankingApiApplication using Java 11.0.12 on LAPTOP-BQ48GM36 with PID
24600 (B:\spring\bankingAPI\target\classes started by The Kash in
B:\spring\bankingAPI)
2022-01-14 14:49:13.605 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : No active profile set,
falling back to default profiles: default
2022-01-14 14:49:13.673 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults
active! Set 'spring.devtools.add-properties' to 'false' to disable
2022-01-14 14:49:13.674 INFO 24600 --- [ restartedMain]
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related
logging consider setting the 'logging.level.web' property to 'DEBUG'
2022-01-14 14:49:14.557 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data
JPA
repositories in DEFAULT mode.
2022-01-14 14:49:14.646 INFO 24600 --- [ restartedMain]
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data
repository scanning in 74 ms. Found 2 JPA repository interfaces.
2022-01-14 14:49:15.876 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with
port(s): 8088 (http)
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-01-14 14:49:15.890 INFO 24600 --- [ restartedMain]
org.apache.catalina.core.StandardEngine : Starting Servlet engine:
[Apache Tomcat/9.0.56]
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring embedded
WebApplicationContext
2022-01-14 14:49:16.008 INFO 24600 --- [ restartedMain]
w.s.c.ServletWebServerApplicationContext : Root
WebApplicationContext:
initialization completed in 2334 ms
2022-01-14 14:49:16.264 INFO 24600 --- [ restartedMain]
o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing
PersistenceUnitInfo [name: default]
2022-01-14 14:49:16.332 INFO 24600 --- [ restartedMain]
org.hibernate.Version : HHH000412: Hibernate ORM
core
version 5.6.3.Final
2022-01-14 14:49:16.542 INFO 24600 --- [ restartedMain]
o.hibernate.annotations.common.Version : HCANN000001: Hibernate
Commons Annotations {5.1.2.Final}
2022-01-14 14:49:16.661 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-01-14 14:49:17.128 INFO 24600 --- [ restartedMain]
com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start
completed.
2022-01-14 14:49:17.145 INFO 24600 --- [ restartedMain]
org.hibernate.dialect.Dialect : HHH000400: Using dialect:
org.hibernate.dialect.MySQL57Dialect
2022-01-14 14:49:18.469 INFO 24600 --- [ restartedMain]
o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using
JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.
NoJtaPlatform]
2022-01-14 14:49:18.478 INFO 24600 --- [ restartedMain]
j.LocalContainerEntityManagerFactoryBean : Initialized JPA
EntityManagerFactory for persistence unit 'default'
2022-01-14 14:49:19.173 WARN 24600 --- [ restartedMain]
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is
enabled by default. Therefore, database queries may be performed
during
view rendering. Explicitly configure spring.jpa.open-in-view to
disable
this warning
2022-01-14 14:49:19.453 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/**', GET]
2022-01-14 14:49:19.455 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [permitAll] for Ant [pattern='/api/auth/**']
2022-01-14 14:49:19.456 DEBUG 24600 --- [ restartedMain]
edFilterInvocationSecurityMetadataSource : Adding web access control
expression [authenticated] for any request
2022-01-14 14:49:19.468 INFO 24600 --- [ restartedMain]
o.s.s.web.DefaultSecurityFilterChain : Will secure any request
with
[org.springframework.security.web.context.request.async.
WebAsyncManagerIntegrationFilter#4b607819,
org.springframework.security.web.context.SecurityContextPersistence
Filter#146dcdcf,
org.springframework.security.web.header.HeaderWriterFilter#74f0174b,
org.springframework.security.web.authentication.logout.
LogoutFilter#839ff7f,
org.springframework.security.web.authentication.www.
BasicAuthenticationFilter#4f78b9a2,
org.springframework.security.web.savedrequest.
RequestCacheAwareFilter#7e2b3eef,
org.springframework.security.web.servletapi.SecurityContextHolder
AwareRequestFilter#1996d59a,
org.springframework.security.web.authentication.Anonymous
AuthenticationFilter#d82cd0b,
org.springframework.security.web.session.SessionManagement
Filter#47842f0b,
org.springframework.security.web.access.ExceptionTranslation
Filter#6fdc8d32, org.springframework.security.web.access.intercept.
FilterSecurityInterceptor#3619bc38]
2022-01-14 14:49:19.922 INFO 24600 --- [ restartedMain]
o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is
running
on port 35729
2022-01-14 14:49:19.959 INFO 24600 --- [ restartedMain]
o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s):
8088 (http) with context path ''
2022-01-14 14:49:19.970 INFO 24600 --- [ restartedMain]
c.kash.bankingAPI.BankingApiApplication : Started
BankingApiApplication
in 6.835 seconds (JVM running for 7.645)
2022-01-14 14:49:51.914 INFO 24600 --- [nio-8088-exec-2] o.a.c.c.C.
[Tomcat].[localhost].[/] : Initializing Spring
DispatcherServlet
'dispatcherServlet'
2022-01-14 14:49:51.915 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Initializing Servlet
'dispatcherServlet'
2022-01-14 14:49:51.916 INFO 24600 --- [nio-8088-exec-2]
o.s.web.servlet.DispatcherServlet : Completed initialization
in
1 ms
2022-01-14 14:49:51.931 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /api/auth/login
2022-01-14 14:49:51.936 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:51.939 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:51.940 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.session.SessionManagementFilter : Request requested invalid
session id 1E5E812360CC1B8291311CA85ACAC55A
2022-01-14 14:49:51.945 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.i.FilterSecurityInterceptor : Authorized filter
invocation
[POST /api/auth/login] with attributes [permitAll]
2022-01-14 14:49:51.946 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST
/api/auth/login
Hibernate: select user0_.id as id1_7_, user0_.email as email2_7_,
user0_.name as name3_7_, user0_.password as password4_7_,
user0_.primary_account_id as primary_6_7_, user0_.savings_account_id
as
savings_7_7_, user0_.username as username5_7_ from users user0_ where
user0_.username=?
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2]
c.k.b.s.serviceImpl.UserSecurityService : Username {
"username": "seeshee",
"password": "12345"
} not found
2022-01-14 14:49:52.313 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.a.dao.DaoAuthenticationProvider : Failed to find user '{
"username": "seeshee",
"password": "1234"
}'
2022-01-14 14:49:52.698 WARN 24600 --- [nio-8088-exec-2]
o.a.c.util.SessionIdGeneratorBase : Creation of SecureRandom
instance for session ID generation using [SHA1PRNG] took [364]
milliseconds.
2022-01-14 14:49:52.700 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.s.HttpSessionRequestCache : Saved request
http://localhost:8088/api/auth/login to session
2022-01-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using
Reque
tHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expec
edHeaderValue=XMLHttpRequest]
2022-1-14 14:49:52.701 DEBUG 24600 --- [nio-8088-exec-2]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using
default entry point
org.springframework.security.web.authentication.www.
BasicAuthenticationEntryPoint#691634d7
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store empty
SecurityContext
2022-01-14 14:49:52.702 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder
to complete request
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Securing POST /error
2022-01-14 14:49:52.705 DEBUG 24600 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Set SecurityContextHolder
to
empty SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder
to
anonymous SecurityContext
2022-01-14 14:49:52.706 DEBUG 24600 --- [nio-8088-exec-2]
o.s.security.web.FilterChainProxy : Secured POST /error
2022-01-14 14:49:52.721 DEBUG 24600 --- [nio-8088-exec-2]
a.DefaultWebInvocationPrivilegeEvaluator : filter invocation [/error]
denied for AnonymousAuthenticationToken [Principal=anonymousUser,
Credentials=[PROTECTED], Authenticated=true,
Details=WebAuthenticationDetails [RemoteIpAddress=0:0:0:0:0:0:0:1,
SessionId=BAFE9322A4A2705325C4B6540915129E], Granted Authorities=
[ROLE_ANONYMOUS]]
org.springframework.security.access.AccessDeniedException: Access is
denied
at
org.springframework.security.access.vote.AffirmativeBased.
decide(AffirmativeBased.java:73)
~[spring-security-core-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWe
bInvocationPrivilegeEvaluator.java:100) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
DefaultWebInvocationPrivilegeEvaluator.isAllowed
(DefaultWebInvocationPrivilegeEvaluator.java:67) ~[spring-security-
web-
5.6.1.jar:5.6.1]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
isAllowed
(ErrorPageSecurityFilter.java:84) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:72) ~[spring-boot-2.6.2.jar:2.6.2]
at
org.springframework.boot.web.servlet.filter.ErrorPageSecurityFilter.
doFilter
(ErrorPageSecurityFilter.java:66) ~[spring-boot-2.6.2.jar:2.6.2]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
ApplicationFilterChain.
java:189) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.jav
a:327) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.invoke
(FilterSecurityInterceptor.java:106) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.access.intercept.
FilterSecurityInterceptor.doFilter
(FilterSecurityInterceptor.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.access.
ExceptionTranslationFilter.doFilter
(ExceptionTranslationFilter.java:122) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.access.ExceptionTranslationFilter.
doFilter
(ExceptionTranslationFilter.java:116) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter
.doFilter
(SessionManagementFilter.java:87) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.session.SessionManagementFilter.
doFilter
(SessionManagementFilter.java:81) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain
.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.
AnonymousAuthenticationFilter.doFilter
(AnonymousAuthenticationFilter.java:109) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.servletapi.
SecurityContextHolderAwareRequestFilter.
doFilter(SecurityContextHolderAwareRequestFilter.java:149) ~[spring-
security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.savedrequest.
RequestCacheAwareFilter.doFilter
(RequestCacheAwareFilter.java:63) ~[spring-security-web-
5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$
VirtualFilterChain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:103) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.authentication.logout.
LogoutFilter.doFilter
(LogoutFilter.java:89) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(
OncePerRequestFilter.java:102)
~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.security.web.FilterChainProxy$VirtualFilter
Chain.doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:110) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.context.SecurityContextPersistence
Filter.doFilter
(SecurityContextPersistenceFilter.java:80) ~[spring-security-web-
5.6.1.jar:5.6.1]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.
doFilter
(FilterChainProxy.java:336) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilterInternal
(FilterChainProxy.java:211) ~[spring-security-web-5.6.1.jar:5.6.1]
at org.springframework.security.web.FilterChainProxy.doFilter
(FilterChainProxy.java:183) ~[spring-security-web-5.6.1.jar:5.6.1]
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate
(DelegatingFilterProxy.java:354) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter
(DelegatingFilterProxy.java:267) ~
[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at
org.springframework.web.filter.RequestContextFilter.doFilterInternal
(RequestContextFilter.java:100) ~[spring-web-5.3.14.jar:5.3.14]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:117) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.springframework.web.filter.OncePerRequestFilter.doFilter
(OncePerRequestFilter.java:102) ~[spring-web-5.3.14.jar:5.3.14]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter
(ApplicationFilterChain.java:189) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:162) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.invoke
(ApplicationDispatcher.java:711) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.processRequest
(ApplicationDispatcher.java:461) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.doForward
(ApplicationDispatcher.java:385) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.ApplicationDispatcher.forward
(ApplicationDispatcher.java:313) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.custom
(StandardHostValve.java:403) ~[tomcat-embed-core-
9.0.56.jar:9.0.56]
at org.apache.catalina.core.StandardHostValve.status
(StandardHostValve.java:249) ~[tomcat-embed-core-9.0.56.jar:9.0.56]
[tomcat-embed-core-9.0.56.jar:9.0.56]
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run
(TaskThread.java:61) ~
[tomcat-embed-core-9.0.56.jar:9.0.56]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
w.c.HttpSessionSecurityContextRepository : Did not store anonymous
SecurityContext
2022-01-14 00:49:13.289 DEBUG 21332 --- [nio-8088-exec-2]
s.s.w.c.SecurityContextPersistenceFilter : Cleared
SecurityContextHolder to complete request
Your logs say this:
2022-01-14 14:49:52.305 WARN 24600 --- [nio-8088-exec-2] c.k.b.s.serviceImpl.UserSecurityService :
Username { "username": "seeshee", "password": "12345" } not found
If we look in your code we can see the following line:
login(#RequestBody String username, String password )
This is your faulty code line, as it doesn't do what you think it does. You think it will take the json and extract the two parameters username and password and set these. But what it actually does is that the #RequestBody will take the entire body (the json) and set it to the parameter that is defined on, which is username.
So what spring is doing is that it will extract the entire json body and place it into the username string.
Then you try to use that to login, and then you get the error message posted above.
What you need to do is to create a holder class that spring can deserialize into.
public class RequestBody {
public RequestBody(String username, String password) {
this.username = username;
this.password = password;
}
// getters, setters
}
#PostMapping("/login")
public ResponseEntity<String> login(#RequestBody RequestBody requestBody ) throws Exception {
Authentication authentication = authenticationManager.authenticate(new
UsernamePasswordAuthenticationToken(
requestBody.getUsername(), requestBody.getPassword()
));
SecurityContextHolder.getContext().setAuthentication(authentication);
return new ResponseEntity<>("User signed -in succesfully", HttpStatus.OK);
}
You can read about how to use requestbody here:
Spring’s RequestBody and ResponseBody Annotation
I'm attempting to create a simple Post request handler in Spring Boot that consumes JSON.
#RestController
#EnableWebMvc
public class WebFormController
{
#RequestMapping(path="/process-contact-form", method = RequestMethod.POST)
public ResponseEntity<String> processContact(#RequestBody Form form) throws Exception
{
System.out.println("TEST TEST: Ran");
return new ResponseEntity<String>("Thank you for contacting us, we'll respond soon.", HttpStatus.OK);
}
}
By default, my understanding is this will consume application/json.
However, when I make a request using curl or Postman, I get this response from Spring...
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported
And in Postman I get '415 Unsupported Media Type'.
If I explicitly define the 'consumes' property...
#RequestMapping(path="/process-contact-form", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE)
Spring Boot returns this...
DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported
I've tried setting consumes to "application/json", x-www-form-urlencoded, and plain text and sending those types of requests from Postman, but I get the same results.
I built this off aws-serverless-java-container https://github.com/awslabs/aws-serverless-java-container/wiki/Quick-start---Spring-Boot and I'm running it from the SAM local CLI.
EDIT
I switched logging to DEBUG to get more details...
2020-05-08 17:53:40.692 DEBUG 1 --- [ main] s.b.w.s.f.OrderedCharacterEncodingFilter : Filter 'characterEncodingFilter' configured for use
2020-05-08 17:53:40.692 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Starting REQUEST: filter 0-characterEncodingFilter
2020-05-08 17:53:40.698 DEBUG 1 --- [ main] c.a.s.p.i.s.AwsProxyHttpServletRequest : Called set character encoding to UTF-8 on a request without a content type. Character encoding will not be set
2020-05-08 17:53:40.698 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Starting REQUEST: filter 2-com.amazonaws.serverless.proxy.internal.servlet.FilterChainManager$ServletExecutionFilter
2020-05-08 17:53:40.729 DEBUG 1 --- [ main] o.s.web.servlet.DispatcherServlet : POST "/process-contact-form", parameters={}
2020-05-08 17:53:40.732 DEBUG 1 --- [ main] c.a.s.p.i.servlet.AwsHttpServletRequest : Trying to access session. Lambda functions are stateless and should not rely on the session
2020-05-08 17:53:40.758 DEBUG 1 --- [ main] c.a.s.p.i.s.AwsHttpServletResponse : Response buffer flushed with 0 bytes, latch=1
2020-05-08 17:53:40.761 WARN 1 --- [ main] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported]
2020-05-08 17:53:40.761 DEBUG 1 --- [ main] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 415
2020-05-08 17:53:40.763 DEBUG 1 --- [ main] c.a.s.p.i.servlet.AwsHttpServletRequest : Trying to access session. Lambda functions are stateless and should not rely on the session
2020-05-08 17:53:40.768 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Executed ERROR: filter 3-com.amazonaws.serverless.proxy.internal.servlet.FilterChainManager$ServletExecutionFilter
2020-05-08 17:53:40.769 DEBUG 1 --- [ main] c.a.s.p.i.servlet.FilterChainHolder : Executed ERROR: filter 3-characterEncodingFilter
2020-05-08 17:53:40.779 INFO 1 --- [ main] c.a.s.p.internal.LambdaContainerHandler : 127.0.0.1:56893 null- null [08/05/2020:17:53:40Z] "POST /process-contact-form null" 415 - "-" "-" combined
2020-05-08 17:53:40.818 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#c9d82f99 pairs: {POST /2018-06-01/runtime/invocation/807c7e06-86f6-1bd3-1055-78b464604573/response HTTP/1.1: null}{Docker-Lambda-Invoke-Wait: 1588960412475}{Docker-Lambda-Init-End: 1588960420587}{User-Agent: Java/1.8.0_201}{Host: 127.0.0.1:9001}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}{Content-type: application/x-www-form-urlencoded}{Content-Length: 104}
2020-05-08 17:53:40.822 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#6f0129144 pairs: {null: HTTP/1.1 202 Accepted}{Content-Type: application/json}{Date: Fri, 08 May 2020 17:53:40 GMT}{Transfer-Encoding: chunked}
2020-05-08 17:53:40.825 DEBUG 1 --- [ main] s.n.www.protocol.http.HttpURLConnection : sun.net.www.MessageHeader#18fdb6cf5 pairs: {GET /2018-06-01/runtime/invocation/next HTTP/1.1: null}{User-Agent: Java/1.8.0_201}{Host: 127.0.0.1:9001}{Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2}{Connection: keep-alive}
EDIT
StreamLambdaHandler
public class StreamLambdaHandler implements RequestStreamHandler {
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;
static {
try {
handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(Application.class);
} catch (ContainerInitializationException e) {
// if we fail here. We re-throw the exception to force another cold start
e.printStackTrace();
throw new RuntimeException("Could not initialize Spring Boot application", e);
}
}
#Override
public void handleRequest(InputStream inputStream, OutputStream outputStream, Context context)
throws IOException {
System.out.println("TEST TEST " + inputStream.toString() + " " + outputStream.toString());
handler.proxyStream(inputStream, outputStream, context);
}
}
I had some assistance starting the app from scratch, and using different libraries. The annotation looks like this now..
#Path("/submit")
#Component
#Slf4j
public class SubmitController {
private JiraService jira;
private ConfigurationRepository configurations;
#Autowired
public SubmitController(JiraService jira, ConfigurationRepository configurations) {
this.jira = jira;
this.configurations = configurations;
}
#POST
#Path("/{id}")
#AnonymousAllowed
#Produces({APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response submitForm(#PathParam("id") String id, String body) {
// Stuff
}
I have problem regarding inserting data from angular to spring boot by rest API using mongodb atlas as the database. I have create another variable called numbers to test it out. But it turns out that the values was able to capture on angular but not in spring boot. Below are my codes:
Angular code:
<div class="todo-content">
<h1 class="page-title">My Todos</h1>
<div class="todo-create">
<form #todoForm="ngForm" (ngSubmit) = "createTodo(todoForm)" novalidate>
<input type="text" id="title" class="form-control" placeholder="Type a todo and press enter..."
required
name="title" [(ngModel)]="newTodo.title"
#title="ngModel" >
<input type="text" id="numbers" class="form-control" placeholder="Type a todo and press enter..."
required
name="numbers" [(ngModel)]="newTodo.numbers"
#numbers="ngModel" >
<div *ngIf="title.errors && title.dirty"
class="alert alert-danger">
<div [hidden]="!title.errors.required">
Title is required.
</div>
</div>
<td><button class="btn btn-danger" (ngSubmit) = "createTodo(todoForm)"> submit User</button></td>
</form>
</div>
<ul class="todo-list">
<li *ngFor="let todo of todos" [class.completed]= "todo.completed === true" >
<div class="todo-row" *ngIf="!editing || editingTodo.id != todo.id">
<a class="todo-completed" (click)="toggleCompleted(todo)">
<i class="material-icons toggle-completed-checkbox"></i>
</a>
<span class="todo-title">
{{todo.title}}
</span>
<span class="todo-actions">
<a (click)="editTodo(todo)">
<i class="material-icons edit">edit</i>
</a>
<a (click)="deleteTodo(todo.id)">
<i class="material-icons delete">clear</i>
</a>
</span>
</div>
<div class="todo-edit" *ngIf="editing && editingTodo.id === todo.id">
<input class="form-control" type="text"
[(ngModel)]="editingTodo.title" required>
<span class="edit-actions">
<a (click)="updateTodo(editingTodo)">
<i class="material-icons">done</i>
</a>
<a (click)="clearEditing()">
<i class="material-icons">clear</i>
</a>
</span>
</div>
</li>
</ul>
<div class="no-todos" *ngIf="todos && todos.length == 0">
<p>No Todos Found!</p>
</div>
todo-list.component.ts
import { Component, Input, OnInit } from '#angular/core';
import { TodoService } from './todo.service';
import { Todo } from './todo';
import {NgForm} from '#angular/forms';
#Component({
selector: 'todo-list',
templateUrl: './todo-list.component.html'
})
export class TodoListComponent implements OnInit {
todos: Todo[];
newTodo: Todo = new Todo();
editing: boolean = false;
editingTodo: Todo = new Todo();
constructor(
private todoService: TodoService,
) {}
ngOnInit(): void {
this.getTodos();
}
getTodos(): void {
this.todoService.getTodos()
.then(todos => this.todos = todos );
}
createTodo(todoForm: NgForm): void {
console.log(this.newTodo.numbers);
console.log(todoForm);
this.todoService.createTodo(this.newTodo)
.then(createTodo => {
todoForm.reset();
this.newTodo = new Todo();
this.todos.unshift(createTodo)
});
}
deleteTodo(id: string): void {
this.todoService.deleteTodo(id)
.then(() => {
this.todos = this.todos.filter(todo => todo.id != id);
});
}
updateTodo(todoData: Todo): void {
console.log(todoData);
this.todoService.updateTodo(todoData)
.then(updatedTodo => {
let existingTodo = this.todos.find(todo => todo.id === updatedTodo.id);
Object.assign(existingTodo, updatedTodo);
this.clearEditing();
});
}
toggleCompleted(todoData: Todo): void {
todoData.completed = !todoData.completed;
this.todoService.updateTodo(todoData)
.then(updatedTodo => {
let existingTodo = this.todos.find(todo => todo.id === updatedTodo.id);
Object.assign(existingTodo, updatedTodo);
});
}
editTodo(todoData: Todo): void {
this.editing = true;
Object.assign(this.editingTodo, todoData);
}
clearEditing(): void {
this.editingTodo = new Todo();
this.editing = false;
}
}
todo.service.ts
import { Injectable } from '#angular/core';
import { Todo } from './todo';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class TodoService {
private baseUrl = 'http://localhost:8080';
constructor(private http: Http) { }
getTodos(): Promise<Todo[]> {
return this.http.get(this.baseUrl + '/api/todos/')
.toPromise()
.then(response => response.json() as Todo[])
.catch(this.handleError);
}
createTodo(todoData: Todo): Promise<Todo> {
console.log("inside service");
console.log(todoData);
console.log(todoData.numbers);
return this.http.post(this.baseUrl + '/api/todos/', todoData, "a")
.toPromise().then(response => response.json() as Todo)
.catch(this.handleError);
}
updateTodo(todoData: Todo): Promise<Todo> {
return this.http.put(this.baseUrl + '/api/todos/' + todoData.id, todoData)
.toPromise()
.then(response => response.json() as Todo)
.catch(this.handleError);
}
deleteTodo(id: string): Promise<any> {
return this.http.delete(this.baseUrl + '/api/todos/' + id)
.toPromise()
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('Some error occured', error);
return Promise.reject(error.message || error);
}
}
todo.ts
export class Todo {
id: string;
title: string;
numbers: string;
completed: boolean;
createdAt: Date;
}
Spring Boot:
TodoController
package com.example.todoapp.controllers;
import javax.validation.Valid;
import com.example.todoapp.models.Todo;
import com.example.todoapp.repositories.TodoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
#RequestMapping("/api")
#CrossOrigin("*")
public class TodoController {
#Autowired
TodoRepository todoRepository;
#GetMapping("/todos")
public List<Todo> getAllTodos() {
Sort sortByCreatedAtDesc = new Sort(Sort.Direction.DESC, "createdAt");
return todoRepository.findAll(sortByCreatedAtDesc);
}
#PostMapping("/todos")
public Todo createTodo(#Valid #RequestBody Todo todo, String numbers) {
System.out.println(todo.getNumber());
System.out.println(todo.getTitle());
System.out.println(numbers+ "numbers");
todo.setCompleted(false);
return todoRepository.save(todo);
}
#PostMapping("/contact")
public Todo createContact(#Valid #RequestBody Todo todo) {
todo.setCompleted(false);
return todoRepository.save(todo);
}
#GetMapping(value="/todos/{id}")
public ResponseEntity<Todo> getTodoById(#PathVariable("id") String id) {
return todoRepository.findById(id)
.map(todo -> ResponseEntity.ok().body(todo))
.orElse(ResponseEntity.notFound().build());
}
#PutMapping(value="/todos/{id}")
public ResponseEntity<Todo> updateTodo(#PathVariable("id") String id,
#Valid #RequestBody Todo todo) {
return todoRepository.findById(id)
.map(todoData -> {
todoData.setTitle(todo.getTitle());
todoData.setCompleted(todo.getCompleted());
Todo updatedTodo = todoRepository.save(todoData);
return ResponseEntity.ok().body(updatedTodo);
}).orElse(ResponseEntity.notFound().build());
}
#DeleteMapping(value="/todos/{id}")
public ResponseEntity<?> deleteTodo(#PathVariable("id") String id) {
return todoRepository.findById(id)
.map(todo -> {
todoRepository.deleteById(id);
return ResponseEntity.ok().build();
}).orElse(ResponseEntity.notFound().build());
}
}
TodoRepository
package com.example.todoapp.repositories;
import com.example.todoapp.models.Todo;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface TodoRepository extends MongoRepository<Todo, String> {
}
Todo
package com.example.todoapp.models;
import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection="todos")
#JsonIgnoreProperties(value = {"createdAt"}, allowGetters = true)
public class Todo {
#Id
private String id;
#NotBlank
#Size(max=100)
#Indexed(unique=true)
private String title;
#Size(max=100)
#Indexed(unique=false)
private String numbers;
private Boolean completed = false;
private Date createdAt = new Date();
public Todo() {
super();
}
public Todo(String title, String numbers) {
this.title = title;
this.numbers= numbers;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public String getNumber() {
return numbers;
}
public void setNumber(String number) {
this.numbers = number;
}
#Override
public String toString() {
return String.format(
"Todo[id=%s, title='%s',numbers='%s', completed='%s']",
id, title,numbers, completed);
}
}
Error from angular:
fff
todo-list.component.ts:32 NgForm {_submitted: true, ngSubmit: EventEmitter, form: FormGroup}
todo.service.ts:20 inside service
todo.service.ts:21 Todo {a: true, title: "My Web Application went blank on private mode", numbers: "fff"}
todo.service.ts:22 fff
Error From spring boot:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.0.RELEASE)
2018-11-10 16:13:21.940 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : Starting TodoappApplication on NCS-180417AV05 with PID 9436 (E:\Project\portfolio_website\templates\spring-boot-mongodb-angular-todo-app-master\spring-boot-backendv2\target\classes started by royyzh in E:\Project\portfolio_website\templates\spring-boot-mongodb-angular-todo-app-master\spring-boot-backendv2)
2018-11-10 16:13:21.944 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : No active profile set, falling back to default profiles: default
2018-11-10 16:13:21.992 INFO 9436 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#327b636c: startup date [Sat Nov 10 16:13:21 SGT 2018]; root of context hierarchy
2018-11-10 16:13:23.367 INFO 9436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2018-11-10 16:13:23.393 INFO 9436 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2018-11-10 16:13:23.393 INFO 9436 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.28
2018-11-10 16:13:23.399 INFO 9436 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jre1.8.0_181\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:/Program Files/Java/jre1.8.0_181/bin/server;C:/Program Files/Java/jre1.8.0_181/bin;C:/Program Files/Java/jre1.8.0_181/lib/amd64;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\TortoiseSVN\bin;C:\Program Files\PuTTY\;C:\Program Files\Microsoft VS Code\bin;C:\Program Files\Git\cmd;C:\apache-maven-3.5.4\bin;C:\curl;C:\Program Files\nodejs\;D:\eclipes java ee\mongodb-win32-x86_64-2008plus-ssl-4.0.3\bin;C:\Users\royyzh\AppData\Roaming\npm;C:\Users\royyzh\AppData\Local\Programs\EmEditor;D:\sts-bundle\sts-3.9.5.RELEASE;;.]
2018-11-10 16:13:23.692 INFO 9436 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-11-10 16:13:23.693 INFO 9436 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1705 ms
2018-11-10 16:13:23.792 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-11-10 16:13:23.797 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-11-10 16:13:23.798 INFO 9436 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-11-10 16:13:24.698 INFO 9436 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], mode=MULTIPLE, requiredClusterType=REPLICA_SET, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500, requiredReplicaSetName='RoyYipProjectCluster-shard-0'}
2018-11-10 16:13:24.698 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:24.746 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:24.747 INFO 9436 --- [ main] org.mongodb.driver.cluster : Adding discovered server royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017 to client view of cluster
2018-11-10 16:13:25.123 INFO 9436 --- [ main] org.mongodb.driver.cluster : No server chosen by com.mongodb.Mongo$4#2e52fb3e from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
2018-11-10 16:13:25.138 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:4829}] to royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.149 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=9102165, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621241304334}
2018-11-10 16:13:25.158 INFO 9436 --- [ main] org.mongodb.driver.cluster : No server chosen by WritableServerSelector from cluster description ClusterDescription{type=REPLICA_SET, connectionMode=MULTIPLE, serverDescriptions=[ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=UNKNOWN, state=CONNECTING}, ServerDescription{address=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=9102165, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621241304334}]}. Waiting for 30000 ms before timing out
2018-11-10 16:13:25.201 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:4482}] to royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.204 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:4726}] to royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.209 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_SECONDARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=7415729, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=null, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621301859146}
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, type=REPLICA_SET_PRIMARY, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 0, 4]}, minWireVersion=0, maxWireVersion=7, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=5801588, setName='RoyYipProjectCluster-shard-0', canonicalAddress=royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, hosts=[royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-01-uwgni.gcp.mongodb.net:27017, royyipprojectcluster-shard-00-02-uwgni.gcp.mongodb.net:27017], passives=[], arbiters=[], primary='royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017', tagSet=TagSet{[]}, electionId=7fffffff0000000000000005, setVersion=1, lastWriteDate=Sat Nov 10 16:13:26 SGT 2018, lastUpdateTimeNanos=33621302845567}
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max election id to 7fffffff0000000000000005 from replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Setting max set version to 1 from replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.210 INFO 9436 --- [ngodb.net:27017] org.mongodb.driver.cluster : Discovered replica set primary royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.296 INFO 9436 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:4, serverValue:4726}] to royyipprojectcluster-shard-00-00-uwgni.gcp.mongodb.net:27017
2018-11-10 16:13:25.698 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#327b636c: startup date [Sat Nov 10 16:13:21 SGT 2018]; root of context hierarchy
2018-11-10 16:13:25.763 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/contact],methods=[POST]}" onto public com.example.todoapp.models.Todo com.example.todoapp.controllers.TodoController.createContact(com.example.todoapp.models.Todo)
2018-11-10 16:13:25.765 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.getTodoById(java.lang.String)
2018-11-10 16:13:25.766 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos],methods=[POST]}" onto public com.example.todoapp.models.Todo com.example.todoapp.controllers.TodoController.createTodo(com.example.todoapp.models.Todo,java.lang.String)
2018-11-10 16:13:25.767 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos],methods=[GET]}" onto public java.util.List<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.getAllTodos()
2018-11-10 16:13:25.767 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[PUT]}" onto public org.springframework.http.ResponseEntity<com.example.todoapp.models.Todo> com.example.todoapp.controllers.TodoController.updateTodo(java.lang.String,com.example.todoapp.models.Todo)
2018-11-10 16:13:25.768 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/todos/{id}],methods=[DELETE]}" onto public org.springframework.http.ResponseEntity<?> com.example.todoapp.controllers.TodoController.deleteTodo(java.lang.String)
2018-11-10 16:13:25.771 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-11-10 16:13:25.771 INFO 9436 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-11-10 16:13:25.793 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.793 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.840 INFO 9436 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-11-10 16:13:25.995 INFO 9436 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-11-10 16:13:26.060 INFO 9436 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-11-10 16:13:26.064 INFO 9436 --- [ main] com.example.todoapp.TodoappApplication : Started TodoappApplication in 4.443 seconds (JVM running for 6.802)
2018-11-10 16:13:32.981 INFO 9436 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-11-10 16:13:32.981 INFO 9436 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-11-10 16:13:33.000 INFO 9436 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms
null
My Web Application went blank on private mode
nullnumbers
null
My Web Application went blank on private mode
nullnumbers
What should I do to make it work? Which part of my code needs to be changed and why?
There are a few mistakes. Here are the fixes you need to make.
this.http.post(this.baseUrl + '/api/todos/', todoData, "a")
What is the "a" doing in the POST call. You can remove that in createTodo method declared in todo.service.ts
In Todo.java the variable is declared as numbers and the setter is declared as
public void setNumber(String number) {
Change this to
public void setNumbers(String numbers) {
this.numbers = numbers;
}
Now you can update createTodo method in TodoController.java to the following
#PostMapping("/todos")
public Todo createTodo(#Valid #RequestBody Todo todo) {
I'm using NamedParameterJdbcTemplate,below SQL works well in Oraclie SQL Developer.
select sum(PRINTEDLICNUM), sum(PRINTEDLICCOPYNUM), PRIPID from LICENSEPRINTRECORD where PRIPID in ('370212230027855') GROUP BY PRIPID;
But this code not works in NamedParameterJdbcTemplate
Map namedParameters = Collections.singletonMap("pripids", pripIds);
StringBuffer recordQueryString = new StringBuffer();
recordQueryString.append("SELECT SUM(PRINTEDLICNUM), SUM(PRINTEDLICCOPYNUM), PRIPID from LICENSEPRINTRECORD where PRIPID in (:pripids) GROUP BY PRIPID");
List<PreviousPrintRecords> records = template.query(recordQueryString.toString(), namedParameters, new RowMapper<PreviousPrintRecords>());
Below is my RowMapper Class:
public class PreviousPrintRecords implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3763072257141955974L;
private int printedLicNum;
private int printedLicCopyNum;
private String pripId;
public PreviousPrintRecords() {
super();
}
public PreviousPrintRecords(int printedLicNum, int printedLicCopyNum, String pripId) {
super();
this.printedLicNum = printedLicNum;
this.setPrintedLicCopyNum(printedLicCopyNum);
this.pripId = pripId;
}
public int getPrintedLicNum() {
return printedLicNum;
}
public void setPrintedLicNum(int printedLicNum) {
this.printedLicNum = printedLicNum;
}
public String getPripId() {
return pripId;
}
public void setPripId(String pripId) {
this.pripId = pripId;
}
public int getPrintedLicCopyNum() {
return printedLicCopyNum;
}
public void setPrintedLicCopyNum(int printedLicCopyNum) {
this.printedLicCopyNum = printedLicCopyNum;
}
}
It will occurs error, nested exception is java.sql.SQLException: Invalid column name
below is detailed trace:
10:48:09,477 INFO [stdout] (DefaultThreadPoolService1) 2018-05-15 10:48:09 INFO o.s.j.support.SQLErrorCodesFactory - SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase, Hana]
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) 2018-05-15 10:48:09 ERROR c.a.p.a.task.GetLicenseItemListTask - Get licenseitem task occurs error org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT SUM(PRINTEDLICNUM), SUM(PRINTEDLICCOPYNUM), PRIPID from LICENSEPRINTRECORD where PRIPID in (?, ?, ?, ?, ?, ?, ?) GROUP BY PRIPID]; nested exception is java.sql.SQLException: Invalid column name
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73)
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649)
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684)
10:48:09,532 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:711)
10:48:09,533 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:761)
10:48:09,533 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192)
10:48:09,533 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:199)
10:48:09,534 INFO [stdout] (DefaultThreadPoolService1) at com.aw.product.abp.licenseprint.service.DaoLicensePrintService.requestLicensePrintItemData(DaoLicensePrintService.java:167)
10:48:09,534 INFO [stdout] (DefaultThreadPoolService1) at com.aw.product.abp.task.GetLicenseItemListTask.run(GetLicenseItemListTask.java:85)
10:48:09,534 INFO [stdout] (DefaultThreadPoolService1) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
10:48:09,534 INFO [stdout] (DefaultThreadPoolService1) at java.util.concurrent.FutureTask.run(FutureTask.java:266)
10:48:09,534 INFO [stdout] (DefaultThreadPoolService1) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
10:48:09,535 INFO [stdout] (DefaultThreadPoolService1) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
10:48:09,535 INFO [stdout] (DefaultThreadPoolService1) at java.lang.Thread.run(Thread.java:745)
10:48:09,535 INFO [stdout] (DefaultThreadPoolService1) Caused by: java.sql.SQLException: Invalid column name
10:48:09,535 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
10:48:09,535 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:133)
10:48:09,537 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:199)
10:48:09,539 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:263)
10:48:09,539 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:271)
10:48:09,539 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:445)
10:48:09,539 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.OracleStatement.getColumnIndex(OracleStatement.java:3367)
10:48:09,540 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.OracleResultSetImpl.findColumn(OracleResultSetImpl.java:2009)
10:48:09,540 INFO [stdout] (DefaultThreadPoolService1) at oracle.jdbc.driver.OracleResultSet.getString(OracleResultSet.java:494)
10:48:09,540 INFO [stdout] (DefaultThreadPoolService1) at org.jboss.jca.adapters.jdbc.WrappedResultSet.getString(WrappedResultSet.java:1381)
10:48:09,540 INFO [stdout] (DefaultThreadPoolService1) at com.aw.product.abp.licenseprint.service.DaoLicensePrintService$2.mapRow(DaoLicensePrintService.java:173)
10:48:09,540 INFO [stdout] (DefaultThreadPoolService1) at com.aw.product.abp.licenseprint.service.DaoLicensePrintService$2.mapRow(DaoLicensePrintService.java:1)
10:48:09,541 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:93)
10:48:09,541 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.RowMapperResultSetExtractor.extractData(RowMapperResultSetExtractor.java:60)
10:48:09,541 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:697)
10:48:09,543 INFO [stdout] (DefaultThreadPoolService1) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633)
10:48:09,543 INFO [stdout] (DefaultThreadPoolService1) ... 12 more
Does NamedParameterJdbcTemplate not support sum function?
If I wanna use sum function, is there any way to achieve this?
java.sql.SQLException: Invalid column name
The exception is clear enough. You properly named your table column name in the wrong way.
You are using rowMapper class, but you not define the column name.
Change your code as below
recordQueryString.append("SELECT SUM(PRINTEDLICNUM) AS printedLicNum, SUM(PRINTEDLICCOPYNUM) AS printedLicCopyNum, PRIPID from LICENSEPRINTRECORD where PRIPID in (:pripids) GROUP BY PRIPID");
i use smartgwt 2.5. i have a databound treegrid which fetches a json from the database and builds the tree. this works fine. the problem is when i try to reparent for example
at begin the tree looks like:
my json that is fetched from the db:
[{"id":"a","ReportsTo":"root","isFolder":"true","isOpen":"false"},{"id":"b","ReportsTo":"c","isFolder":"false", "isOpen":"false"},{"id":"c","ReportsTo":"root","isFolder":"true","isOpen":"true"},{"id":"d","ReportsTo":"a","isFolder":"false","isOpen":"false"}]
after reparent b (drag b at folder c and drop it into c) all leafs gets folders:
http://i.stack.imgur.com/lLHdX.png
this is send to the server:
{
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "dataSource":"isc_RestDataSource_0",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "operationType":"update",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "data":{
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "id":"b",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "ReportsTo":"c",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "isFolder":false,
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "isOpen":"false"
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) },
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "oldValues":{
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "id":"b",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "ReportsTo":"a",
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "isFolder":false,
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) "isOpen":"false"
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) }
12:46:52,773 INFO [stdout] (http--127.0.0.1-7443-4) }
after site refresh the tree is displayed correctly:
a
c
-b
-d
my code for the treegrid:
public class FavoritesGrid extends TreeGrid {
public FavoritesGrid() {
setWidth("12%");
setShowConnectors(false);
setShowResizeBar(true);
setCanReorderRecords(true);
setCanAcceptDroppedRecords(true);
setCanDragRecordsOut(true);
setCanReparentNodes(true);
setDragDataAction(DragDataAction.MOVE);
setAutoSaveEdits(false);
setAutoFetchData(false);
setLoadDataOnDemand(false); //load everything
setHeight("50%");
RestDataSource ds = new RestDataSource();
ds.setRecordXPath("/");
ds.setDataFormat(DSDataFormat.JSON);
OperationBinding fetch = new OperationBinding();
fetch.setOperationType(DSOperationType.FETCH);
fetch.setDataProtocol(DSProtocol.POSTMESSAGE);
fetch.setDataFormat(DSDataFormat.JSON);
OperationBinding add = new OperationBinding();
add.setOperationType(DSOperationType.ADD);
add.setDataProtocol(DSProtocol.POSTMESSAGE);
add.setDataFormat(DSDataFormat.JSON);
OperationBinding update = new OperationBinding();
update.setOperationType(DSOperationType.UPDATE);
update.setDataProtocol(DSProtocol.POSTMESSAGE);
update.setDataFormat(DSDataFormat.JSON);
ds.setOperationBindings(fetch, update, add);
ds.setDataURL("/Kronos/Favorites");
DataSourceTextField key = new DataSourceTextField("id", "id");
key.setPrimaryKey(true);
key.setRequired(true);
DataSourceTextField parent = new DataSourceTextField("ReportsTo",
"ReportsTo");
parent.setRequired(true);
parent.setForeignKey("id");
parent.setRootValue("root");
ds.setFields(key, parent);
//define properties
Tree tree = new Tree();
tree.setDefaultIsFolder(false); //default the nodes should be leafs
tree.setRootValue("root");
tree.setNameProperty("id");
tree.setIdField("id");
tree.setParentIdField("ReportsTo");
//the setOpenProperty also doesn't work
//if i set it smartgwt displays all folder opened
tree.setOpenProperty("isOpen");
//setIsFolderProperty is being ignored after reparent, need to refresh the site for correction
tree.setIsFolderProperty("isFolder");
setDataProperties(tree);
setDataSource(ds);
fetchData();
}
}
can somebody pls help me?