All tests from get methods work,
and this line works fine for them:
.andExpect(content().json(ow.writeValueAsString(orders.get(0))))
Here is the code:
Test setUp
#Autowired
private MockMvc mockMvc;
#MockBean
private OrderService orderService;
private List<OrderDTO> orders;
private String ordersJson;
ObjectWriter ow;
#BeforeEach
void setUp() throws JsonProcessingException {
orders = new LinkedList<>();
for (int i = 1; i <= 3; i++) {
orders.add(new OrderDTO.OrderDTOBuilder("test"+i, i*100)
.build());
}
ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
ordersJson = ow.writeValueAsString(orders);
}
Test that fails:
#Test
#DisplayName("POST /orders test - order saved with status 200")
#WithMockUser(roles = "PUBLISHER")
void saveNewOrder() throws Exception {
Mockito.doReturn(orders.get(0)).when(orderService).saveOrder(any(),any(),any(),any());
mockMvc.perform(
MockMvcRequestBuilders.post("/orders")
.content(ow.writeValueAsString(orders.get(0)))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(content().json(ow.writeValueAsString(orders.get(0))))
.andExpect(status().isOk())
.andReturn();
}
Tested Controller method:
#PostMapping("")
public OrderDTO saveNewOrder(#RequestBody OrderDTO orderData,
#RequestBody List<Long> processes,
#RequestBody Long clientId,
#RequestBody Long deliveryId)
{
return orderService.saveOrder(orderData, processes, clientId, deliveryId);
}
And here is the console message:
org.json.JSONException: Unparsable JSON string:
at org.skyscreamer.jsonassert.JSONParser.parseJSON(JSONParser.java:56)
at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:50)
at org.skyscreamer.jsonassert.JSONCompare.compareJSON(JSONCompare.java:125)
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:415)
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:394)
at org.skyscreamer.jsonassert.JSONAssert.assertEquals(JSONAssert.java:336)
at org.springframework.test.util.JsonExpectationsHelper.assertJsonEqual(JsonExpectationsHelper.java:61)
at org.springframework.test.web.servlet.result.ContentResultMatchers.lambda$json$9(ContentResultMatchers.java:215)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
at eu.mrndesign.matned.metalserwisproductionrest.controller.OrderControllerTest.saveNewOrder(OrderControllerTest.java:166)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1540)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
You have 2 options from what you have posted.
option 1: Relax your API with updating to required=false
#PostMapping("")
public OrderDTO saveNewOrder(#RequestBody OrderDTO orderData,
#RequestBody(required=false) List<Long> processes,
#RequestBody(required=false) Long clientId,
#RequestBody(required=false) Long deliveryId)
{
return orderService.saveOrder(orderData, processes, clientId, deliveryId);
}
Option 2: Add all required items in your test. this is a snippet and now real code.
MockMvcRequestBuilders.post("/orders")
.content("send all the required data with orderData, processes, clientId and deliveryId"))
I have an XML file data . and my target to put it in mysql database with a table called forecast containing just four columns (area_id, parameter_id, datetime, and value).
I managed to read the data from all the XML data but couldn't write the data into the database yet. How to write data that has been read in the logging class to the database?
below, there are several classes that I created with a spring batch configuration
Area.java
#XmlRootElement(name="area")
#XmlAccessorType(XmlAccessType.FIELD)
public class Area {
#XmlAttribute(name = "id")
private String area_id;
#XmlElement(name = "parameter")
private List<Parameter> area=null;
public List<Parameter> getArea(){
return area;
}
public void setArea(List<Parameter> area){
this.area = area;
}
public Area(){
}
public Area(String area_id) {
this.area_id = area_id;
}
#Override
public String toString() {
return "Area{" +
"area_id='" + area_id + '\'' +
", area=" + area +
'}';
}
}
TimeRange.java
#XmlRootElement(name="timerange")
#XmlAccessorType(XmlAccessType.FIELD)
public class TimeRange{
#XmlElement(name = "value")
String value;
#XmlAttribute(name = "datetime")
String datetime;
public TimeRange(){
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("TimeRange{");
sb.append("value='").append(value).append('\'');
sb.append(", datetime='").append(datetime).append('\'');
sb.append('}');
return sb.toString();
}
}
Parameter.java
#XmlRootElement(name="parameter")
#XmlAccessorType(XmlAccessType.FIELD)
public class Parameter{
#XmlAttribute(name="id")
private String parameter_id;
#XmlElement(name="timerange")
public List<TimeRange> parameter;
public List<TimeRange> getParameter(){
return parameter;
}
public void setParameter(List<TimeRange> parameter){
this.parameter = parameter;
}
public Parameter(){
}
public Parameter(String parameter_id) {
this.parameter_id = parameter_id;
}
#Override
public String toString() {
final StringBuffer sb = new StringBuffer("Parameter{");
sb.append("parameter_id='").append(parameter_id).append('\'');
sb.append(", parameter=").append(parameter);
sb.append('}');
return sb.toString();
}
}
Config.java
#Configuration
public class SpringBatchExampleJobConfig {
#Bean
public ItemReader<Area> areaItemReader() {
Jaxb2Marshaller areaMarshaller = new Jaxb2Marshaller();
areaMarshaller.setClassesToBeBound(Area.class);
return new StaxEventItemReaderBuilder<Area>()
.name("areaReader")
.resource(new ClassPathResource("data/DigitalForecast-SulawesiTengah.xml"))
.addFragmentRootElements("area")
.unmarshaller(areaMarshaller)
.build();
}
#Bean
public ItemWriter<Area> areaItemWriter(){
return new LoggingAreaItemWriter();
}
/**
* Creates a bean that represents the only step of our batch job.
* #param areaItemReader
* #param step1BuilderFactory
* #param areaItemWriter
* #return
*/
#Bean
public Step Step1(ItemReader<Area> areaItemReader,
ItemWriter<Area> areaItemWriter,
StepBuilderFactory step1BuilderFactory) {
return step1BuilderFactory.get("Step1")
.<Area, Area>chunk(1)
.reader(areaItemReader)
.writer(areaItemWriter)
.build();
}
/**
* Creates a bean that represents our example batch job.
* #param Step1
* #param jobBuilderFactory
* #return
*/
#Bean
public Job areaJob(Step Step1,
JobBuilderFactory jobBuilderFactory) {
return jobBuilderFactory.get("areaJob")
.incrementer(new RunIdIncrementer())
.start(Step1)
.build();
}
}
and the logging class I use to write readable data results
LoggingAreaItemWriter.java
public class LoggingAreaItemWriter implements ItemWriter<Area> {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingAreaItemWriter.class);
#Override
public void write(List<? extends Area> list) throws Exception {
LOGGER.info("Writing area: {}", list);
}
}
and the result
Writing area: [Area{area_id='501520', area=[Parameter{parameter_id='hu', parameter=[TimeRange{value='95', datetime='202102010000'}, TimeRange{value='80', datetime='202102010600'}, TimeRange{value='90', datetime='202102011200'}, TimeRange{value='95', datetime='202102011800'}, TimeRange{value='85', datetime='202102020000'}, TimeRange{value='60', datetime='202102020600'}, TimeRange{value='90', datetime='202102021200'}, TimeRange{value='90', datetime='202102021800'}, TimeRange{value='85', datetime='202102030000'}, TimeRange{value='55', datetime='202102030600'}, TimeRange{value='95', datetime='202102031200'}, TimeRange{value='95', datetime='202102031800'}]}, Parameter{parameter_id='humax', parameter=[TimeRange{value='95', datetime='202102011200'}, TimeRange{value='95', datetime='202102021200'}, TimeRange{value='95', datetime='202102031200'}]}, Parameter{parameter_id='tmax', parameter=[TimeRange{value='91.4', datetime='202102011200'}, TimeRange{value='91.4', datetime='202102021200'}, TimeRange{value='91.4', datetime='202102031200'}]}, Parameter{parameter_id='humin', parameter=[TimeRange{value='80', datetime='202102011200'}, TimeRange{value='60', datetime='202102021200'}, TimeRange{value='55', datetime='202102031200'}]}, Parameter{parameter_id='tmin', parameter=[TimeRange{value='75.2', datetime='202102011200'}, TimeRange{value='73.4', datetime='202102021200'}, TimeRange{value='73.4', datetime='202102031200'}]}, Parameter{parameter_id='t', parameter=[TimeRange{value='75.2', datetime='202102010000'}, TimeRange{value='91.4', datetime='202102010600'}, TimeRange{value='75.2', datetime='202102011200'}, TimeRange{value='73.4', datetime='202102011800'}, TimeRange{value='77', datetime='202102020000'}, TimeRange{value='91.4', datetime='202102020600'}, TimeRange{value='77', datetime='202102021200'}, TimeRange{value='75.2', datetime='202102021800'}, TimeRange{value='78.8', datetime='202102030000'}, TimeRange{value='91.4', datetime='202102030600'}, TimeRange{value='77', datetime='202102031200'}, TimeRange{value='73.4', datetime='202102031800'}]}, Parameter{parameter_id='weather', parameter=[TimeRange{value='1', datetime='202102010000'}, TimeRange{value='1', datetime='202102010600'}, TimeRange{value='1', datetime='202102011200'}, TimeRange{value='3', datetime='202102011800'}, TimeRange{value='1', datetime='202102020000'}, TimeRange{value='1', datetime='202102020600'}, TimeRange{value='1', datetime='202102021200'}, TimeRange{value='3', datetime='202102021800'}, TimeRange{value='3', datetime='202102030000'}, TimeRange{value='1', datetime='202102030600'}, TimeRange{value='0', datetime='202102031200'}, TimeRange{value='3', datetime='202102031800'}]}, Parameter{parameter_id='wd', parameter=[TimeRange{value='29230', datetime='202102010000'}, TimeRange{value='4500', datetime='202102010600'}, TimeRange{value='2230', datetime='202102011200'}, TimeRange{value='22500', datetime='202102011800'}, TimeRange{value='22500', datetime='202102020000'}, TimeRange{value='4500', datetime='202102020600'}, TimeRange{value='15730', datetime='202102021200'}, TimeRange{value='22500', datetime='202102021800'}, TimeRange{value='27000', datetime='202102030000'}, TimeRange{value='000', datetime='202102030600'}, TimeRange{value='000', datetime='202102031200'}, TimeRange{value='27000', datetime='202102031800'}]}, Parameter{parameter_id='ws', parameter=[TimeRange{value='1.028888888', datetime='202102010000'}, TimeRange{value='10.28888888', datetime='202102010600'}, TimeRange{value='1.028888888', datetime='202102011200'}, TimeRange{value='1.028888888', datetime='202102011800'}, TimeRange{value='1.028888888', datetime='202102020000'}, TimeRange{value='10.28888888', datetime='202102020600'}, TimeRange{value='1.028888888', datetime='202102021200'}, TimeRange{value='1.028888888', datetime='202102021800'}, TimeRange{value='1.028888888', datetime='202102030000'}, TimeRange{value='0', datetime='202102030600'}, TimeRange{value='0', datetime='202102031200'}, TimeRange{value='2.57222222', datetime='202102031800'}]}]}]
Please add a JDBC writer instead of logging writer like below.
#Bean
public JdbcBatchItemWriter<UnifiedInvoiceDTO> summaryWriter() {
JdbcBatchItemWriter<UnifiedInvoiceDTO> databaseItemWriter = new JdbcBatchItemWriter<>();
databaseItemWriter.setDataSource(dataSource);
databaseItemWriter.setSql("YOUR SQL");
ItemPreparedStatementSetter<UnifiedInvoiceDTO> invoicePreparedStatementSetter = new InvoiceSummarySetter();
databaseItemWriter.setItemPreparedStatementSetter(invoicePreparedStatementSetter);
return databaseItemWriter;
}
public class InvoiceSummarySetter implements ItemPreparedStatementSetter<UnifiedInvoiceDTO> {
Logger logger = LoggerFactory.getLogger(InvoiceSummarySetter.class);
#Override
public void setValues(UnifiedInvoiceDTO invoiceDTO, PreparedStatement preparedStatement) throws SQLException {
preparedStatement.setString(1, invoiceDTO.getTypeInvInfo().getAccountNumber());
}
Your XML input has a hierarchical format:
<area id="1">
<parameter id="11">
<timerange datetime="202102220000">
<value>85</value>
</timerange>
</>
<parameter id="12">
<timerange datetime="202102220600">
<value>95</value>
</timerange>
</>
</area>
<area id="2">
<parameter id="21">
<timerange datetime="202102220000">
<value>85</value>
</timerange>
</>
<parameter id="22">
<timerange datetime="202102220600">
<value>95</value>
</timerange>
</>
</area>
while your output has a flat format area_id,parameter_id,datetime,value:
1,11,202102220000,85
1,12,202102220600,95
2,21,202102220000,85
2,22,202102220600,95
So a single input XML item should be written as multiple database records. In this case, you need to "flatmap" your items before writing them to the database. This can be done with an item processor. See the following posts for more details on how to do that:
Save object with List as csv file FlatFileItemWriter
Flatten processing result in spring batch
i am trying to write test case for below controller its working fine,But problem is when i run unit test case then its showing null pointer exception in controller class at (LOGGER.info("========>request is------>" + objectMapper.writeValueAsString(basBaaisnEvcIdRequest));
can some one help me please how can i resolve this problem
controller
#RequestMapping(value = "/api/baaisn/queryevcid", produces = MediaType.APPLICATION_JSON_VALUE, method = RequestMethod.POST)
#ResponseBody
public BaaisnEvcIdResponse getQueryEvcid(#RequestBody BaaisnEvcIdRequest basBaaisnEvcIdRequest)
throws IOException, DAOException, SQLException, HttpServletException,JsonProcessingException {
LOGGER.info("========>request is------>" + objectMapper.writeValueAsString(basBaaisnEvcIdRequest));
if (basBaaisnEvcIdRequest.getLata() != 0 && (basBaaisnEvcIdRequest.getProduct_type() != null
&& !basBaaisnEvcIdRequest.getProduct_type().equalsIgnoreCase(""))) {
BaaisnEvcIdResponse baaisnEvcIdResponse = BaaisnEvcIdMSService.getQueryEvcidService(basBaaisnEvcIdRequest);
return baaisnEvcIdResponse;
} else {
BaaisnEvcIdResponse basiBaaisnEvcIdResponse = new BaaisnEvcIdResponse();
basiBaaisnEvcIdResponse.setStatus_code(0);
if (basBaaisnEvcIdRequest.getProduct_type() == null || basBaaisnEvcIdRequest.getProduct_type().equals("")) {
basiBaaisnEvcIdResponse.setStatus_desc("Please send Product type");
} else if (basBaaisnEvcIdRequest.getLata() == 0) {
basiBaaisnEvcIdResponse.setStatus_desc("Please send Lata");
}
return basiBaaisnEvcIdResponse;
}
}
Test class
#InjectMocks
BaaisnEvcIdMSController baaisnEvcIdMSController;
#Mock
BaaisnEvcIdMSService baaisnEvcIdMSService;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
#Test
public void getQueryEvcid() throws
IOException, DAOException, SQLException, HttpServletException,JsonProcessingException{
//Request object
BaaisnEvcIdRequest baaisnEvcIdRequest = mock(BaaisnEvcIdRequest.class);
Mockito.when(baaisnEvcIdRequest.getLata()).thenReturn(620);
Mockito.when(baaisnEvcIdRequest.getProduct_type()).thenReturn("LEVC");
Mockito.when(baaisnEvcIdRequest.getSvc_type()).thenReturn("EMS");
//Response object
BaaisnEvcIdResponse basiBaaisnEvcIdResponse = mock(BaaisnEvcIdResponse.class);
Mockito.when(basiBaaisnEvcIdResponse.getEvc_id()).thenReturn("/TLSM/100020218/001");
Mockito.when(basiBaaisnEvcIdResponse.getStatus_code()).thenReturn(1);
Mockito.when(basiBaaisnEvcIdResponse.getStatus_desc()).thenReturn("Success");
Mockito.when(baaisnEvcIdMSService.getQueryEvcidService(Mockito.any()))
.thenReturn(basiBaaisnEvcIdResponse);
BaaisnEvcIdResponse mockResponse = baaisnEvcIdMSController.getQueryEvcid(baaisnEvcIdRequest);
assertEquals("Success", mockResponse.getStatus_desc());
assertEquals("/TLSM/100020218/001", mockResponse.getEvc_id());
}
exception
java.lang.NullPointerException
at com.verizon.uts.ms.cdm.baaisn.evcid.controller.BaaisnEvcIdMSController.getQueryEvcid(BaaisnEvcIdMSController.java:44)
at com.verizon.uts.ms.cdm.baaisn.evcid.controller.BaaisnEvcIdMSControllerTest.getQueryEvcid(BaaisnEvcIdMSControllerTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:40)
at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.Iterator.forEachRemaining(Iterator.java:116)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:80)
at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:71)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
This question already has an answer here:
How to convert Part to Blob, so I can store it in MySQL?
(1 answer)
Closed 6 years ago.
I want to upload a file and save it to mysql database. thus far, I am able to upload the file, print its detail. However, when I attempt to store it in the database via a helper class everything except for the ID become null. Can you take a look and let me know what I am missing? Also, let me know if you see anything that I should change/modify as code enhancement.
Uploading the file using JSF/Primefaces:
<h:form enctype="multipart/form-data">
<p:growl id="messages" showDetail="true" />
<p:fileUpload value="#{fileUploadView1.file}" mode="simple"/>
<p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadView1.upload}" />
</h:form>
FileBean:
#ManagedBean
#SessionScoped
public class FileUploadView1 {
private InputStream input;
private String fileName;
private Long fileSize;
private UploadedFile file;
#Inject
private FileController1 fileController;
public InputStream getInput() {
return input;
}
public String getFileName() {
return fileName;
}
public Long getFileSize() {
return fileSize;
}
public FileController1 getFileController() {
return fileController;
}
public UploadedFile getFile() {
return file;
}
public void setFile(UploadedFile file) {
this.file = file;
System.out.println("filesize " + file.getSize());
}
public void upload() throws IOException {
if (file != null) {
FacesMessage message = new FacesMessage("Succesful", file.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, message);
input = file.getInputstream();
fileName = file.getFileName();
fileSize = file.getSize();
System.out.println("filesize3 " + file.getSize());
fileController.uploadFile(file);
}
}
}
FileController:
#ManagedBean
#SessionScoped
public class FileController1 {
private FileDbUtil1 fileDbUtil;
private Logger logger = Logger.getLogger(getClass().getName());
public FileController1() throws Exception {
fileDbUtil = FileDbUtil1.getInstance();
}
public String uploadFile(UploadedFile theFile) {
logger.info("Uploading File: " + theFile);
try {
fileDbUtil.uploadFile(theFile);
} catch (Exception exc) {
logger.log(Level.SEVERE, "Error adding files", exc);
addErrorMessage(exc);
return null;
}
return "welcomePrimefaces";
}
private void addErrorMessage(Exception exc) {
FacesMessage message = new FacesMessage("Error: " + exc.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
FileDbUtil File
public static FileDbUtil1 getInstance() throws Exception {
if (instance == null) {
instance = new FileDbUtil1();
}
return instance;
}
private FileDbUtil1() throws Exception {
dataSource = getDataSource();
}
private DataSource getDataSource() throws NamingException {
Context context = new InitialContext();
DataSource theDataSource = (DataSource) context.lookup(jndiName);
return theDataSource;
}
public void uploadFile(UploadedFile theFile) throws Exception {
fileName = theFile.getFileName();
input = theFile.getInputstream();
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "insert into upload"
+ "(name, file)"
+ " values (?,?)";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, fileName);
myStmt.setBinaryStream(2, input);
myStmt.executeUpdate();
} finally {
close(myConn, myStmt);
}
}
private Connection getConnection() throws Exception {
Connection theConn = dataSource.getConnection();
return theConn;
}
private void close(Connection theConn, Statement theStmt) {
close(theConn, theStmt, null);
}
private void close(Connection theConn, Statement theStmt, ResultSet theRs) {
try {
if (theRs != null) {
theRs.close();
}
if (theStmt != null) {
theStmt.close();
}
if (theConn != null) {
theConn.close();
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
Stack Trace: Note that I am able to print the file size before calling the helper class
Info: filesize 3501
Info: filesize3 3501
Warning: java.lang.NullPointerException
javax.el.ELException: java.lang.NullPointerException
at com.sun.el.parser.AstValue.invoke(AstValue.java:293)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
... 39 more
FATAL: JSF1073: javax.faces.FacesException caught during processing of INVOKE_APPLICATION 5 : UIComponent-ClientId=, Message=java.lang.NullPointerException
FATAL: java.lang.NullPointerException
javax.faces.FacesException: java.lang.NullPointerException
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:89)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.el.ELException: java.lang.NullPointerException
at com.sun.el.parser.AstValue.invoke(AstValue.java:293)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
... 31 more
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
... 39 more
Caused by: java.lang.NullPointerException
at com.uploadfile.test.FileUploadView1.upload(FileUploadView1.java:68)
fileController isn't getting injected.
Use #Inject private FileController1 fileController.
BalusC is right on his comment.
I have built a gui with javafx and swing and when I add an action listener to parse the expression in a textfield I get a error, I am not sure what the problem is.
the error is:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at functionparsergui.Test.parseFunction(Test.java:110)
at functionparsergui.Test.access$000(Test.java:38)
at functionparsergui.Test$2.actionPerformed(Test.java:88)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:729)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:702)
at java.awt.EventQueue$4.run(EventQueue.java:700)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:699)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
Caused by: java.lang.UnsupportedOperationException: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with version 3 (expected 2).
at org.antlr.v4.runtime.atn.ATNSimulator.deserialize(ATNSimulator.java:114)
at edu.chrr.util.function.FunctionLexer.<clinit>(FunctionLexer.java:504)
... 39 more
Caused by: java.io.InvalidClassException: org.antlr.v4.runtime.atn.ATN; Could not deserialize ATN with version 3 (expected 2).
... 41 more
My code starting from declaring the actionlistener is as follows:
ActionListener clearField = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
exprField.setText("");
JOptionPane.showMessageDialog(frame, "Input Cleared");
}
};
clearButton.addActionListener(clearField);
ActionListener parserButton;
parserButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String expression = exprField.getText();
String nowhiteExpr = expression.replaceAll("\\s+", "");
parseFunction(nowhiteExpr, frame);
}
};
parseButton.addActionListener(parserButton);
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
}
private static void parseFunction(final String function, final JFrame frame) {
try {
ANTLRInputStream input = new ANTLRInputStream(function);
FunctionLexer lexer = new FunctionLexer(input);
CommonTokenStream tokens = new CommonTokenStream((TokenSource) lexer);
FunctionParser parser = new FunctionParser(tokens);
parser.start();
int errorsCount = parser.getNumberOfSyntaxErrors();
if (errorsCount == 0) {
JOptionPane.showMessageDialog(frame, "Syntax is Correct");
} else {
Token t = parser.getCurrentToken();
String msg = "Syntax Incorrect: Missing " + t.getText();
JOptionPane.showMessageDialog(frame, msg);
}
} catch (RecognitionException ex) {
JOptionPane.showMessageDialog(frame, "Syntax is Incorrect");
}
}
private static void initFX(JFXPanel fxPanel) {
// This method is invoked on the JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() {
Group root = new Group();
Scene scene = new Scene(root, Color.ALICEBLUE);
return (scene);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initAndShowGUI();
}
});
}
}
ANTLR 4.1 is not compatible with ANTLR 4.0. You are generating your code with ANTLR 4.1 but attempting to run it with the ANTLR 4.0 runtime library.