JasperReports won't replace $R{} when internationalizing report - internationalization

I need to produce i18n reports with existing code using JasperReports (4.7.1 originally but same problem with 5.6.1).
I did the following:
Report name is: x_report.jrxml
Added attribute resourceBundle="x_report" to the jasperReport tag in the jrxml file
Replaced text with $R{} tags in jrxml file
Built file
Added JRParameter.REPORT_LOCALE and JRParameter.REPORT_RESOURCE_BUNDLE to the parameters to pass to the JasperFillManager:
File reportFile = new File(getClass().getResource("/reports").getFile(), report.getReportFileName());
Map<String, Object> fillParams = (Map<String, Object>) report.getFillParameters();
java.util.Locale locale = new java.util.Locale("it");
fillParams.put(JRParameter.REPORT_LOCALE, locale);
String resBundleName = ...
ResourceBundle resBundle = ResourceBundle.getBundle(resBundleName, locale);
fillParams.put(JRParameter.REPORT_RESOURCE_BUNDLE, resBundle);
...
The JasperFillManager getting the params (with locale and resource bundle) and the report path:
BeanReport report = (BeanReport) this.report;
Collection<?> beans = report.getBeans();
JRBeanCollectionDataSource ds = new JRBeanCollectionDataSource(beans);
JasperPrint print = JasperFillManager.fillReport(reportFile.getPath(), fillParams, ds);
...
if (httpSession != null) {
httpSession.setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, print);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "ReportImage?image=");
}
exporter is a JRExporter:
exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
exporter.exportReport();
The resource bundle is found but my generated report still has the $R{} tags instead of the localized text.
What could be missing?
Thank you for your help!

I'm not sure if you are using JasperReports Server or not, but if you are what worked for me was to drop my properties bundle files into the ../jasperserver-pro/WEB-INF/classes folder.

Related

How to update pom.xml file using jaxb?

I am working on an application where I have to update the pom.xml file programmatically.
Steps which I am following.
Create JAVA POJO from maven XSD (http://maven.apache.org/xsd/maven-4.0.0.xsd).
Using the following program to load pom.xml file in POJO and updated value in the model then updated the same pom.xml file.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
File xml = new File("C:\\DS Designer Forum\\pomfiles\\pom.xml");
Document document = db.parse(xml);
JAXBContext jc = JAXBContext.newInstance(Model.class);
Binder<Node> binder = jc.createBinder();
Model model = (Model) binder.unmarshal(document);
Dependencies dependencies = model.getDependencyManagement().getDependencies();
if(dependencies != null) {
for(Dependency dependency : dependencies.getDependency()) {
if(!StringUtils.isEmpty(dependency.getScope()) && dependency.getScope().contains("provided")) {
String scope = dependency.getScope().replace("provided", StringUtils.EMPTY);
dependency.setScope(scope);
}
}
}
binder.updateXML(model);
TransformerFactory tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false);
Transformer t = tf.newTransformer();
t.transform(new DOMSource(document), new StreamResult(new File("C:\\DS Designer Forum\\pomfiles\\aaaaapom.xml")));
getting the following error.
**
Exception in thread "main" javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"project"). Expected elements are <{http://maven.apache.org/POM/4.0.0}project>
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1131)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:556)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:538)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor.startElement(InterningXmlVisitor.java:60)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:153)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.visit(DOMScanner.java:229)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:112)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:95)
at com.sun.xml.internal.bind.unmarshaller.DOMScanner.scan(DOMScanner.java:88)
at com.sun.xml.internal.bind.v2.runtime.BinderImpl.associativeUnmarshal(BinderImpl.java:146)
at com.sun.xml.internal.bind.v2.runtime.BinderImpl.unmarshal(BinderImpl.java:117)
at com.sunlife.innovation.update.LoadInfoFromPOMFile.main(LoadInfoFromPOMFile.java:52)
**
Please help me.
Thanks

Can't generate jasper report on spring

I am trying to generate a PDF file using JasperReports, however, regardless of how I try it, it's giving me a NullPointerException.
https://community.jaspersoft.com/questions/520803/getting-null-pointer-exception-fillreport
Tried looking there, and changed the jasper properties file, but it didn't do anything and i'm still getting the same error.
Tried absolute paths, relative paths, getting resource as stream, nothing
This is the code i'm using to generate the report
public String generateInvoiceFor (Reservation reservation) throws JRException {
JasperReport jasperReport = JasperCompileManager.compileReport("I:\\anoranzaHopefullyFinal\\src\\main\\resources\\jasper\\FacturaFinalFinal.jrxml");
List<Reservation> reservations = reservationService.getAll();
JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(reservations);
Map<String,Object> parameters = new HashMap<>();
parameters.put("Idparam", reservation.getId());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrBeanCollectionDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "jasper/jasperOutput/Factura.pdf");
return "Report successfully generated #path= jasper/jasperOutput/";
}
Check your datasource and jasperPrint. If there is no problem try this.
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(
new SimpleOutputStreamExporterOutput("PDF NAME IS HERE.pdf"));
SimplePdfReportConfiguration reportConfig
= new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig
= new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor("Auth name is here");
exportConfig.setEncrypted(true);
exportConfig.setAllowedPermissionsHint("PRINTING");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
exporter.exportReport();

Spring cannot find the file via specified path

My files hierarchy:
>resources:
>static:
>css:
>json:
>networks:
>network-list.json
>js:
>img:
I've tried to create a new file via:
File jsonNetworkDetailsFile = new File("/json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("static/json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("../json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("../../json/networks/network-list.json");
File jsonNetworkDetailsFile = new File("/json/networks/network-list.json");
...and some more. None of it works.
I'm still getting the
java.io.FileNotFoundException: the system cannot find the path specified
What's the proper way?
EDIT
Found a solution. Had to include full path to the file like:
File jsonNetworkDetailsFile = new File("src/main/resources/static/json/networks/Turtlecoin/turtlecoin-pools.json");
EDIT2
As TwiN stated - it's impossible to reference a file through File object as soon as the app is packed into .jar. A proper solution would include:
InputStream jsonNetworkDetailsFile = new ClassPathResource("/static/json/networks/network-list.json").getInputStream();
InputStream is = new ClassPathResource("/someFile.txt").getInputStream();
where /someFile.txt is in your resources folder.
As mentioned in the documentation for ClassPathResource:
Supports resolution as java.io.File if the class path resource resides
in the file system, but not for resources in a JAR. Always supports
resolution as URL.
In other words, you'll want to use the getInputStream() method for your case:
InputStream is = new ClassPathResource("/someFile.txt").getInputStream();
try {
String contents = new String(FileCopyUtils.copyToByteArray(is), StandardCharsets.UTF_8);
System.out.println(contents); // do something with the content here
is.close();
} catch (IOException e) {
e.printStackTrace();
}
I'm mentioning this because ClassPathResource also has a getFile() method.
For more details, see reference
Try something like this :
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("classpath:static/json/networks/network-list.json").getFile());
You could also use :
#Value(value = "static/json/networks/network-list.json")
private Resource myFile;
And then :
myFile.getInputStream()
(will only work on a class annoted with #Component, #Service... etc)
you can try this to load files from ressources :
ClassLoader loader = Thread.currentThread().
getContextClassLoader();
InputStream configStream = loader.getResourceAsStream("/static/json/networks/network-list.json");
I think you should give the exact location to File object. Another solution:
File currDir = new File(".");
String path = currDir.getAbsolutePath();
// String path = "C:\\ExternalFiles\\"; // Or you can give staticly
File jsonNetworkDetailsFile = new File(path);
Hope it helps.

Spring Boot load another file from app.properties

I am new to Spring Boot. I have this emailprop.properties in src/main/resource:
//your private key
mail.smtp.dkim.privatekey=classpath:/emailproperties/private.key.der
But I am getting the error as
classpath:\email properties\private.key.der (The filename, directory
name, or volume label syntax is incorrect)
How do I properly load this file?
Update-1
my java code is
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),
emailProps.getProperty("mail.smtp.dkim.privatekey"));
its working as "D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"Instead of emailProps.getProperty("mail.smtp.dkim.privatekey")
Update-2
i have tried java code is
String data = "";
ClassPathResource cpr = new ClassPathResource("private.key.der");
try {
byte[] bdata = FileCopyUtils.copyToByteArray(cpr.getInputStream());
data = new String(bdata, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),data);
Error is : java.io.FileNotFoundException: class path resource [classpath:private.key.der] cannot be resolved to URL because it does not exist
Tried Code is :
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
Still same error..
please update the answer..
If you want to load this file runtime then you need to use ResourceLoader please have a look here for the documentation - section 8.4.
Resource resource = resourceLoader.getResource("classpath:/emailproperties/private.key.der");
Now if you want to keep this exact path in properties file you can keep it there and then load it in your Autowired constructor/field like that:
#Value("${mail.smtp.dkim.privatekey}") String pathToPrivateKey
and then pass this to the resource loader.
Full example you can find here. I don't want to copy paste it.
If your file is located here:
"D:\\WorkShop\\MyDemoProj\\EmailService\\src\\main\\resources\\private.key.der"
then it should be:
mail.smtp.dkim.privatekey=classpath:private.key.der
EDIT:
I see now, you are using DKIMSigner, which expects file-path string,
Try changing your code like this:
ClassPathResource resource = new ClassPathResource(emailProps.getProperty("mail.smtp.dkim.privatekey"));
File file = resource.getFile();
String absolutePath = file.getAbsolutePath();
dkimSigner = new DKIMSigner(emailProps.getProperty("mail.smtp.dkim.signingdomain"), emailProps.getProperty("mail.smtp.dkim.selector"),absolutePath
);

How to load jasperreports resourcebundle at runtime?

Is it possible with jasper Reports to load a ResourceBundle (for i18n) at runtime?
I want to create a report from a jrxml file (for example c:\reports\report.jrxml)
with my labels in the properties file located at (c:\messages\report.properties).
I only found example where the property file is in the classloader.
Thanks
John Ferguson's blog mentions that the trick is to override the REPORT_RESOURCE_BUNDLE parameter with a custom ResourceBundle instance.
// Compiling the report is not a necessary step; prefer using .jasper files
// that have been pre-compiled to avoid this compilation step.
//
JasperDesign jasperDesign = JasperManager.loadXmlDesign("Report.jrxml");
JasperReport jasperReport = JasperManager.compileReport(jasperDesign);
Map parameters = new HashMap();
parameters.put("REPORT_LOCALE",LocaleManager.currentLocale());
parameters.put("REPORT_RESOURCE_BUNDLE",resourceBundle);
Connection conn = DBConnectionFactory.getConnection();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
parameters,
conn);
The resourceBundle can come from anywhere. For example:
try(FileInputStream fis = new FileInputStream("/tmp/report.properties")) {
ResourceBundle resourceBundle = new PropertyResourceBundle(fis);
// Pass resourceBundle into the report, as shown above.
}
loading bundle from resources package:
ResourceBundle bundle=ResourceBundle.getBundle("/reports/bundles/bundle",Locale.CANADA_FRENCH);
filling report::
params.put("REPORT_RESOURCE_BUNDLE", bundle);
JasperPrint jasPrint = JasperFillManager.fillReport(reportStream, params, data);

Resources