How to update pom.xml file using jaxb? - maven

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

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 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.

Conversion exceptions while using docx4j (From Docx to PDF)

I would like to know why this code:
String inputfilepath = "D:\\DFADFADSF";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath + ".docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
wordMLPackage.setFontMapper(new IdentityPlusMapper());
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPackage);
String outputfilepath = "D:\\OUT_FontContent.pdf";
OutputStream os = new java.io.FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
Throws this exception:
org.docx4j.openpackaging.exceptions.Docx4JException: Exception exporting package
org.docx4j.openpackaging.exceptions.Docx4JException: Exception executing transformer: org.apache.fop.fo.ValidationException: "fo:flow" is missing child elements. Required content model: marker* (%block;)+
Although there are similar posts, I haven't seen one about this exception...
Maybe I should add aditional code to configure the conversion...

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