Jasper Report cannot run in war file deployed in tomcat - spring-boot

when try to run my project in eclipse IDE its work
#GetMapping(value = "/Print")
public void print(#RequestParam("Param_id") int Param_id, HttpServletResponse response)
throws IOException, JRException {
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(
invoiceServices.getInvoiceByBillId(Param_id) , false);
JasperReport report = null;
report = JasperCompileManager
.compileReport(
new FileInputStream("src/main/resources/static/reports/Invoice2.jrxml"));
report.setWhenNoDataType(WhenNoDataTypeEnum.NO_DATA_SECTION);
HashMap<String, Object> parm = new HashMap<>();
parm.put("Param_id", Param_id);
JasperPrint jasperPrint = null;
jasperPrint = JasperFillManager.fillReport(report, parm, beanCollectionDataSource);
JRPdfExporter exporter = new JRPdfExporter();
SimplePdfReportConfiguration reportConfigXLS = new SimplePdfReportConfiguration();
exporter.setConfiguration(reportConfigXLS);
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));
response.setContentType("application/pdf");
response.setHeader("Cache-Control", "max-age=0");
exporter.exportReport();
}
but its not work when run war file in tomcat
enter image description here
How to solve it?

Related

Download multiple files as zip using SpringBoot

i've been trying to download multiple files as a zip from the database using Spring Boot.
I am using Mysql and i did store the file succesfully on the database, but i can t find any help on how to retrive a list of files put it in a zip and download it.
I did manage to get files paths from database and download a zip file , but i would prefer getting some help in how to get the files directly from the database.
This is the code i am using to get a zip file out of local files.
WebService:
#GetMapping("/downloadZipFile/demande/{demandeRef}")
public void downloadZipFile(HttpServletResponse response,#PathVariable String demandeRef) throws IOException {
List<String> listOfFileNames = new ArrayList<>();
Demande d = demandeService.findByReference(demandeRef);
for (DemandePieceJointe dmd : d.getDemandePieceJointes() ){
listOfFileNames.add(dmd.getPath());
}
demandePieceJointeService.downloadZipFile(response, listOfFileNames);
}
Service:
#Override
public void downloadZipFile(HttpServletResponse response, List<String> name) throws IOException {
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=download.zip");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (String fileName : name) {
File resource = new File(fileName);
FileInputStream fileInputStream = new FileInputStream(resource);
ZipEntry zipEntry = new ZipEntry(resource.getName());
zipEntry.setSize(resource.getTotalSpace());
zipOut.putNextEntry(zipEntry);
StreamUtils.copy(fileInputStream, zipOut);
zipOut.closeEntry();
}
zipOut.finish();
zipOut.close();
response.setStatus(HttpServletResponse.SC_OK);
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"\"");

Unit test in Spring boot using Mockito

While executing Juint4 test. it shows null pointer exception. while using save method in unit test it returns null. Here i am using Mockito Juint4 Testing to mock the method. someone help me out with this.
**Service Method.**
public Result save(Map inputParams){
Result result = new Result();
logger.info("::::::::::::::: save ::::::::::::::::"+inputParams);
try{
String name = inputParams.get("name").toString();
String type = inputParams.get("type").toString();
CoreIndustry coreIndustry = coreIndustryDao.findByName(name);
if(coreIndustry != null){
result.setStatusCode(HttpStatus.FOUND.value());
result.setMessage(Messages.NAME_EXIST_MESSAGE);
result.setSuccess(false);
}else{
CoreIndustry coreIndustryNew = new CoreIndustry();
coreIndustryNew.setName(name);
coreIndustryNew.setType(type);
coreIndustryNew.setInfo(new Gson().toJson(inputParams.get("info")));
System.out.println("CoreIndustry Info is :............:.............:..............:"+coreIndustryNew.getInfo());
CoreIndustry coreIndustryData = coreIndustryDao.save(coreIndustryNew);
System.out.println("Saved Data Is.............::::::::::::::::::::................ "+coreIndustryData.getName()+" "+coreIndustryData.getType()+" "+coreIndustryData.getType());
result.setData(coreIndustryData);
result.setStatusCode(HttpStatus.OK.value());
result.setMessage(Messages.CREATE_MESSAGE);
result.setSuccess(true);
}
}catch (Exception e){
logger.error("::::::::::::::: Exception ::::::::::::::::"+e.getMessage());
result.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
result.setSuccess(false);
result.setMessage(e.getMessage());
}
return result;
}
**Controller**
#PostMapping(path = "/industry/save")
public Result save(#RequestBody Map<String, Object> stringToParse) {
logger.debug("save---------------"+stringToParse);
Result result = industryService.save(stringToParse);
return result;
}
**Unit Test**
#RunWith(SpringRunner.class)
#SpringBootTest
public class IndustryServiceTest {
#MockBean
private CoreIndustryDao coreIndustryDao;
private IndustryService industryService;
#Test
public void getAll() {
System.out.println("::::::: Inside of GetAll Method of Controller.");
// when(coreIndustryDao.findAll()).thenReturn(Stream.of(
// new CoreIndustry("Dilip","Brik","Brik Industry"))
// .collect(Collectors.toList()));
//assertEquals(1,industryService.getAll().setData());
}
#Test
public void save() {
ObjectMapper oMapper = new ObjectMapper();
CoreIndustry coreIndustry = new CoreIndustry();
coreIndustry.setId(2L);
coreIndustry.setName("Dilip");
coreIndustry.setType("Business");
HashMap<String,Object> map = new HashMap();
map.put("name","Retail");
map.put("type","Development");
coreIndustry.setInfo(new Gson().toJson(map));
when(coreIndustryDao.save(any(CoreIndustry.class))).thenReturn(new CoreIndustry());
Map<String, Object> actualValues = oMapper.convertValue(coreIndustry,Map.class);
System.out.println("CoreIndustry Filed values are........ : "+coreIndustry.getName()+" "+coreIndustry.getInfo());
Result created = industryService.save(actualValues);
CoreIndustry coreIndustryValue = (CoreIndustry) created.getData();
Map<String, Object> expectedValues = oMapper.convertValue(coreIndustryValue, Map.class);
System.out.println(" Getting Saved data from CoreIndustry........"+expectedValues);
System.out.println(" Getting Saved data from CoreIndustry........"+coreIndustryValue.getName());
assertThat(actualValues).isSameAs(expectedValues);
}
I am new in this Spring boot Technology.
After Running the source code for save method.
After Debugging my source code..
It will be great please to help me out. Thank you.

Veracode CWE id 611

I have a piece of code where there is veracode finding for Improper Restriction of XML External Entity Reference ('XXE') Attack.
Code:
Transformer transformer = TransformerFactory.newInstance().newTransformer();
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.transform(source, result); //CWE ID 611, impacted line.
I used
transformer.setOutputProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setOutputProperty(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
but no luck.
The issue got resolved with the following code:
TransformerFactory transformer = TransformerFactory.newInstance();//.newTransformer();
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(node);
transformer.newTransformer().transform(source, result);
It is advised to put a try-catch block.
try{
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
} catch (IllegalArgumentException e) {
//jaxp 1.5 feature not supported
}
Please note for anyone running the application on JDK5 or older that you will not have these XML Constants available:
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
transformer.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
Instead you will have to parse to a Document using a secured document builder then use a DOM source in your transformer.
private static void example(String xmlDocument, Result result) throws ParserConfigurationException, IOException, SAXException, TransformerException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
db.setEntityResolver(new EntityResolver() {
public InputSource resolveEntity(String s, String s1) throws SAXException, IOException {
return new InputSource(new StringReader(""));
}
});
Document doc = db.parse(new InputSource(new StringReader(xmlDocument)));
DOMSource domSource = new DOMSource(doc);
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.transform(domSource, result);
}

Programmatically download an order report to a server in Odoo

Is there some kind of endpoint or get resource available to download a quotation_order printout report?
I was able to get account invoices with the following code from the Odoo docs:
private void generateReport(final Object reportId) throws XmlRpcException, IOException {
final Object[] invoice_ids = (Object[])models.execute(
"execute_kw", asList(
db, uid, password,
"account.invoice", "search",
asList(asList(
asList("type", "=", "out_invoice"),
asList("state", "=", "open")))
));
final XmlRpcClientConfigImpl report_config = new XmlRpcClientConfigImpl();
report_config.setServerURL(
new URL(String.format("%s/xmlrpc/2/report", url)));
final Map<String, Object> result = (Map<String, Object>)models.execute(
report_config, "render_report", asList(
db, uid, password,
"account.report_invoice",
invoice_ids));
final byte[] report_data = DatatypeConverter.parseBase64Binary(
(String)result.get("result"));
File file = new File("proposal/odooOutput.pdf");
byte[] bytes = Base64.decodeBase64(report_data);
FileUtils.writeByteArrayToFile(file, report_data);
}
But I'm not sure how to hit the quotation_order (sale.order) printout:
Figured it out, this was my method for accomplishing this in Java:
private void generateQuotationOrderReport(final Object internalOdooQuoteId) throws XmlRpcException, IOException {
logger.info("generating quote report pdf for order #: " + internalOdooQuoteId);
final Object internalOdooQuoteIds = asList((Object[]) models.execute("execute_kw", asList(
db, uid, password,
"sale.order", "search",
asList(asList(
asList("id", "=", internalOdooQuoteId)
)),
new HashMap() {{
put("limit", 1);
}}
)));
final XmlRpcClientConfigImpl report_config = new XmlRpcClientConfigImpl();
report_config.setServerURL(
new URL(String.format("%s/xmlrpc/2/report", url)));
final Map<String, Object> result = (Map<String, Object>)models.execute(
report_config, "render_report", asList(
db, uid, password,
"sale.report_saleorder",
internalOdooQuoteIds));
final byte[] report_data = DatatypeConverter.parseBase64Binary(
(String)result.get("result"));
File file = new File("records/quotation_order.pdf");
FileUtils.writeByteArrayToFile(file, report_data);
}

Spring jaxb WebServiceGatewaySupport implementation java.lang.IllegalArgumentException

I'm working in jaxb with Spring, trying to write a custom unmarshalling process using WebServiceGatewaySupport.
My class is below. The problem is with response, when I call the following method
getWebServiceTemplate().sendSourceAndReceiveToResult
It crashes with message "java.lang.IllegalArgumentException: 'uri' must not be empty". It seems like even though I am using StringResult, it is trying to parse xml and finding a xml/soap response error.
public class WUResultGateway extends WebServiceGatewaySupport{
private WebServiceTemplate webServiceTemplate;
private SourceExtractor ratingResponseExtractor = new WUResponseExtractor();
public WUResultGateway(WebServiceTemplate webServiceTemplate){
this.webServiceTemplate = webServiceTemplate;
}
private Source marshall( SendRDCResults results ) throws IOException{
StringResult resp = new StringResult();
Marshaller marshaller = webServiceTemplate.getMarshaller();
marshaller.marshal( results, resp );
return new ResourceSource( new ByteArrayResource( resp.toString().getBytes() ) );
}
public Object wuResponse( SendRDCResults results) throws IOException{
//StringSource source = new StringSource();
Result result = new StreamResult();
StringResult strResult = new StringResult();
boolean flag = getWebServiceTemplate().sendSourceAndReceiveToResult( marshall( results ), strResult );
return result;
}
}
Without making any change to the response from the server, I want to get values in s String or simple xml format without errors. Can anyone help?
setDefaultUri(webServiceTemplate.getDefaultUri());
finally looks as follows
public Object wuResponse( SendRDCResults results) throws IOException{
//StringSource source = new StringSource();
Result result = new StreamResult();
StringResult strResult = new StringResult();
setDefaultUri(webServiceTemplate.getDefaultUri());
boolean flag = getWebServiceTemplate().sendSourceAndReceiveToResult( marshall( results ), strResult );
return result;
}

Resources