EclipseLink Throwing Exception? - jersey

i'm working on a project based on jersey implementation of REST,and i i'm using JPA for persistence,spring IoC for DI.Now i have some objects that must be marshalled with JAXB (MOXy).Following step by step this tuto i tried to get things working but unfortunately i haven't succeeded yet.The folling are my classes,if you can help please:
Root classe :
package com.persistent.entity;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement
public class Bar {
private Map<String,String> mapbar;
public Bar() {
}
public Bar(Map<String,String> map ){
this.mapbar = map;
}
#XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> getMapbar() {
return mapbar;
}
public void setMapbar(Map<String, String> map) {
this.mapbar = map;
}
}
MapAdapter class :
package com.persistent.entity;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
//import javax.xml.bind.JAXBContext;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class MapAdapter extends XmlAdapter<AdaptedMap, Map<String, String>> {
#Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.newDocument();
Element rootElement = document.createElement("bar");
document.appendChild(rootElement);
for(Entry<String,String> entry : map.entrySet()) {
Element mapElement = document.createElement(entry.getKey());
mapElement.setNodeValue(entry.getValue());
rootElement.appendChild(mapElement);
}
AdaptedMap adaptedMap = new AdaptedMap();
adaptedMap.setValue(document);
return adaptedMap;
}
#Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
Map<String, String> map = new HashMap<String, String>();
Element rootElement = (Element) adaptedMap.getValue();
NodeList childNodes = rootElement.getChildNodes();
for(int x=0,size=childNodes.getLength(); x<size; x++) {
Node childNode = childNodes.item(x);
if(childNode.getNodeType() == Node.ELEMENT_NODE) {
map.put(childNode.getLocalName(), childNode.getTextContent());
}
}
return map;
}
}
AdaptedMap class :
package com.persistent.entity;
import javax.xml.bind.annotation.XmlAnyElement;
//import org.w3c.dom.Document;
public class AdaptedMap {
private Object value;
#XmlAnyElement
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
and, finally, the resource class :
package com.persistent.rest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.persistent.entity.Bar;
import com.persistent.entity.BarList;
import com.persistent.entity.Pie;
import com.persistent.entity.Vente;
import com.persistent.entity.VentesList;
import com.persistent.entity.PieList;
import com.persistent.service.VenteService;
import com.sun.jersey.api.json.JSONWithPadding;
// The Java class will be hosted at the URI path "/myresource"
#Path("/myresource")
#Component
#Scope("request")
public class MyResource {
#Autowired
VenteService venteService;
#GET
#Produces("application/x-javascript")
public JSONWithPadding getBarService(#QueryParam("callback") String callback){
int i;
VentesList ventes = venteService.getAll();
Map<String,String> hmBar = new HashMap<String,String>();
for (i=0;i<ventes.getsimpleVentes().size();i++){
hmBar.put(ventes.getsimpleVentes().get(i).getProjet(),String.valueOf(
ventes.getsimpleVentes().get(i).getNbrRsrv()));
}
Bar ba = new Bar(hmBar);
return new JSONWithPadding(ba,callback);
}
}
After running this on Tomcat i get this Exception :
GRAVE: "Servlet.service()" pour la servlet Jersey Spring Web Application a généré une exception
java.io.IOException: Error marshalling JAXB object of type "class com.persistent.entity.Bar".
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:145)
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:254)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:578)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:502)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:493)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:308)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:314)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:239)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
Caused by: javax.xml.bind.MarshalException
- with linked exception:
[Exception [EclipseLink-25003] (Eclipse Persistence Services - 2.3.1.v20111018-r10243): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: An error occurred marshalling the object
Internal Exception: Exception [EclipseLink-3001] (Eclipse Persistence Services - 2.3.1.v20111018-r10243): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [{Dyar Al Baydae=6, TEST=8, test=5, Dyar Al Bahja=20, Dyar Al Mansour=87}], of class [class java.util.HashMap], could not be converted to [class com.persistent.entity.AdaptedMap].]
at org.eclipse.persistence.jaxb.JAXBMarshaller.marshal(JAXBMarshaller.java:326)
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:167)
at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:143)
... 19 more

i found an other solution to my problem based on the solution posted here...It's worked for me and i think is the best solution to the mapping of object of type HashMap.

Related

Spring boot Kafka integration test: Consumer always returns 0 records

For the following test I am always getting the error:
org.opentest4j.AssertionFailedError: expected: 10 but was : 0
What exactly I am trying to verify in scope of the test:
I am trying to send 10 messages to Kafka and after that immediately I am trying to read those messages from Kafka, but for some unknown reason KafkaConsumer returns 0 records, and I am struggling to understand why Consumer can't read messages that were sent earlier?
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.stream.IntStream;
#SpringBootTest
#ActiveProfiles("test")
#ContextConfiguration(initializers = TestKafkaContextInitializer.class)
#Slf4j
public class KafkaFlowVerificationITest {
#Autowired
private KafkaTemplate<String, String> kafkaTemplate;
#Autowired
private KafkaProperties kafkaProperties;
private final String kafkaTopic = "test.topic";
#Test
void testKafkaFlow() {
IntStream.range(0, 10)
.forEach(e -> {
try {
kafkaTemplate.send(kafkaTopic, UUID.randomUUID().toString()).get();
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
});
checkKafkaForMessage();
}
private void checkKafkaForMessage() {
Map<String, Object> properties = new HashMap<>();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaProperties.getBootstrapServers());
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringDeserializer.class);
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, org.apache.kafka.common.serialization.StringDeserializer.class);
properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
properties.put(ConsumerConfig.GROUP_ID_CONFIG, "acme");
KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
consumer.subscribe(List.of(kafkaTopic));
ConsumerRecords<String, String> records = consumer.poll(Duration.ZERO);
Assertions.assertThat(records.count()).isEqualTo(10);
}
}
and TestKafkaContextInitializer:
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.testcontainers.containers.KafkaContainer;
import org.testcontainers.utility.DockerImageName;
#Slf4j
public class TestKafkaContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final KafkaContainer kafkaContainer =
new KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:5.4.3"));
#Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
kafkaContainer.start();
var values = TestPropertyValues.of(
"spring.kafka.producer.bootstrap-servers=" + kafkaContainer.getBootstrapServers(),
"spring.kafka.consumer.bootstrap-servers=" + kafkaContainer.getBootstrapServers()
);
values.applyTo(configurableApplicationContext);
}
}
The root cause of the issue is:
I set TestContainer Kafka bootstrap server url for the following properties:
spring.kafka.producer.bootstrap-servers
spring.kafka.consumer.bootstrap-servers
but in the test I use:
spring.kafka.bootstrap-servers property, that why Consumer made attempt connect to localhost:9092 default URL instead of URL provided by TestContainer.

Spring Boot #ComponentScan finds candidate component class but does not inject #Configuration beans

I have #SpringBootApplication with #ComponentScan({"myPackage"}) and in myPackage I have a class annotated with #Configuration or #Component. When I start the spring boot app the logs show:
DEBUG [main] org.sprin.conte.annot.ClassPathScanningCandidateComponentProvider 437 scanCandidateComponents: Identified candidate component class: file [C:\Web\project\bin\main\myPackage\Config.class]
but then nothing injects the class or its beans into the app...
It looks related to this
CODE
package app;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.gemfire.config.annotation.EnableLogging;
import org.springframework.data.gemfire.repository.config.EnableGemfireRepositories;
#SpringBootApplication
#ComponentScan({"myPackage"})
#EntityScan({"myPackage"})
#EnableGemfireRepositories("region")
#EnableLogging(logLevel="info", logFile="geodeApi.log")
public class Web {
private static final Logger log = LogManager.getLogger(Web.class);
public static void main(String[] args) {
log.info("In Main");
SpringApplication app = new SpringApplication(Web.class);
app.setWebApplicationType(WebApplicationType.REACTIVE);
SpringApplication.run(Web.class, args);
log.info("Out Main");
}
}
In myPackage.Client
package myPackage;
import java.util.UUID;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import org.apache.logging.log4j.Logger;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.gemfire.cache.config.EnableGemfireCaching;
import org.springframework.data.gemfire.config.annotation.ClientCacheApplication;
import org.springframework.data.gemfire.config.annotation.EnableClusterDefinedRegions;
import org.springframework.data.gemfire.config.annotation.EnablePdx;
import org.springframework.data.gemfire.config.annotation.EnablePool;
import org.springframework.data.gemfire.config.annotation.EnablePool.Locator;
import org.springframework.data.gemfire.config.annotation.EnableStatistics;
import org.springframework.session.data.gemfire.config.annotation.web.http.EnableGemFireHttpSession;
#ClientCacheApplication(name = "Web", logLevel = "debug")
#EnablePool(name = "webPool", subscriptionEnabled = true)
#EnableClusterDefinedRegions(clientRegionShortcut=ClientRegionShortcut.CACHING_PROXY)
#EnablePdx
#EnableStatistics
#EnableGemFireHttpSession(poolName = "webPool")
#EnableGemfireCaching
// #EnableWebFlux
public class Client {
private static final Logger log = LogManager.getLogger(Client.class);
#Resource
private Region<String, String> myAdmin;
#PreDestroy
public void onDestroy() throws Exception {
log.info("onDestroy");
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Shutdown");
log.traceExit();
}
#Bean
ApplicationRunner StartedUp(){
log.traceEntry("StartedUp");
return args -> {
String guid = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
myAdmin.put(guid, "Web Started");
log.traceExit();
};
}
// Required to resolve property placeholders in Spring #Value annotations.
#Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
log.traceEntry("propertyPlaceholderConfigurer");
return new PropertySourcesPlaceholderConfigurer();
}
}
In myPackage.Config
package myPackage;
import org.apache.geode.cache.GemFireCache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.gemfire.client.ClientRegionFactoryBean;
#Configuration
public class Config {
private static final Logger log = LogManager.getLogger(Config.class);
#Bean("myRegion")
public Region<String, Object> myRegion(GemFireCache cache) {
log.traceEntry();
Region<String, Object> r = cache.getRegion("myRegion");
r.setUserAttribute(ClientRegionShortcut.CACHING_PROXY);
return r;
}
}
In Config class while defining the bean you are using Region<String, Object> as return type. Where as in the your Client class you define Region<String, String>. Here it is clearly a type mismatch and hence bean will not load.

Implementing JUnit test cases in Spring batch Jobs calling from Controller

I am new to Junit. I am literally struggling to write Junit test cases for my code. I am working with Spring boot, Batch and JPA. I configured Jobs,file read and write in to DB everything working fine. But when it comes to JUnit, I don't even get an idea to write code. Can anyone help me. Below is my code
FileProcessController.java
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameter;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.sc.batchservice.model.StatusResponse;
import lombok.extern.slf4j.Slf4j;
#Slf4j
#RestController
#RequestMapping("/fileProcess")
public class FileProcessController {
#Autowired
private JobLauncher jobLauncher;
#Autowired
#Qualifier("euronetFileParseJob")
private Job job;
#GetMapping(path = "/process")
public #ResponseBody StatusResponse process() throws Exception {
try {
Map<String, JobParameter> parameters = new HashMap<>();
parameters.put("date", new JobParameter(new Date()));
jobLauncher.run(job, new JobParameters(parameters));
return new StatusResponse(true);
} catch (Exception e) {
log.error("Exception", e);
Throwable rootException = ExceptionUtils.getRootCause(e);
String errMessage = rootException.getMessage();
log.info("Root cause is instance of JobInstanceAlreadyCompleteException --> "+(rootException instanceof JobInstanceAlreadyCompleteException));
if(rootException instanceof JobInstanceAlreadyCompleteException){
log.info(errMessage);
return new StatusResponse(false, "This job has been completed already!");
} else{
throw e;
}
}
}
}
BatchConfig.java
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import com.sc.batchservice.model.DetailsDTO;
#Configuration
#EnableBatchProcessing
public class BatchConfig {
private JobBuilderFactory jobBuilderFactory;
#Autowired
public void setJobBuilderFactory(JobBuilderFactory jobBuilderFactory) {
this.jobBuilderFactory = jobBuilderFactory;
}
#Autowired
StepBuilderFactory stepBuilderFactory;
#Value("file:${input.files.location}${input.file.pattern}")
private Resource[] fileInputs;
#Value("${euronet.file.column.names}")
private String filecolumnNames;
#Value("${euronet.file.column.lengths}")
private String fileColumnLengths;
#Value("${input.files.location}")
private String inputFileLocation;
#Value("${input.file.pattern}")
private String inputFilePattern;
#Autowired
FlatFileWriter flatFileWriter;
#Bean
public Job euronetFileParseJob() {
return jobBuilderFactory.get("euronetFileParseJob")
.incrementer(new RunIdIncrementer())
.start(fileStep())
.build();
}
public Step fileStep() {
return stepBuilderFactory.get("fileStep")
.<DetailsDTO, DetailsDTO>chunk(10)
.reader(new FlatFileReader(fileInputs, filecolumnNames, fileColumnLengths))
.writer(flatFileWriter)
.build();
}
}
FlatFileReader.java
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.MultiResourceItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FixedLengthTokenizer;
import org.springframework.core.io.Resource;
import com.sc.batchservice.model.DetailsDTO;
import com.sc.batchservice.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
#Slf4j
public class FlatFileReader extends MultiResourceItemReader<DetailsDTO> {
public EuronetFlatFileReader(Resource[] fileInputs, String filecolumnNames, String fileColumnLengths) {
setResources(fileInputs);
setDelegate(reader(filecolumnNames, fileColumnLengths));
setStrict(true);
}
private FlatFileItemReader<DetailsDTO> reader(String filecolumnNames, String fileColumnLengths) {
FlatFileItemReader<DetailsDTO> flatFileItemReader = new FlatFileItemReader<>();
FixedLengthTokenizer tokenizer = CommonUtil.fixedLengthTokenizer(filecolumnNames, fileColumnLengths);
FieldSetMapper<DetailsDTO> mapper = createMapper();
DefaultLineMapper<DetailsDTO> lineMapper = new DefaultLineMapper<>();
lineMapper.setLineTokenizer(tokenizer);
lineMapper.setFieldSetMapper(mapper);
flatFileItemReader.setLineMapper(lineMapper);
return flatFileItemReader;
}
/*
* Mapping column data to DTO
*/
private FieldSetMapper<DetailsDTO> createMapper() {
BeanWrapperFieldSetMapper<DetailsDTO> mapper = new BeanWrapperFieldSetMapper<>();
try {
mapper.setTargetType(DetailsDTO.class);
} catch(Exception e) {
log.error("Exception in mapping column data to dto ", e);
}
return mapper;
}
}
I have Writer,Entity and model classes also, But if any example or idea upto this code, I can proceed with those classes.

Spring Cloud Stream Processor Unit Testing - #Autowire not working

I am trying to write a spring cloud stream processor class that takes an XML in through using the #StreamListener(Processor.INPUT) annotation.
The processor then extracts smaller XML messages and sends them to the output via this.processor.output().send(message);
I have not yet deployed this to dataflow because I wanted to test it with junit. When I run this with junit I can not seem to get my Processor object to instantiate.
I have tried using #Autowired which is how I have seen it done in may examples but I can't seem to get it to work. Any ideas would be appreciated.
My code is below.
package io.spring.dataflow.sample.usagecostprocessor;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import lombok.AllArgsConstructor;
#AllArgsConstructor
#EnableBinding(Processor.class)
public class REDACTXMLSplitter {
private Processor processor;
//#Autowired
//private SendingBean sendingBean;
#SuppressWarnings("unchecked")
#StreamListener(Processor.INPUT)
public void parseForREDACTApplications(String redactXML) {
InputSource doc = new InputSource( new StringReader( redactXML ) );
try
{
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // never forget this!
XPathFactory xfactory = XPathFactory.newInstance();
XPath xpath = xfactory.newXPath();
String xpathQuery = "//REDACT/Application";
xpath = xfactory.newXPath();
XPathExpression query = xpath.compile(xpathQuery);
NodeList productNodesFiltered = (NodeList) query.evaluate(doc, XPathConstants.NODESET);
for (int i=0; i<productNodesFiltered.getLength(); ++i)
{
Document suppXml = dBuilder.newDocument();
//we have to recreate the root node <products>
Element root = suppXml.createElement("REDACT");
Node productNode = productNodesFiltered.item(i);
//we append a product (cloned) to the new file
Node clonedNode = productNode.cloneNode(true);
suppXml.adoptNode(clonedNode); //We adopt the orphan :)
root.appendChild(clonedNode);
suppXml.appendChild(root);
//write out files
//At the end, we save the file XML on disk
// TransformerFactory transformerFactory = TransformerFactory.newInstance();
// Transformer transformer = transformerFactory.newTransformer();
// transformer.setOutputProperty(OutputKeys.INDENT, "yes");
// DOMSource source = new DOMSource(suppXml);
// StreamResult result = new StreamResult(new File("test_" + i + ".xml"));
// transformer.transform(source, result);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(suppXml), new StreamResult(writer));
String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
System.out.println(output);
Message<String> message = (Message<String>) suppXml;
this.processor.output().send(message);
}
}
catch (XPathExpressionException | ParserConfigurationException | TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package io.spring.dataflow.sample.usagecostprocessor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class REDACTXMLSplitterApplication {
public static void main(String[] args) {
SpringApplication.run(REDACTXMLSplitterApplication.class, args);
}
}
package io.spring.dataflow.sample.usagecostprocessor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.cloud.stream.messaging.Processor;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
#DirtiesContext
public class MAIPXMLSplitterApplicationTests {
#Autowired
private Processor myProcessor;
#Test
public void contextLoads() {
}
#Test
public void parseXML() {
try {
String cmErrorPayloadXML = readFile(ResourceUtils.getFile(this.getClass().getResource("/XMLSamples/REDACTApplicationXMLSamples/redact.xml")));
REDACTXMLSplitter redactXMLSplitter = new REDACTXMLSplitter(myProcessor);
redactXMLSplitter.parseForREDACTApplications(cmErrorPayloadXML);
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFile(File file) {
StringBuffer stringBuffer = new StringBuffer();
if (file.exists())
try {
//read data from file
FileInputStream fileInputStream = new FileInputStream(file);
int c;
while ((c = fileInputStream.read()) != -1){
stringBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}
Update,
I tried this but myProcessor is still null
package io.spring.dataflow.sample.usagecostprocessor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.ResourceUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
#RunWith(SpringRunner.class)
#SpringBootTest(classes = MAIPXMLSplitterApplicationTests.TestProcessor.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MAIPXMLSplitterApplicationTests {
#Autowired
private Processor myProcessor;
#Test
public void contextLoads() {
}
#Test
public void parseXML() {
try {
String cmErrorPayloadXML = readFile(ResourceUtils.getFile(this.getClass().getResource("/XMLSamples/MAIPApplicationXMLSamples/354_20191126_MAIP.xml")));
MAIPXMLSplitter maipXMLSplitter = new MAIPXMLSplitter(myProcessor);
maipXMLSplitter.parseForMAIPApplications(cmErrorPayloadXML);
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFile(File file) {
StringBuffer stringBuffer = new StringBuffer();
if (file.exists())
try {
//read data from file
FileInputStream fileInputStream = new FileInputStream(file);
int c;
while ((c = fileInputStream.read()) != -1){
stringBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
#EnableBinding(Processor.class)
#EnableAutoConfiguration
public static class TestProcessor {
}
}
You need to have #EnableBinding(Processor.class) in one of the configuration classes used by the Test class.
Typically, you can have a simple #Configuration subclass and have it part of the #SpringBootTest classes list. You can see an example here

Error creating bean, Injection of autowired dependencies failed - 500 Internal Server Error

I have created a new Spring project and I have some trouble when I run the application. I am new to Spring development and I thing that the annotations are not placed properly. Any detailed explanation would be great for me for better understating. I am currently reading Spring in action, but if any other book or tutorial seems more accurate, please leave me a comment :)[this is the error that I am getting - 500 Internal Server Error].
This is my project:
HelloWorldConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#ComponentScan(basePackages = "com.websystique.springmvc")
public class HelloWorldConfiguration {
#Bean(name="HelloWorld")
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
HelloWordInitializer
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
HelloWorldController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import service.StudentService;
import java.util.HashMap;
import java.util.Map;
#Configuration
#Controller
#ComponentScan(basePackages = "com.websystique.springmvc")
#RequestMapping("/")
public class HelloWorldController {
public HelloWorldController(){
}
#Autowired
private StudentService studentService;
private Map<String, Student> persoaneAdaugate = new HashMap<String, Student>();
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("greeting", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
/***
* #ModelAttribute = binds a method parameter or a method return value to a named model attribute and then exposes it to a web view.
* #param student
* #param result
* #param modelMap
* #return
* That is, #ModelAttribute methods are invoked before the controller methods annotated with #RequestMapping are invoked.
* The logic behind the sequence is that, the model object has to be created before any processing starts inside the controller methods.
*/
#RequestMapping(value="/", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("addStudent") Student student, BindingResult result, ModelMap modelMap){
if(result.hasErrors()){
return "error";
}
else {
studentService.addStudent(student);
}
/*modelMap.addAttribute("nume", student.getNume());
modelMap.addAttribute("prenume", student.getPrenume());
persoaneAdaugate.put(student.getNume(), student);
System.out.println("Persoane adaugate: " + persoaneAdaugate +"\n");
System.out.println("nume: " + student.getNume()+" si prenume: " +student.getPrenume());
*/
return "success";
}
}
StudentDao
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentDao {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentDaoImpl
import com.websystique.springmvc.model.Student;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository("studentDao")
#Service
#Transactional
public class StudentDaoImpl implements StudentDao{
#Autowired
private SessionFactory sessionFactory;
public List<Student> getAllStudents() {
return null;
// return sessionFactory.getCurrentSession().createQuery("from Date").list();
}
public void addStudent(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
}
Student
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="DATE")
public class Student implements Serializable{
#Id
#NotEmpty
#Column(name="nume", unique=true, nullable=false )
private String nume;
#NotEmpty
#Column(name="prenume", nullable = false)
private String prenume;
protected Student(){
}
Student(String nume, String prenume){
this.prenume=prenume;
this.nume=nume;
}
public String getNume(){
return nume;
}
public void setNume(String nume){
this.nume=nume;
}
public String getPrenume(){
return prenume;
}
public void setPrenume(String prenume){
this.prenume=prenume;
}
#Override
public String toString(){
return "Numele adaugat: nume= " + nume +" si prenume= " +prenume;
}
}
StudentService
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentService {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentServiceImpl
import com.websystique.springmvc.dao.StudentDao;
import com.websystique.springmvc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDao studentDao;
#Transactional
public List<Student> getAllStudents() {
return studentDao.getAllStudents();
}
public void addStudent(Student student) {
studentDao.addStudent(student);
}
}

Resources