Unable to move a file using java while using apache tika - java

I am passing a file as input stream to parser.parse() method while using apache tika library to convert file to text.The method throws an exception (displayed below) but the input stream is closed in the finally block successfully. Then while renaming the file, the File.renameTo method from java.io returns false. I am not able to rename/move the file despite successfully closing the inputStream. I am afraid another instance of file is created, while parser.parse() method processess the file, which doesn't get closed till the time exception is throw. Is that possible? If so what should I do to rename the file.
The Exception thrown while checking the content type is
java.lang.NoClassDefFoundError: Could not initialize class com.adobe.xmp.impl.XMPMetaParser
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:160)
at com.adobe.xmp.XMPMetaFactory.parseFromBuffer(XMPMetaFactory.java:144)
at com.drew.metadata.xmp.XmpReader.extract(XmpReader.java:106)
at com.drew.imaging.jpeg.JpegMetadataReader.extractMetadataFromJpegSegmentReader(JpegMetadataReader.java:112)
at com.drew.imaging.jpeg.JpegMetadataReader.readMetadata(JpegMetadataReader.java:71)
at org.apache.tika.parser.image.ImageMetadataExtractor.parseJpeg(ImageMetadataExtractor.java:91)
at org.apache.tika.parser.jpeg.JpegParser.parse(JpegParser.java:56)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.CompositeParser.parse(CompositeParser.java:244)
at org.apache.tika.parser.AutoDetectParser.parse(AutoDetectParser.java:121)
Please suggest any solution. Thanks in advance.
public static void main(String args[])
{
InputStream is = null;
StringWriter writer = new StringWriter();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
File file = null;
File destination = null;
try
{
file = new File("E:\\New folder\\testFile.pdf");
boolean a = file.exists();
destination = new File("E:\\New folder\\test\\testOutput.pdf");
is = new FileInputStream(file);
parser.parse(is, new WriteOutContentHandler(writer), metadata, new ParseContext()); //EXCEPTION IS THROWN HERE.
String contentType = metadata.get(Metadata.CONTENT_TYPE);
System.out.println(contentType);
}
catch(Exception e1)
{
e1.printStackTrace();
}
catch(Throwable t)
{
t.printStackTrace();
}
finally
{
try
{
if(is!=null)
{
is.close(); //CLOSES THE INPUT STREAM
}
writer.close();
}
catch(Exception e2)
{
e2.printStackTrace();
}
}
boolean x = file.renameTo(destination); //RETURNS FALSE
System.out.println(x);
}

This might be due to other processes are still using the file, like anti-virus program and also it may be a case that any other processes in your application may possessing a lock.
please check that and deal with that, it may solve your problem.

Related

Reading and writing object array list to text file

public void readList () {
try {
FileOutputStream writeData = new FileOutputStream("Accounts.txt");
ObjectOutputStream writeStream = new ObjectOutputStream(writeData);
writeStream.writeObject(AccountCredentials);
writeStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public void writeList() {
try {
FileInputStream readData = new FileInputStream("Accounts.txt");
ObjectInputStream readStream = new ObjectInputStream(readData);
AccountCredentials = (ArrayList <Accounts>) readStream.readObject();
readStream.close();
System.out.println(AccountCredentials.size());
}
catch (Exception e) {
e.printStackTrace();
}
}
My readList method works fine right, I have ¬í sr java.util.ArrayListxÒ™Ça I sizexp w
in the file. My writeList does not. I have a School folder inside the Netbeans folder, and in the main directory is Accounts.txt. Do I need to specify that? My Java file is in Schools/src. It always says my list size is 0
Can you please share the exception or stack trace you are getting and paste it here ? , Also I would highly recommend not to use a flat file for storing the account credentials, rather use any of the identity management solution and db driven account management. Did you also try to debug the following line "ObjectInputStream readStream = new ObjectInputStream(readData);"

How to upload zip file through REST API Mule 4?

I'm trying to upload zip file to the url https://anypoint.mulesoft.com/designcenter/api-designer/projects/{projectId}/branches/master/import. Content-Type must be application/zip, cant change to multipart/form-data. In Mule 3, a java transform class is used (com.test.FileReader) with the FileReader.class is stored in lib. It worked in Mule 3.
I tried to use ReadFile component to read test.zip and set as payload but it's not working. Any suggestion how to upload zip file in Mule 4?
package com.test;
import org.mule.transformer.*;
import org.mule.api.*;
import org.mule.api.transformer.*;
import java.io.*;
public class PayloadFileReader extends AbstractMessageTransformer
{
public Object transformMessage(final MuleMessage message, final String outputEncoding) throws TransformerException {
byte[] result = null;
try {
result = this.readZipFile("test.zip");
}
catch (Exception e) {
e.printStackTrace();
}
message.setPayload((Object)result);
return message;
}
public String readFileTest(final String path) throws FileNotFoundException, IOException, Exception {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = null;
final StringBuilder stringBuffer = new StringBuilder();
try {
bufferReader = new BufferedReader(fileReader);
String line;
while ((line = bufferReader.readLine()) != null) {
stringBuffer.append(line);
}
}
catch (IOException e) {
e.printStackTrace();
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
finally {
if (bufferReader != null) {
try {
bufferReader.close();
}
catch (IOException e2) {
e2.printStackTrace();
}
}
}
return stringBuffer.toString();
}
public byte[] readZipFile(final String path) {
final ClassLoader classLoader = this.getClass().getClassLoader();
final File file = new File(classLoader.getResource(path).getFile());
final byte[] b = new byte[(int)file.length()];
try {
final FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(b);
fileInputStream.close();
}
catch (FileNotFoundException e) {
System.out.println("Not Found.");
e.printStackTrace();
}
catch (IOException e2) {
System.out.println("Error");
e2.printStackTrace();
}
return b;
}
}
'
Assuming that your zip file corresponds to a valid API spec, in Mule 4, you don't need to use a custom java code to achieve what you want: you can read the file content using the File connector Read operation, and use an HTTP Request to upload it to Design Center using Design Center API. Your flow should look like:
For the Read operation, you only need to set the file location, in the File Path operation property.
No need to set content type in the HTTP Request (Mule 4 will configure the content type automatically based on the file content loaded by the Read operation).
You can't use Java code that depends on Mule 3 classes in Mule 4. Don't bother trying to adapt the code, it is not meant to work. Their architecture are just different.
While in Mule 4 you can use plain Java code or create a module with the SDK, there is no reason to do so for this problem and it would be counterproductive. My advise it to forget the Java code and resolve the problem with pure Mule 4 components.
In this case there doesn't seem a need to actually use Java code. The File connector read operation should read the file just fine as it doesn't appear the Java code is doing anything else than reading the file into the payload.
Sending through the HTTP Request connector should be straightforward. You didn't provide any details of the error, (where is it happening, complete error message, HTTP status error code, complete flow with the HTTP request in both versions, etc) and the API Designer REST API doesn't document an import endpoint so it is difficult to say if the request is correctly constructed.

Receiving message and saving it into a file in current directory

This is a question about: Receiving message and saving it into a file in current directory.
My issue is that, even though the messages are received, i am unable to write them into a file. The file is updated but it is empty. Yet the messages are printed on the interface. What i want is the message to be inside the file, not printed on the interface.
This is the code
public void receiveMessages() {
File file = new File ("msgs.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
PrintWriter printWriter = null;
try {
printWriter = new PrintWriter(file);
SealedObject encrypedSealedObject = null;
while(true){
try {
String message = this.crypto.decryptMsg(encrypedSealedObject);
printWriter.println(message);
}
catch (IOException e) {
break;
}
}
}
//catching exceptions ``here.... etc
}
Thank you for your help!
PrintWriter implements Flushable interface.
A Flushable is a destination of data that can be flushed. The flush
method is invoked to write any buffered output to the underlying
stream.
So, you have to flush your output to the file. So, you have to use pw.flush().
And above code will rewrite the file and not append the successive messages. If this is your requirement then its ok. But, I would suggest the following:
PrintWriter pw = null;
if (appendToFile) {
pw = new PrintWriter(new FileWriter(filename, true));
} else {
pw = new PrintWriter(new FileWriter(filename));
}
No need of using 2 try and catch as in both statement you are throwing IOException. And I would suggest to throw Throwable and handle the error in top layer it's good practice and easier maintenance. A function call must only perform logic.

How to delete file within catch block

public class deleteFile {
public static void main(String args[]){
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append("c:/");
fileNameStr.append("Test");
File file = new File(fileNameStr.toString());
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
}
According to this code, when I get SQLException, it can't delete file. Why?
There is nothing special about deleting a file in a catch block.
If your code (above) is not deleting the file, then it could be a number of things:
You may have the file pathname incorrect.
The file may not exist in the first place.
Your application may not have permission to delete the file, due to normal file / directory permission issues, "mandatory access control" restrictions (e.g. SELinux) or Java sandbox restrictions.
The file may be undeletable because it is "in use" ... on Windows.
That particular exception may not be being thrown.
Your catch block with SqlException never catching.
Use finally{} block in order to delete file or free resource.
Actually my full source code is,
public class deleteFile {
public static void main(String args[]){
-------------------------
StringBuffer fileNameStr = new StringBuffer();
fileNameStr.append(.....);
fileNameStr.append(.....);
File file = new File(fileNameStr.toString());
PrintWriter printWriter = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file),
"windows-31j")));
String systemDateTime = null;
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
file.delete();
}
}
Finally I found the solution that is need to close printWriter before deletion file. Thank you for your advice.
try {
systemDateTime = con.getSystemDateTime();
} catch (SQLException e) {
printWriter.flush();
printWriter.close();
file.delete();}
}

Java: Does nu.xom.Builder properly close Files?

I am using nu.xom.* for my project, link found at http://www.xom.nu/. My question is about the following part of my code:
private void open() {
builder = new Builder();
try {
document = builder.build(file);
} catch (ParsingException | IOException ex) {
Logger.getLogger(InvoiceData.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have some unwanted file locks in my program and am practically checking all places where I open a file. Now it struck me here that builder.build(File file) does implement Closeable, so I myself am not sure here whether it closes the file properly or not.
Can anyone shed some light on this?
Regards.
Fortunately the XOM library is open source, so you can take a look at the source code of nu.xom.Builder.build(File):
public Document build(File in)
throws ParsingException, ValidityException, IOException {
InputStream fin = new FileInputStream(in);
// [...]
String base = url.toString();
try {
Document doc = build(fin, base);
return doc;
}
finally {
fin.close();
}
}
So you pass a File instance to the build() method and inside this method a FileInputStream is opened and closed at the end.
There is a part after new FileInputStream(in) which is not enclosed by a try block. If this code throws an unchecked exception it is possible that the input stream isn't closed. But if you don't catch an exception then you can be sure, that the input stream is closed properly.

Categories