Convert PDF to multipage TIFF file using ghostscript in Java - java

Download the Ghost libraries from Ghost4j site. Minimum jar required are ghost4j-1.0.0.jar, jna-3.3.0.jar, log4j-1.2.15.jar.
Also, you have to install the Ghostscript setup, which you can find from ghostscript site according to your windows bit.
Below is the code to convert the PDF to multipage TIFF.
public void PDFtoMultipageTIFFileByScript(String pdfFileLoc, String fileName, String tiffFileLoc) {
try {
Ghostscript gs = Ghostscript.getInstance();
List<String> gsArgs = new ArrayList<String>();
gsArgs.add("gswin64c.exe");
gsArgs.add("-o");
gsArgs.add(tiffFileLoc);
gsArgs.add("-sDEVICE=tiffg4");
gsArgs.add("-r600"); //Resolution.
gsArgs.add(pdfFileLoc);
//System.out.println("command running : " + gsArgs.toString());
gs.initialize(gsArgs.toArray(new String[0]));
gs.exit();
} catch (GhostscriptException e) {
System.err.println("ERROR: " + e.getMessage());
throw new RuntimeException(e.getMessage());
} catch (UnsatisfiedLinkError ule) {
throw new RuntimeException(getMessage(ule.getMessage()));
} catch (NoClassDefFoundError ncdfe) {
throw new RuntimeException(getMessage(ncdfe.getMessage()));
} catch (Exception e) {
e.printStackTrace();
}
}
String getMessage(String message) {
if (message.contains("library 'gs") || message.contains("ghost4j")) {
return message + GS_INSTALL;
}
return message;
}

Related

FTPClient connection with Java on AWS Virtual Machine

I'm trying to connect to my FTP server in Java SE 1.8. To do so I use this method :
private void connectFTP() {
String server = "ftp.XXXXXXXXXX.site";
int port = 21;
String user = "XXXX";
String pass = "XXXX";
if(!ftpConnexionSuccess.get())
{
client = new FTPClient();
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
try {
client.connect(server, port);
ftpConnexionSuccess.set(client.login(user, pass));
if (!ftpConnexionSuccess.get()) {
System.out.println("Could not login to the server");
return;
}
else
{
System.out.println("LOGGED IN SERVER");
client.changeWorkingDirectory("/crypto");
listenedFile = getListenedFile();
System.out.println(listenedFile.getName());
if(listenedFile != null)
{
baseFileTimeStamp.set(listenedFile.getTimestamp().getTimeInMillis());
}
System.out.println(baseFileTimeStamp);
}
} catch (Exception ex) {
System.err.println("FTP connection error : Sleeping for 5 seconds before trying again (" + ex.getMessage() + ")");
ex.printStackTrace();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {e.printStackTrace();}
try {
client.disconnect();
} catch (IOException e) {e.printStackTrace();}
connectFTP();
}
}
}
It works great when I'm on Eclipse and when I export the app on my Windows 10.
Nonetheless, when I try to launch the app on my AWS Webmachine I get a null pointer exception at "listenedFile". The method to listen to this file is the one below.
private FTPFile getListenedFile() {
FTPFile returnedFile = null;
try {
for(FTPFile file : client.listFiles())
{
if(file.getName().contains("filetolisten.txt"))
returnedFile = file;
}
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
try {
client.disconnect();
} catch (IOException e1) {e1.printStackTrace();}
connectFTP();
return getListenedFile();
}
return returnedFile;
}
I thought it was because of the line
client.configure(new FTPClientConfig(FTPClientConfig.SYST_UNIX));
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked.
I tried to delete the line, and to replace SYST_UNIX with SYST_NT, but nothing worked. Also updated Java, updated the common-nets library. Nothing worked

Renaming the original file name of a Multipart file

I have this code where I wanted to rename the before saving it to the file system. I tried other questions here in stack overflow but it doesn't apply for me. Hoping you could help me this is my code.
#PostMapping("/api/file/upload")
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
try {
fileStorage.store(file);
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
return "Error -> message = " + e.getMessage();
}
}
This is my store function:
#Override
public void store(MultipartFile file){
try {
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (Exception e) {
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
}
I tried renaming the original file but it doesn't work.
Hoping you could help me. Thank you so much!!!
Below is working snippet with little modification here and there :
#PostMapping(value = "/api/file/upload", headers = {"content-type=multipart/*"})
public #ResponseBody String uploadMultipartFile(#RequestParam("uploadfile") MultipartFile file) {
Path TO = Paths.get("/Users/myusername/Desktop/newfileName");
try {
try {
Files.copy(file.getInputStream(), TO);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
}
return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
} catch (Exception e) {
e.printStackTrace();
return "Error -> message = " + e.getMessage();
}
}
OutputScreen:

Jackcess DatabaseBuilder.open fails

I am using Jackcess API in my Eclipse plugin project. I added jackcess-2.1.0.jar file under resources/lib. I included the jar under my Binary build and in build.properties. I successfully make a connection using connection string but my DatabaseBuilder.open() call is not executing. My code is
public void run() {
try {
File tempTarget = File.createTempFile("eap-mirror", "eap");
try {
this.source = DriverManager.getConnection(EaDbStringParser.eaDbStringToJdbc(sourceString));
this.source.setReadOnly(true);
try {
FileUtils.copyFile(new File(templateFileString), tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
// Changes
try {
this.target = DatabaseBuilder.open(tempTarget);
} catch (IOException e) {
e.printStackTrace();
}
Collection<String> tables = selectTables(source);
long time = System.currentTimeMillis();
for (String tableName : tables) {
long tTime = System.currentTimeMillis();
Table table = target.getTable(tableName);
System.out.print("Mirroring table " + tableName + "...");
table.setOverrideAutonumber(true);
copyTable(table, source, target);
System.out.println(" took "+ (System.currentTimeMillis() - tTime));
}
System.out.println("Done. Overall time: "+ (System.currentTimeMillis() - time));
System.out.println("done");
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// More Code here
} catch (IOException e1) {
}
}
When I run the class in debug mode and I reach DatabaseBuilder.open call it fails.
Here is my project structure:
Can anyone tell me the possible reason for it ?
The .open method of DatabaseBuilder expects to open an existing well-formed Access database file. The .createTempFile method of java.io.File creates a 0-byte file. So, the code
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", "eap");
try (Database db = DatabaseBuilder.open(dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}
will cause Jackcess to throw
java.io.IOException: Empty database file
when it tries to do DatabaseBuilder.open(dbFile).
Instead, you should DatabaseBuilder.create to convert the 0-byte file into a real Access database file like this
File dbFile;
try {
dbFile = File.createTempFile("eap-mirror", ".accdb");
dbFile.deleteOnExit();
try (Database db = DatabaseBuilder.create(Database.FileFormat.V2010, dbFile)) {
System.out.println(db.getFileFormat());
} catch (IOException ioe) {
ioe.printStackTrace(System.out);
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
System.out.println("Finally...");
}

Resources not getting released in java

So, I have a function that reads file data, in this case image size. But after it's done it doesn't seem to properly release the files. I can't move those files afterwards. If I don't call this function everything works, but if I do I always get "file in use.. blah blah blah"
private void setMoveType() {
ImageInputStream in = null;
try {
in = ImageIO.createImageInputStream(new FileInputStream(file.toString()));
try {
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if(readers.hasNext()) {
ImageReader reader = readers.next();
try {
reader.setInput(in);
try {
moveType = Helper.getMoveType(new Dimension(reader.getWidth(0), reader.getHeight(0)));
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
} catch(Exception e) {
System.err.println("ReaderException: " + e.getMessage());
} finally {
reader.dispose();
}
}
} catch(Exception e) {
System.err.println("MoveTypeSetException: " + e.getMessage());
}
} catch (IOException e) {
System.err.print("IOException: failure while creating image input stream");
System.err.println(" -> createImageInputStream Error for file: " + file.getFileName());
return;
} finally {
if(in != null) {
try {
in.close();
} catch (IOException e) {
System.err.println("IOException: " + e.getMessage());
return;
}
}
}
}
EDIT: The ImageInputStream doesn't close properly
EDIT2: a FileInputStream wasn't closed
This stream should also be closed:
new FileInputStream(file.toString())
Closing the stream when you are done should work (in.close()). The operating system prevents the file from being changed, deleted or moved while it is in use. Otherwise, the stream would get messed up. Closing the stream tells the operating system you are no longer using the file.

Read XML file using SimpleXML throws Serializer Exception

I use SimpleXML to save a simple POJO into XML file and then read it back. I follow this tutorial. The file is successfully created, but the reading part is just simply not working. It throws the second exception which comes from serializer.read.
Room room = new Room("1");
Serializer serializer = new Persister();
try {
File ff = new File("room.xml");
serializer.write(room, ff);
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException\n");
} catch (Exception e) {
System.out.println("Exception from serializer.write\n");
}
try {
File ffi = new File("room.xml");
Room aroom = serializer.read(Room.class, ffi);
System.out.println("RoomName: " + aroom.getRid() + "\n");
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException\n");
} catch (Exception e) {
System.out.println("Exception from serializer.read\n");
}
Any hint?
Make sure you have a default constructor in Room.
public Room(){
}
Alternatively, make sure your constructor looks like this:
public Room(#Attribute(name="rid") String rid){
this.rid = rid;
}

Categories