Posts

Showing posts with the label spring-boot

Spring Boot include ID field in json

Image
Clash Royale CLAN TAG #URR8PPP Spring Boot include ID field in json Propably it's very simple but everything what I found is related to Spring Data Rest. I'm using "spring-boot-starter-web" and I can't found any solution... Here is my entity clas: @Entity @Table(name = "buses") class Bus( @Id @JsonProperty("sideNumber") @JsonInclude private val sideNumber: Int, @NotBlank var longitude: Double, @NotBlank var latitude: Double ) I tried to annotate sideNumber(Id) property with @JsonInclude and @Jsonproperty but with no luck. In my json reponse I only get longitude and latitude... My controller looks like that. @RestController @RequestMapping("/api") class BusController { @Autowired private lateinit var busRepository: BusRepository @GetMapping("/buses") fun getAllBuses(): List<Bus> { return busRepository.findAll() } @PostMapping("/buses") fun cre...

How to create Spring Cloud Config Client with env specific configuration?

Image
Clash Royale CLAN TAG #URR8PPP How to create Spring Cloud Config Client with env specific configuration? I have facing an issue with Spring Cloud Config Server and Eureka Server Profiling. Let's say I have 3 services with their name ("spring.application.name") as : myapp-svc myapp-spring-cloud-config-svc myapp-spring-eureka-svc I want to deploy each service in 2 regions ( dev and prod ). In Dev region, each service will run on localhost and in prod it will have some different url. 'myapp-spring-cloud-config-svc' in dev region will point to local git repo, while in prod region it will point to remote git repo. I can have 2 configurations: 1) When I start 'myapp-svc' service in local, it should connect to 'myapp-spring-cloud-config-svc' in dev. I can do this by setting spring.cloud.config.uri = <url of config svc in Dev>. But the issue with this set up is that the property needs to be defined in bootstrap.properties. So, If deploy 'm...

Connection refused during running app on docker - Spring Boot & mssql server

Image
Clash Royale CLAN TAG #URR8PPP Connection refused during running app on docker - Spring Boot & mssql server I'm start to play with Docker. I'm trying to run Spring Boot application on Docker which connects with mssql-server-linux on docker. I'm configure and run mssql server. My app has set database port and when I run this app in IntelliJ everything is ok. Also when I build app './mvnw install dockerfile:build' command everything is ok. Also adds entity to database during build. When I try run app 'docker run' command I get this exception: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.". What's the problem? My spring boot app prop...

401 status error on API request

Image
Clash Royale CLAN TAG #URR8PPP 401 status error on API request I always get this error when trying to implement simple web service that displays just a msg (angular5 + spring boot) this is the error :vendor.bundle.js:62557 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: "OK", url: "localhost:8080/hello";, ok: false, …} error : "... headers : HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message : "Http failure response for localhost:8080/hello: 401 OK" name : "HttpErrorResponse" ok : false status : 401 statusText : "OK" url : "localhost:8080/hello"; this is my simple code: controller.java: @GetMapping("/hello") public String sayhello(){ return "{"message": "Hello, world!"}";} } hello.component.ts: import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpParams } from ...

ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: “OK”, url: “http://localhost:8080/hello”, ok: false, …}

Image
Clash Royale CLAN TAG #URR8PPP ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: “OK”, url: “http://localhost:8080/hello”, ok: false, …} I alwaaays get this error when trying to implement simple web service that display just a msg (angular5 + spring boot) the error shown is in this img this is my simple code: controller.java: @GetMapping("/hello") public String sayhello(){ return "{"message": "Hello, world!"}";} } hello.component.ts: import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpErrorResponse, HttpParams } from '@angular/common/http'; import { Observable } from 'rxjs/Rx'; import { Adresse } from '../shared/adresse'; @Component({ selector: 'app-forgot', templateUrl: './forgot.component.html', styleUrls: ['./forgot.component.css'] }) export class ForgotComponent implements OnInit { ...

ManyToOne referenced entities not exist in JSON Response when returning PagedResource

Image
Clash Royale CLAN TAG #URR8PPP ManyToOne referenced entities not exist in JSON Response when returning PagedResource When I return a Page<Entity> from a method inside my @RestController class, all fields of Entity both referenced via @OneToXXX and @ManyToXXX take place in the returned JSON object. But when I switched the return type to PagedResource (to be able to add links to the response), @ManyToXXX fields are not included at all. Page<Entity> @RestController Entity @OneToXXX @ManyToXXX PagedResource @ManyToXXX Here is the method in question: @GetMapping("/fetch") public PagedResources getResults(Pageable pageable, PagedResourcesAssembler assembler) { Page<ParentClass> page = myRepository.findAll(pageable); PagedResources pagedResources = assembler.toResource(page, myResourceAssembler); return pagedResources; } Here are the basic class definitions: ParentClass @Entity @Table(name = "parent_table", catalog = "...

Spring Rest Api Design For Following a User in Twitter Clone Appliction?

Image
Clash Royale CLAN TAG #URR8PPP Spring Rest Api Design For Following a User in Twitter Clone Appliction? i Want to Design a Demo Twitter Clone Application where user can follow any other user . however i am doubting my rest api design . please suggest me am i right . can we pass followerId in url rather than passing it as requestbody ? and if better option could be there like put/patch or any rest api design ? Here JwtUser is Authenticated User public class FollowerDto { @NotBlank private Long followerId; private boolean following; public FollowerDto() { } public FollowerDto(Long followerId, boolean following) { this.followerId = followerId; this.following = following; } public boolean getFollowing() { return following; } public void setFollowing(boolean following) { this.following = following; } public Long getFollowerId() { return followerId; } public void setFollowerId(Long followerId) { this.followerId = followerId; } } @PostMapping("/follower"...

Spring Batch restart uncompleted jobs from the same execution and step

Image
Clash Royale CLAN TAG #URR8PPP Spring Batch restart uncompleted jobs from the same execution and step I use the following logic to restart the Spring Batch uncompleted(for example after application abnormal termination) jobs: public void restartUncompletedJobs() { LOGGER.info("Restarting uncompleted jobs"); try { jobRegistry.register(new ReferenceJobFactory(documetPipelineJob)); List<String> jobs = jobExplorer.getJobNames(); for (String job : jobs) { Set<JobExecution> runningJobs = jobExplorer.findRunningJobExecutions(job); for (JobExecution runningJob : runningJobs) { runningJob.setStatus(BatchStatus.FAILED); runningJob.setEndTime(new Date()); jobRepository.update(runningJob); jobOperator.restart(runningJob.getId()); LOGGER.info("Job restarted: " + runningJob); } } } catch (Exception e) { ...

No qualifying bean of type Error in Junit test

Image
Clash Royale CLAN TAG #URR8PPP No qualifying bean of type Error in Junit test I am trying to connect two different data source using spring boot version 2.0.3. One is pointing to the MySQL and another is PostgreSQL. MySQL passed every test. But problem with the PostgreSQL. Here is the Entity class that should be mapped to PostgreSQL. @Entity @Table(name = "order") @Data @NoArgsConstructor @AllArgsConstructor public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String productName; } This is the configuration class for PostgreSQL. @Configuration @EnableJpaRepositories( basePackageClasses = Order.class, entityManagerFactoryRef = "orderEntityManager", transactionManagerRef = "orderTransactionManager" ) @PropertySource("classpath:application.properties") public class OrderConfig { @Autowired Environment env; @Bean public DataSource getDataSource() { DriverManagerDataSource dataSo...

rest template exchange method null pointer exception

Image
Clash Royale CLAN TAG #URR8PPP rest template exchange method null pointer exception I am trying the hit the url with rest template exchange but getting null pointer exception at point of executing resttemplate.exchange method.Can you please let me know why i am getting the below null pointer exception I am trying the hit the url with rest template exchange but getting null pointer exception at point of executing resttemplate.exchange method.Can you please let me know why i am getting the below null pointer exception I am trying the hit the url with rest template exchange but getting null pointer exception at point of executing resttemplate.exchange method.Can you please let me know why i am getting the below null pointer exception I am trying the hit the url with rest template exchange but getting null pointer exception at point of executing resttemplate.exchange method.Can you please let me know why i am getting the below null pointer exception I am trying the hit the url with rest te...

Spring Boot + Angular 4 + Social and Local Login

Image
Clash Royale CLAN TAG #URR8PPP Spring Boot + Angular 4 + Social and Local Login I have been searching for the best way to build an application using Angular 4 (client application running over apache2), Spring Boot (Rest Controller) and Social and Local login. I am kinda new to all of this, and I've be looking around for about one month and still have not a good idea how to implement that! Couldnt find a good tutorial for the tecnologies mentioned above... I need to be able to let the user login via system's own login and social login like facebook and google. Could someone please point at the right direction? I am not sure if that I am on the right track... I thought that would be easy, but I feel very confuse and dont see how to integrate the response from spring with my angular application. And the login with social networks will not be direct with the angular application. The user will authenticate with facebook, for example, and when facebook redirect to spring, Ill retriev...

Displaying image in spring boot from system directory

Image
Clash Royale CLAN TAG #URR8PPP Displaying image in spring boot from system directory I am working with spring boot I want to display image from my system directory in html page but i cannot do that. Any can help me please. This is my html code <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <img alt="no image" src="D:imagesfav-icon"> </body> I tried the following code also but it is not working <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <img alt="no data" th:src="@{D:images1r-product-6.jpg}"> </body> </html> By clicking "P...

How to wait particular up to particular time limit until get response from rest service

Image
Clash Royale CLAN TAG #URR8PPP How to wait particular up to particular time limit until get response from rest service In my code i am calling one external web service to get response by using HTTP Client Get request. Here the service may delay up to 5 mins to give the response. So i have to do below things. 1. want to set request timeout(No idea how to do it) 2. call the service and set the time limit up to what time it can wait for response(In my case i want to set time limit for 5 mins) can any one suggest me how can i achieve this 2 things. Thanks, Sudheer I am able to find how to set request time out i am using PoolingHttpClientConnectionManager ConnManager = new PoolingHttpClientConnectionManager(timeToLive,TimeUnit.MINUTES); . Stil no clue how to wait until get the response. – user3853393 Jul 25 at 16:12 ...

java.lang.IllegalStateException: No primary constructor found for java.util.List

Image
Clash Royale CLAN TAG #URR8PPP java.lang.IllegalStateException: No primary constructor found for java.util.List My project based on spring boot,Thymeleaf,mysql,html and Jquery. I tried to post a List of EntSetCharges type data to the @controller ,but it is not succeed..it trows error like java.lang.IllegalStateException: No primary constructor found for java.util.List Previously i worked with this error org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'chargesName' cannot be found on null Now i got another error in same page Here is my full code... <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <!-- bootstrap css lib --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <!-- Bootstrap...

Spring Profiles application properties order

Image
Clash Royale CLAN TAG #URR8PPP Spring Profiles application properties order We have many environments that have multiple active Spring profiles, but what is the precedence of the application-{profile}.yml files? If I have spring.profiles.active=test-us-west-2-p1, test-us-west-2, test spring.profiles.active=test-us-west-2-p1, test-us-west-2, test In what order do the files application-test.yml, application-test-us-west-2.yml, application-test-us-west-2-p1.yml get loaded? If I have the same property in each file, which "wins"? application-test.yml, application-test-us-west-2.yml, application-test-us-west-2-p1.yml Also, has this changed from Spring-Boot 1.5.x to 2.x? It seems like it may have. 1 Answer 1 The profile's properties are loaded in the same order as you specify them, and if the same property is defined in different profiles the last one wins. This behavior applies to both Sp...

Why is my Spring Boot Service test returning a NullPointerException?

Image
Clash Royale CLAN TAG #URR8PPP Why is my Spring Boot Service test returning a NullPointerException? Lately I have been trying to test my Spring Boo(2.0.3) Service, but I have been receiving a NullPointerException. The userDAOImpl implements the userDAO interface, Here is the serviceImpl class, it implements the interface Service: import app.clothapp.DAO.UserDAO; import app.clothapp.Model.User; import app.clothapp.Service.UserService; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Service public class UserServiceImpl implements UserService { Logger logger = LogManager.getLogger("UserServiceImplLogger"); @Autowired private UserDAO userDao; @Override @Transactional public void createUser(User user) { logger.debug(...