Spring Boot with AngularJS - angularjs

I have a Spring Boot project using Jersey as my REST service and using AngularJS for my front end development. While I run it without using any controller and go to index.html (which is in resource/static/index.html) it works fine. When I add a controller it renders gives the string "index.html" as an output. Spring Boot Configuration:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#SpringBootApplication
#ComponentScan(basePackages = {"com.cst.interfaces","com.cst.configuration","com.cst.application","com.cst.application.implmentation"})
#EnableAutoConfiguration
public class ApplicationConfiguration {
public static void main(String args[]) throws Exception{
SpringApplication.run(ApplicationConfiguration.class, args);
}
public ServletRegistrationBean jerseyServlet(){
ServletRegistrationBean register = new ServletRegistrationBean(new ServletContainer(),"/*");
register.addInitParameter(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyInitalize.class.getName());
return register;
}
}
JerseyConfiguration:
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
#Component
public class JerseyInitalize extends ResourceConfig{
public JerseyInitalize(){
super();
this.packages("com.cst.interfaces");
}
}
Controller Class:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.web.bind.annotation.RestController;
#RestController
#Path("/home")
public class HomeResource {
#GET
#Produces("application/json")
public String getString(){
return "index.html";
}
}

This is because you annotated your controller with #RestController, which is a shorthand for #Controller with #ResponseBody. The latter annotation instructs the controller to render the output as-is directly into the response.
Use #Controller for controllers that are not RESTful instead.

Related

Error:The method dataSource(DataSource) is undefined for the type EntityManagerFactoryBuilder

I am trying to connect two databases(MSSQL server and H2db) using springboot with spring data jpa and hibernate
I have created two configuration files
but getting error in configuration file.
Error:The method dataSource(DataSource) is undefined for the type EntityManagerFactoryBuilder
at return builder.dataSource(db2DataSource()) point
DbOneConfig
package com.examle.demo.config.h2db;
import java.util.HashMap;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
//to active transaction and services
#EnableTransactionManagement
#EnableJpaRepositories(
entityManagerFactoryRef = "db1EntityManagerFactory",
transactionManagerRef = "db1TransactionManager",
basePackages = { "package com.example.h2db.repo" } //for repository
)
public class DbOneConfig {
//datasource
#Bean //indicates creating the Object here
#ConfigurationProperties(prefix ="db1.datasource")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();//build method returns the Object ,
//create method internally builds the datasource here
}
//EntityManagerFactory
#Primary
#Bean(name = "db1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean db1EntityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("db1DataSource") DataSource db1DataSource
) {
//HashMap<String, Object>properties = new HashMap<>();
//properties.put("hibernate.hbm2ddl.auto","create");
//properties.put("hibernate.dialect","org.hibernate.dialect.H2Dialect");
return builder
.dataSource(db1DataSource) //getting error on this line
.packages("com.eaxample.demo.model.h2db")
.build();
}
//TXManager
#Bean
public PlatformTransactionManager db1TransactionManager(
#Qualifier("db1EntityManagerFactory")
//read object from the container
EntityManagerFactory entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
You have imported org.hibernate.jpa.boot.spi.EntityManagerFactoryBuilder and you should import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder.

replacement for camel cxfbean

we are currently struggling with updating our legacy service (non spring, jee + deltaspike, weld) and it's dependencies.
We try to upgrade from camel 2.16.2 to 3.x (due to java 11 compatibility).
We have already read through the migration guide several times, but could not find any reference to your replacement of the cxfbean component.
e.g.:
public class MonitoringRoute extends RouteBuilder {
#Override
public void configure() throws Exception {
from("servlet:///monitoring?matchOnUriPrefix=true")
.to("cxfbean:monitoringService")
.setId("MonitoringRoute");
}
}
#Named("monitoringService")
public class MonitoringService implements MonitoringAPI {
#Override
public String status() {
return "OK";
}
}
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
public interface MonitoringAPI {
#GET
#Path("status")
#Produces(MediaType.TEXT_PLAIN)
String status();
}
We already tried cxfrs:monitoringService, but this will led to "Uri is not absolute" exception.
Any idea to replace cxfbean properly?

Camel exchange header lost during test

I'm trying to test the onException(JsonProcessingException.class) route in the following class (please don't mind its name, I've cut some code out for clarity):
import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.rest.RestBindingMode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.JsonProcessingException;
import pl.muni.camel.sample.customer.domain.CustomerData;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerErrorResponseProcessor;
import pl.muni.camel.sample.customer.route.processor.CreateCustomerOkResponseProcessor;
#Component
public class SendCustomerDataToQueueRoute extends RouteBuilder {
#Value("${http.rest.listener.host}")
private String restListenerHost;
#Value("${http.rest.listener.port}")
private int restListenerPort;
#Override
public void configure() {
restConfiguration()
.component("restlet")
.dataFormatProperty("prettyPrint", "true")
.host(restListenerHost)
.port(restListenerPort);
rest("/rest/v1/customer")
.post("/create")
.bindingMode(RestBindingMode.json)
.skipBindingOnErrorCode(false)
.consumes("application/json")
.type(CustomerData.class)
.produces("application/json")
.route().id("acceptCreateCustomerRequest")
.from("direct:acceptRequest")
.to("direct:processRequest");
onException(JsonProcessingException.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
.to("direct:processException");
onException(Exception.class)
.handled(true)
.setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
.to("direct:processException");
from("direct:processRequest").routeId("processCreateCustomerRequest")
.log("Received customer data: ${body}")
.process(new CreateCustomerOkResponseProcessor()).id("createOkResponse");
from("direct:processException").routeId("processCreateCustomerException")
.log(LoggingLevel.ERROR, "${exception.stacktrace}").id("logExceptionStackTrace")
.process(new CreateCustomerErrorResponseProcessor()).id("createErrorResponse");
}
}
I want to intercept the exchange after createErrorResponse processor and run some assertions on it. So far I've come up with this code, in which I weave in a mock endpoint after direct:processException endpoint:
import java.util.List;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringBootRunner;
import org.apache.camel.test.spring.EnableRouteCoverage;
import org.apache.camel.test.spring.MockEndpointsAndSkip;
import org.apache.camel.test.spring.UseAdviceWith;
import org.assertj.core.api.Assertions;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.annotation.DirtiesContext;
import pl.muni.camel.sample.customer.infrastructure.rest.CreateCustomerResponse;
#UseAdviceWith
#MockEndpointsAndSkip("restlet*")
#EnableRouteCoverage
#DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
#SpringBootTest
#ComponentScan("pl.muni.camel.sample.customer")
#RunWith(CamelSpringBootRunner.class)
public class SendCustomerDataToQueueIntegrationTest {
#Produce
private ProducerTemplate producerTemplate;
#Autowired
private CamelContext context;
#EndpointInject(uri = "mock:error")
private MockEndpoint errorEndpoint;
#Before
public void setUp() throws Exception {
context.getRouteDefinition("processCreateCustomerRequest").adviceWith(context, new AdviceWithRouteBuilder() {
#Override
public void configure() {
weaveByToUri("direct:processException")
.after()
.to("mock:error");
}
});
context.start();
}
#After
public void tearDown() throws Exception {
context.stop();
}
#Test
public void shouldReturnHttpStatus400ForInvalidJson() throws InterruptedException {
// given
final String customerDataString = "{\"firstName\": \"aaa\", \"lastname\": \"bbb\"}";
//when
producerTemplate.sendBody("direct:acceptRequest", customerDataString);
//then
errorEndpoint.expectedHeaderReceived(Exchange.HTTP_RESPONSE_CODE, 400);
errorEndpoint.assertIsSatisfied();
final List<Exchange> exchanges = errorEndpoint.getExchanges();
Assertions.assertThat(exchanges).hasSize(1);
final Exchange exchange = exchanges.get(0);
final CreateCustomerResponse response = exchange.getIn().getBody(CreateCustomerResponse.class);
Assertions.assertThat(response.isSuccess()).isFalse();
Assertions.assertThat(response.getErrorMessage()).startsWith("UnrecognizedPropertyException: Unrecognized field \"lastname\"");
}
}
Unfortunately, the Exchange.HTTP_RESPONSE_CODE header somehow disappears during the test and the assertion on errorEndpoint fails. I ran the test with debugger and breakpoint set within CreateCustomerErrorResponseProcessor class and there the header was still available.
Is there another way to set up the test and be able to retrieve the header or could this be a bug?
The URI you are weaving ("direct:processException") in your unit test is attached to a wrong route definition.
It should be:
context.getRouteDefinition("processCreateCustomerException").adviceWith(...)
(and not "processCreateCustomerRequest")

Download pdf for my web users

I'm having fun with pdfbox but still can't find usefull info about downloading this.
So, I've got button, when I click it - pdf is saved on my computer locally.
Controller:
#RequestMapping("/pdf")
public class DocumentCreateController {
#Autowired
private DocumentCreate DCpdf;
#RequestMapping(method=RequestMethod.GET)
public void getPDF() throws IOException{
DCpdf.getPDF();
}
}
Service:
package pl.asseco.portalhr.obiegdokum;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.springframework.stereotype.Service;
#Service
public class DocumentCreate {
public void getPDF() throws IOException{
PDDocument document = new PDDocument();
document.save("C:/myfolder/test.pdf");
document.close();
return;
}
}
Please help, what about I have to learn? What I need to use?

Cannot Unit Test Using Fongo fails in 4.1.4 - worked in 3.1.4

https://github.com/sanjuthomas/spring-data-mongodb
I have try several examples such as the one above to understand how to unit test mongo applications using fongo. All the examples examples worked - including the one above but when I upgrade the pom to the latest releases supported in spring boot all the examples fail. It seems the application context is no longer getting loaded for the test. Is this unit test functionality broken or do I need to change the code?
Below is the code that fails and used to work in Spring 3 - now the rule fails stating that a mongo instance does not exist in the context:
package com.ourownjava.spring.data.mongo.repository;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.foursquare.fongo.Fongo;
import com.lordofthejars.nosqlunit.annotation.ShouldMatchDataSet;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import com.mongodb.Mongo;
import com.ourownjava.spring.data.mongo.model.Trade;
/**
* Spring Data MongoDB Repository Unit testcase.
*
* #author ourownjava.com
*
*/
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class TestTradeRepository {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule mongoDbRule = newMongoDbRule().defaultSpringMongoDb(
"trade-db");
#Autowired
private TradeRepository tradeRepository;
#Test
#ShouldMatchDataSet(location = "/testData/trade-t1.json")
public void shouldSaveTrade(){
tradeRepository.save(createTrade());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByTraderId(){
final List<Trade> trades = tradeRepository.findByTraderId("papjac");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("papjac", trades.get(0).getTraderId());
}
#Test
#UsingDataSet(locations = {"/testData/trade-t1.json"})
public void shouldFindByExchangeCode(){
final List<Trade> trades = tradeRepository.findByExchangeCode("NYSE");
assertNotNull(trades);
assertTrue(trades.size() > 0);
assertEquals("NYSE", trades.get(0).getExchangeCode());
}
private Trade createTrade(){
final Trade trade = new Trade();
trade.setId("t1");
trade.setTraderId("papjac");
trade.setExchangeCode("NYSE");
trade.setValue(90.3);
return trade;
}
#Configuration
#EnableMongoRepositories
#ComponentScan(basePackageClasses = { TradeRepository.class })
static class MongoConfiguration extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "trade-db";
}
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.ourownjava.spring.data.mongo";
}
}
}
You have to use Annotation #Bean for mongo()
#Bean
#Override
public Mongo mongo() {
return new Fongo("trade-test").getMongo();
}

Resources