How to load jasperreports resourcebundle at runtime? - internationalization

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);

Related

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
);

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

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.

Framework for generating BPEL in runtime?

I need to generate BPEL XML code in runtime. The only way I can do it now is to create XML document with "bare hands" using DOM API. But there must be a framework that could ease such work incorporating some kind of object model.
I guess it should look something like this:
BPELProcessFactory.CreateProcess().addSequence
Do you know any?
The Eclipse BPEL designer project provides an EMF model for BPEL 2.0. The generated code can be used to programmatically create BPEL code with a convenient API.
In case anyone stumbles upon this.
Yes this can be done using the BPEL Model.
Here is a sample piece of code which generates a quite trivial BPEL file:
public Process createBPEL()
{
Process process = null;
BPELFactory factory = BPELFactory.eINSTANCE;
try
{
ResourceSet rSet = new ResourceSetImpl();
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("bpel", new BPELResourceFactoryImpl());
File file = new File("myfile.bpel");
file.createNewFile();
String filePath = file.getAbsolutePath();
System.out.println(filePath);
AdapterRegistry.INSTANCE.registerAdapterFactory( BPELPackage.eINSTANCE, BasicBPELAdapterFactory.INSTANCE );
Resource resource = rSet.createResource(URI.createFileURI(filePath));
process = factory.createProcess();
process.setName("FirstBPEL");
Sequence seq = factory.createSequence();
seq.setName("MainSequence");
Receive recieve = factory.createReceive();
PortType portType = new PortTypeProxy(URI.createURI("http://baseuri"), new QName("qname"));
Operation operation = new OperationProxy(URI.createURI("http://localhost"), portType , "operation_name");
recieve.setOperation(operation);
Invoke invoke = factory.createInvoke();
invoke.setOperation(operation);
While whiles = factory.createWhile();
If if_st = factory.createIf();
List<Activity> activs = new ArrayList<Activity>();
activs.add(recieve);
activs.add(invoke);
activs.add(if_st);
activs.add(whiles);
seq.getActivities().addAll(activs);
process.setActivity(seq);
resource.getContents().add(process);
Map<String,String> map = new HashMap<String, String>();
map.put("bpel", "http://docs.oasis-open.org/wsbpel/2.0/process/executable");
map.put("xsd", "http://www.w3.org/2001/XMLSchema");
resource.save(map);
}
catch(Exception e)
{
e.printStackTrace();
}
return process;
}
The dependencies require that you add the following jars to the project's build path from the plugins folder in eclipse installation directory:
org.eclipse.bpel.model_*.jar
org.eclipse.wst.wsdl_*.jar
org.eclipse.emf.common_*.jar
org.eclipse.emf.ecore_*.jar
org.eclipse.emf.ecore.xmi_*.jar
javax.wsdl_*.jar
org.apache.xerces_*.jar
org.eclipse.bpel.common.model_*.jar
org.eclipse.xsd_*.jar
org.eclipse.core.resources_*.jar
org.eclipse.osgi_*.jar
org.eclipse.core.runtime_*.jar
org.eclipse.equinox.common_*.jar
org.eclipse.core.jobs_*.jar
org.eclipse.core.runtime.compatibility_*.jar

Resources