Posts

Showing posts with the label spring-boot

REST API request using Hibernate relationships

REST API request using Hibernate relationships Rest Controller: @PostMapping("transaction") public ResponseEntity<Transaction> init(@RequestBody Transaction transactionInput) { Transaction transaction = transactionRepository.save(transactionInput); return new ResponseEntity<>(transaction, HttpStatus.OK); } Transaction Entity: @Getter @Setter @Entity @NoArgsConstructor @AllArgsConstructor @DynamicInsert @DynamicUpdate @Table(name = "transaction") public class Transaction { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false) @JoinColumn(name="currency_id") private Currency currency; Currency Entity: @Entity @NoArgsConstructor @AllArgsConstructor @Getter @Setter @DynamicInsert @DynamicUpdate @Table(name = "currency") public class Currency { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) priv...

How to produce metrics of URI correctly in spring boot 2 + webflux

How to produce metrics of URI correctly in spring boot 2 + webflux I have a problem using spring boot 2.0.3 + spring webflux (functional endpoints) + metrics. According to the official doc: The generated metrics of uri should be the request’s URI template prior to variable substitution Which means instead of /api/person/123, the generated metrics of URI should be something like /api/person/{id}. However, when I query those metrics on my spring boot app with this link http://localhost:8080/actuator/metrics/http.server.requests, I got these URIs: /api/person/2 /api/person/33 /api/person/12 To reproduce this issue, I put a sample code here: https://gitlab.com/itsleon/demo Can someone please shed some light on this issue? Thanks in advance! 1 Answer 1 There's an open issue for that in Spring Boot. Currently, Spring WebFlux fn doesn't provide the information about the URI pattern that matched fo...

Spring Boot Application failed to start with classpath: []

Spring Boot Application failed to start with classpath: I generated a Spring Boot application with jHipster, added some code from my previous project (non-jhipster project) and tried to run it using IDEA. First I got an error message similar to this, saying "Command line is too long.." (I am running Windows 10 x64). I clicked enable, but then I got an error like this.: "C:Program FilesJavajdk1.8.0_144binjava" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:51351,suspend=y,server=n -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=51350 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true -Dfile.encoding=UTF-8 -classpath C:UsersUserAppDataLocalTempclasspath.jar com.test.pc.TestPartsComposerApp Connected to the target VM, address: '127.0.0.1:51351', transport...

Change the file name in Audit4j

Change the file name in Audit4j I am using Audit4j for audit logging purpose. It generates the file in the given path with the name Audit_Log_yyyy_mm-dd format. I want to change the file name as MyFileName_yyyy-mm-dd . Is it possible to do this ?. I have tried to set the file prefix using the following code. But it did not work. FileAuditHandler fileAuditHandler = new FileAuditHandler(); fileAuditHandler.setPath(AUDIT_FILE_LOCATION); fileAuditHandler.setAuditFilePrefix(applicationName); Please help me to fix this ? By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

How to serialize a json containing LAZY associations

How to serialize a json containing LAZY associations I am having an Person entity which has @ManyToOne association with Contact entity with fetch type LAZY. I am using spring-boot to expose REST API. One of my POST call contains nested JSON to save the parent entity Person along with association Contact Person @ManyToOne Contact Person Contact Since Contact fetch type is LAZY, I am encountering into following exception Contact ERROR 17415 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path threw exception [Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and ...

actuator /refresh is not being provided in SpringBoot 2.0.1

actuator /refresh is not being provided in SpringBoot 2.0.1 I am creating a demo project for Spring-Config-Server and Spring-Config-Client . Spring-Config-Server Spring-Config-Client In SpringBoot 1.5.6.RELEASE everything is working fine. SpringBoot 1.5.6.RELEASE However, when I am upgrading project to 2.0.1.RELEASE it does not provide the actuator endpoints. 2.0.1.RELEASE Actuator endpoint provided in 1.5.6.RELEASE Mapped "{[/refresh || /refresh.json],methods=[POST]}" Mapped "{[/dump || /dump.json],methods=[GET] Mapped "{[/heapdump || /heapdump.json],methods=[GET] Mapped "{[/autoconfig || /autoconfig.json],methods=[GET] Mapped "{[/resume || /resume.json],methods=[POST]}" Mapped "{[/configprops || /configprops.json],methods=[GET] Mapped "{[/features || /features.json],methods=[GET] Mapped "{[/loggers/{name:.*}],methods=[GET] Mapped "{[/restart || /restart.json],methods=[POST]}" ...and many more Actuator endpoint provided in...

How to allow anonymous users to access a certain function only using spring security

How to allow anonymous users to access a certain function only using spring security I'm using spring security in my project. I have a condition where the anonymous users should be able to read from database whereas only authorized users to add/update/delete. How can we mention such situation in the security-config? .antMatchers("/user/**").permitAll() permit all requires to be authenticated but I want even none authenticated users to access via the GET method. @RequestMapping("/user") @PreAuthorize("hasAuthority('USER')") public List<UserAll> getAll() { return userService.getAll(); } And here how do I mention that this function should be accessed by anonymous users too? you can change to hasAnyRole('USER', 'ANONYMOUS') – fg78nc Jul 2 at 4:18 hasAnyR...

Spring Boot serialize parameteried type into JSON with type id

Spring Boot serialize parameteried type into JSON with type id Spring Boot sample project: https://github.com/yejianfengblue/spring-boot-jackson-serialize-generic-type I have question in how Spring Boot serializes generic type into JSON with Jackson library. Please see my demo: Fruit is a common interface of Apple and Banana . Fruit Apple Banana BasketController has 3 RESTful API: BasketController getFruitList() List<Fruit> getFruitBasket() FruitBasket List<Fruit> getBasketOfFruit() Basket<Fruit> List<T> In BasketController , I log the JSON string written from Jackson Object Mapper and Object Writer . Please see the actual output in the comment below the log statement. BasketController BasketController.java /** <li>Object<b>Mapper</b>.writeValueAsString, @type is lost due to java type erasure. * <li>Object<b>Writer</b>.writeValueAsString, @type is kept */ @GetMapping(path = "getFruitList") public List<Fruit...

Spring boot security login verify failed

Spring boot security login verify failed I want to verify the user's identity when he or she send a localhost:8080/submit request, so I added the following to SecurityConfig class: localhost:8080/submit @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/submit").access("hasRole('WORKER')") .antMatchers("/**").permitAll() .and() .formLogin() .loginPage("/login") .and() .logout() .logoutSuccessUrl("/") .and() .rememberMe() .tokenValiditySeconds(4838400) .key("workerKey"); } I wish the page could redirect to localhost:8080/login when I input localhost:8080/submit in the address field. My Worker entity has the role "WORKER": localhost:8080/login localhost:8080/submit @Override public Col...

Spring Boot Embedded Tomcat Performance

Spring Boot Embedded Tomcat Performance I am developing Microservices API for my application. I started with Spring Boot application. I created two artifacts - "business code with embedded tomcat" and "business code without embedded tomcat" . When I compare the performance results, I can see that the "non-embedded tomcat" (i.e. executing on standalone tomcat) gives good output because of native execution. So basically what is the difference between the embedded tomcat and the standalone tomcat regarding implementation? How the performance varies between two executions? How you did the tests? Could you explain? Thanks. – Rudge Oct 30 '16 at 18:46 @Rudge: Using Jmeter i simulated load on both scenarios. I am using camel in my business-code. At the end of transaction, i am printin...

Spring boot 2.0 custom converter being ignored

Spring boot 2.0 custom converter being ignored I've either completely miss-understood converters, or all the examples/blogs/docs I've found are assuming I've done a step... My understanding is that when I post a String , the converter will pick it up and give the Controller a POJO instead. String Controller The problem I have is the converter is never being called. The payload coming into the controller is a standard JSON API string { "data":{ "attributes":{ "created-date":null, }, "type":"steaks" } } The converter: @Slf4j @Configuration public class SteakConverter implements Converter<String, Steak> { @Override public Steak convert(String value) { log.info("converter value {}", value); return new Steak.builder().build(); } } The controller: @Slf4j @CrossOrigin @RestController public class SteakController { @PostMapping("/steaks") ...

IgnoreCase Finder Not Working with Spring Data Rest and Neo4J

IgnoreCase Finder Not Working with Spring Data Rest and Neo4J I am unable to coax Spring Data Neo4J (with Spring Data Rest) to ignore case with a finder method. Here's an example repository: @RepositoryRestResource public interface WidgetRepository extends PagingAndSortingRepository<Widget, Long> { Optional<Widget> findByNameIgnoreCase(String name); } This example will only find widgets by exact case even though I have the IgnoreCase keyword. I would appreciate advice on how to get a finder method to ignore case with Neo4J. Thanks! IgnoreCase 1 Answer 1 The case specific keywords are not implemented in Spring Data Neo4j yet. But it is possible to use regex in a derived query method. Define a regex finder method Optional<Widget> findByNameMatchesRegex(String name); Optional<Widget> findByNameMatchesRegex(String name); and use it like this widgetRepository.findByNameMa...

Using Pebble template engine with Spring Boot

Using Pebble template engine with Spring Boot So I'm trying to integrate Pebble templating engine to my spring boot application but I'm confused on how to implement this. So I've read through their site on how to implement it however it says for Spring MVC which I think not similar with Spring Boot. I also go to their github page then trying to add their maven dependency to POM.xml but I don't know if I will configure something or it is the same as Thymeleaf or Mustache that are autoconfigured. Link to their site: http://mitchellbosecke.com/pebble/ They provide an example on their github that you can try, to get an idea of how it works: github.com/PebbleTemplates/pebble-example-spring – Dovmo May 14 at 3:17 1 Answer 1 Add the starter depe...

Getting NullPointerException when tried to read @Autowired configuration object [duplicate]

Image
Getting NullPointerException when tried to read @Autowired configuration object [duplicate] This question already has an answer here: I am trying to read some properties from application.properties . I have created a configuration class with @Component and @ConfigurationProperties annotations. application.properties @Component @ConfigurationProperties When I am trying to access the configuration from a controller class, its working fine. But when I am trying to access the configuration from one component class, its throwing a null pointer exception. Following are the application.properties and classes. application.properties application.properties elasticsearch.ip=localhost InputManagementController.java @RestController public class InputManagementController { @Autowired private Configuration configuration; @GetMapping("/crawler/start") public String start(){ try{ System.out.println(configuration.getIp()); ----> getting value localhos...

How compare date in spring mongo

How compare date in spring mongo I want to fetch result bw two date in Mongo and spring but it show parse exception. If I pass like date as string then no result. How compare date in spring and Mongo application. Aggregation.match(Criteria.where("date").gte(new Date("2018-06-24")).lte(new Date("2018-06-30"))); My collection: { "_id" : ObjectId("5b34a31a68f1b041aa13b82f"), "date" : ISODate("2018-06-28T00:00:00Z"), "eventname" : "app open" } 1 Answer 1 You can try something like: DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = df.parse("2018-06-24"); Date endDate = df.parse("2018-06-30"); Aggregation.match(Criteria.where("date").gte(startDate).lte(endDate)); Please see also Spring Data MongoDB Date Between and Spring data mongodb search for ...

Spring Boot Integration Tests override custom .properties file

Spring Boot Integration Tests override custom .properties file I am implementing integration tests and I have a problem with overriding custom properties that my application use. Integration test sample: @RunWith(SpringRunner.class) @SpringBootTest( classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT ) @TestPropertySource(locations = "classpath:test.properties") public abstract class BaseIntegrationTest { @Autowired protected TestRestTemplate restClient; The @TestPropertySource(locations = "classpath:test.properties") will override application.properties of my application with one that is provided @TestPropertySource(locations = "classpath:test.properties") application.properties However, my application use custom property file like this: @Configuration @PropertySource("classpath:fileProvider/custom.properties") @ConfigurationProperties(prefix = "com.sample.config") public class Sample...

Spring Boot 2 PreAuthentication using windows login username

Spring Boot 2 PreAuthentication using windows login username Once user logins to windows machine and access the website, the user should be able to access the site without login and the roles should be set from the database. I am using Spring boot 2, SpringSecurity and Postgres SQL. I have gone through few PreAuthentication posts but they are mainly for Site Minder authentication, but no information on applying the roles from the database. Any help would be highly appreciated. By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

LazyInitializationException with graphql-spring

LazyInitializationException with graphql-spring I am currently in the middle of migrating my REST-Server to GraphQL (at least partly). Most of the work is done, but i stumbled upon this problem which i seem to be unable to solve: OneToMany relationships in a graphql query, with FetchType.LAZY. I am using: https://github.com/graphql-java/graphql-spring-boot and https://github.com/graphql-java/graphql-java-tools for the integration. Here is an example: Entities: @Entity class Show { private Long id; private String name; @OneToMany private List<Competition> competition; } @Entity class Competition { private Long id; private String name; } Schema: type Show { id: ID! name: String! competitions: [Competition] } type Competition { id: ID! name: String } extend type Query { shows : [Show] } Resolver: @Component public class ShowResolver implements GraphQLQueryResolver { @Autowired private ShowRepository showRepository; public List...