File format converter library in Java - jax-rs

I am trying to create a simple webservice in java that uses some library to convert the input docx file to an pdf file. Can some one please suggest me some sample libraries and also share some sample codes.

Since you are using Jersey, configure the file upload part of it. For it you need dependecy:
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.8</version>
</dependency>
After that you need dependecy of documents4j, I believe it is something similar as below:
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-api</artifactId>
<version>0.2.1</version>
</dependency>
You have more dependecy info here:
http://mvnrepository.com/artifact/com.documents4j
After it in your servlet you should receive your file upload:
http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
And convert it to PDF:
File wordFile = new File( ... ), target = new File( ... );
IConverter converter = ... ;
Future<Boolean> conversion = converter
.convert(wordFile).as(DocumentType.MS_WORD)
.to(target).as(DocumentType.PDF)
.prioritizeWith(1000) // optional
.schedule();
https://github.com/documents4j/documents4j
For more docs you can look here:
http://documents4j.com/#/
For IConverter:
IConverter converter = LocalConverter.builder()
.baseFolder(new File("C:\Users\documents4j\temp"));
.workerPool(20, 25, 2, TimeUnit.SECONDS)
.processTimeout(5, TimeUnit.SECONDS)
.build();

Related

View pdf in JPanel

How to view the pdf in JPanel using PDfBox??
I have the Source Code Like below.
try {
PDDocument inputPDF = PDDocument.load(FilePath);
List<PDPage> AllPages = inputPDF.getDocumentCatalog().getAllPages();
inputPDF.close();
PDPage TestPage = (PDPage)AllPages.get(0);
PDFPagePanel pdfPanel = new PDFPagePanel();
pdfPanel.setPage(TestPage);
pnlRiwayatStatus.add(pdfPanel);
}
catch(Exception e){
Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, e);
}
But thus source code NoClassDefFoundError
The missing class is mentioned in a comment:
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
This shows that you don't have the Apache Commons Logging jar in your class path.
According to the PDFBox web site, though, it is a required dependency:
Minimum Requirements
PDFBox has the following basic dependencies:
Java 6
commons-logging
Commons Logging is a generic wrapper around different logging frameworks, so you’ll either need to also use a logging library like log4j or let commons-logging fall back to the standard java.util.logging API included in the Java platform.
You should consider using Apache Maven for automatic dependency resolution.

sending mail with javamail throws NoSuchMethodError: sun.security.ssl.SessionId.checkLength

My Java ee 8 webapp is using javamail 1.6.1 to send emails via gmail. I'm running it on Glassfish 5, Mac os High Sierra, and Glassfish 5 is set to run on jdk1.8.0_20 and I start it from Netbeans 8.2.
Here's the snippet where it's being done:
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// Get the Session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
message.setSubject("Testing Subject");
message.setContent(
"<h1>This message is embedded in HTML tags</h1>",
"text/html");
Transport.send(message); // this line throws the exception
} catch (MessagingException e) {
throw new RuntimeException(e);
}
The Transport.send line throws the exception in the title above. More precisely:
Caused by: java.lang.NoSuchMethodError: sun.security.ssl.SessionId.checkLength(Lsun/security/ssl/ProtocolVersion;)V
at sun.security.ssl.HandshakeMessage$ServerHello.<init>(HandshakeMessage.java:504)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:209)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:984)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:919)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1043)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1343)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1371)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:619)
at com.sun.mail.util.SocketFetcher.startTLS(SocketFetcher.java:546)
at com.sun.mail.smtp.SMTPTransport.startTLS(SMTPTransport.java:2135)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:738)
at javax.mail.Service.connect(Service.java:388)
at javax.mail.Service.connect(Service.java:246)
at javax.mail.Service.connect(Service.java:195)
at javax.mail.Transport.send0(Transport.java:254)
at javax.mail.Transport.send(Transport.java:124)
I've found this similar question here but all they say is to make sure that Glassfish is running on JDK 1.8, and mine is.
I noticed that the same javax.mail.Transport class exists in both dependecies, javaee-api and javamail, so I removed javamail from my dependencies in my pom.xml and I could still build the application, but got the same error when trying to send the email.
This is what my pom.xml looks like:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>8.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.1</version>
</dependency>
Downgrading your JDK is not advisable. I found another solution which worked for me. See Antoine's answer in sun.security.ssl.SSLSessionImpl not found . You can remove the sun.* packages from the relevant file using a zip utility such as 7ZIP.
I haven't tried for this particular error message but I suspect it will be the solution as there seems to be many similar questions related to this package with the same root cause.
I upgraded the JDK 8 to 1.8.0_172 and started getting this other error:
NoSuchMethodError: sun.security.ssl.SSLSessionImpl.<init>(Lsun/security/ssl/ProtocolVersion;Lsun/security/ssl/CipherSuite;Ljava/util/Collection;Lsun/security/ssl/SessionId;Ljava/lang/String;I)V
That apparently is an issue with Glassfish 5 as discussed here.
So I downgraded the JDK 8 version to 1.8.0_152, which solved this problem.
To set netbeans to use the right update of the jdk configure this in the file netbeans_home/etc/netbeans.conf :
netbeans_jdkhome=/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

WRITE_DATES_WITH_ZONE_ID cannot be disabled for ZonedDateTime

I'm using Jackson 2.8.1 for serialization of java object. However, I just can't git rid of zone id when converting a ZonedDateTime object to a string with "WRITE_DATES_WITH_ZONE_ID" set to false
ObjectMapper mapper = new ObjectMapper()
.findAndRegisterModules()
.setSerializationInclusion(Include.NON_EMPTY)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(SerializationFeature.WRITE_DATES_WITH_ZONE_ID, false);
ZonedDateTime zdt = ZonedDateTime.now();
System.out.println(mapper.writeValueAsString(zdt)); // "2016-08-23T13:35:38.127+08:00[Asia/Shanghai]"
Can any one help?
I would say the issue is because you call "findAndRegisterModules".
You probably added the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
Doing so, you introduced two new modules: "JSR310Module" (deprecated) and "JavaTimeModule".
"findAndRegisterModules" can register the "JSR310Module" that is not supporting properly the WRITE_DATES_WITH_ZONE_ID feature.
You can register the right module by removing "findAndRegisterModules" and adding:
JavaTimeModule module = new JavaTimeModule();
registerModule(module);
Then, don't forget to disable WRITE_DATES_WITH_ZONE_ID in your mapper:
disable(SerializationFeature.WRITE_DATES_WITH_ZONE_ID);

Is it possible to start Mule3 embedded without spring dependency?

I am trying to use Mule 3.2.1 embedded from a plain java application. The application is suppose to run in an environment where storage space is limited.
I tried something like (import, exceptions omitted for brevity):
DefaultMuleContextFactory muleContextFactory = new DefaultMuleContextFactory();
ConfigurationBuilder configBuilder = new AutoConfigurationBuilder("mule-config.xml");
MuleContext muleContext = muleContextFactory.createMuleContext(configBuilder);
muleContext.start();
and also this:
AutoConfigurationBuilder configBuilder = new AutoConfigurationBuilder("mule-config.xml");
DefaultMuleConfiguration configuration = new DefaultMuleConfiguration();
MuleContextBuilder contextBuilder = new DefaultMuleContextBuilder();
contextBuilder.setMuleConfiguration(configuration);
MuleContext muleContext = new DefaultMuleContextFactory().createMuleContext(configbuilder, contextBuilder);
muleContext.start();
but both require spring-core, spring-beans, spring-context and some commons libraries. Any help would be great.
If you use the XML configuration, you need Spring.
If you don't want to use Spring, your options are:
Instantiate and wire Mule internal components by hand, dealing with life cycles as well,
Wait until Mule DSL gets released. You may want to bug MuleSoft about a release date :)
If you only want to use raw transports, ie not configure any flow or pattern, you can do it without Spring but bear in mind that, if the mule-core dependency doesn't bring Spring transitively, all the modules and transports do. This means that you'll have to use filtering to keep these dependencies at bay.
For example to use the HTTP transport, you would need these Maven dependencies:
<dependency>
<groupId>org.mule</groupId>
<artifactId>mule-core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mule.transports</groupId>
<artifactId>mule-transport-http</artifactId>
<version>3.4.0</version>
<exclusions>
<exclusion>
<groupId>org.mule.modules</groupId>
<artifactId>mule-module-spring-config</artifactId>
</exclusion>
</exclusions>
</dependency>
With this in place you then do:
MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();
MuleContextBuilder muleContextBuilder = new DefaultMuleContextBuilder();
MuleContext muleContext = muleContextFactory.createMuleContext(muleContextBuilder);
muleContext.start();
MuleClient client = muleContext.getClient();
MuleMessage response = client.request("http://www.google.com", 20000L);
System.out.println(response.getPayloadAsString());
muleContext.dispose();
System.exit(0);
Note that if that's all you're doing with Mule, then you'd rather use the Apache HTTP Client directly :)
MuleContextFactory muleContextFactory = new DefaultMuleContextFactory();
MuleContextBuilder muleContextBuilder = new DefaultMuleContextBuilder();
MuleContext muleContext
muleContextFactory.createMuleContext(muleContextBuilder);
muleContext.start();
// create mule client
MuleClient client = new MuleClient(muleContext);
// generate xml request
String reportRequestXml = createXML(reportRequest);
// set up message properties
Map<String, Object> messageProperties = new HashMap<String, Object>();
messageProperties.put("Content-Type", "application/xml");
// send request with timeout
MuleMessage response = client.send(crsRestUrl, reportRequestXml, messageProperties, httpTimeout);
muleContext.stop();

Can't access properties file

I've made a plugin from external jar. In this jar there is access to properties file:
final Properties properties = new Properties();
final String fileName = "/" + thisClass.getName() + ".properties";
InputStream inputStream;
try
{
inputStream = thisClass.getResourceAsStream(fileName);
properties.load(inputStream);
}
In my RCP-Application the inputStream is null. I've also exported the default package in the plugin. What's wrong.
I've solved my problem. The solution is to make an Eclipse-BuddyPolicy Entry to the Manifest.mf of the plugin with the external jar.
Eclipse-BuddyPolicy: global
This is described in the Eclipse Help: Platform Plugin Developer Guide-->Reference-->Other reference information-->Third party libraries and classloading