java.util.concurrent.ExecutionException: java.lang.Error: Invalid memory access - java

Please note that i am writing a java program using tes4j and i am able to extract the tiff file and save it as pdf but many times i am getting this error. I am running the files as a batch using callable i am taking 5 files and process them during which i get this error. test4j i am using as a maeven dependency.
Error Description
java.util.concurrent.ExecutionException: java.lang.Error: Invalid memory access
at java.util.concurrent.FutureTask.report(Unknown Source)
at java.util.concurrent.FutureTask.get(Unknown Source)
at com.mkyong.listener.SerachablePDFConversionService.processAllFiles(SerachablePDFConversionService.java:197)
at com.mkyong.listener.SerachablePDFConversionService.run(SerachablePDFConversionService.java:107)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.Error: Invalid memory access
at com.sun.jna.Native.invokeInt(Native Method)
at com.sun.jna.Function.invoke(Function.java:419)
at com.sun.jna.Function.invoke(Function.java:354)
at com.sun.jna.Library$Handler.invoke(Library.java:244)
at com.sun.proxy.$Proxy0.gsapi_init_with_args(Unknown Source)
at org.ghost4j.Ghostscript.initialize(Ghostscript.java:350)
at com.mkyong.listener.SerachablePDFConversionService.convertPDFToTiff(SerachablePDFConversionService.java:137)
at com.mkyong.listener.SerachablePDFConversionService$1.call(SerachablePDFConversionService.java:213)
at com.mkyong.listener.SerachablePDFConversionService$1.call(SerachablePDFConversionService.java:1)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
Code
package com.apache.pdfbox.ocr.tesseract;
import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.ghost4j.Ghostscript;
import org.ghost4j.GhostscriptException;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.ITesseract.RenderedFormat;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class SerachablePDFConversionService {
private static final String OCR_INPUT_FOLDER = System.getenv("OCR_INPUT");
private static final String OCR_OUTPUT_FOLDER = System.getenv("OCR_OUTPUT");
private static final String OCR_SUCCESS_FOLDER = System.getenv("OCR_SUCCESS");
private static final String TESSDATA_PREFIX = System.getenv("TESSDATA_PREFIX");
public static void main(String[] args) {
File inputFiles[] = new File(OCR_INPUT_FOLDER).listFiles();
String tiffFileName = "";
String inputFileName = "";
try {
for (File inputFile : inputFiles) {
inputFileName = inputFile.getName();
System.out.println("Input File Name is [" + inputFileName + "]");
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = inputFile.getName().replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
System.out.println("Tiff File Name is [" + tiffFileName + "]");
System.out.println("Start Time" + new Date());
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(
FileSystems.getDefault()
.getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault()
.getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("End Time" + new Date());
} else {
System.out.println("Searchable PDF creation is failed");
}
} else {
System.out.println("PDF to tiff conversion is failed");
}
} else {
}
}
} catch (Exception e) {
System.out.println("ERROR in Main Method: " + e.getMessage());
System.err.println(e.getMessage());
}
}
public static String covertToTiffAndOCR(ArrayList<String> inputFiles) throws Exception {
String success = "false";
for (String inputFileName : inputFiles) {
System.out.println("File Name " + inputFileName);
String tiffFileName = "";
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = inputFileName.replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
System.out.println("Tiff File Name is [" + tiffFileName + "]");
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(FileSystems.getDefault().getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault().getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
} else {
System.out.println("Searchable PDF creation is failed");
}
} else {
System.out.println("PDF to tiff conversion is failed");
}
} else {
}
}
success = "true";
return success;
}
public static String convertPDFToTiff(String pdfFile, String tiffFile) {
System.out.println("Called=========convertPDFToTiff " + pdfFile + "tiffFile " + tiffFile);
String opSuccess = "false";
Ghostscript gs = Ghostscript.getInstance();
try {
synchronized (gs) {
String[] gsArgs = new String[9];
gsArgs[0] = "-gswin64";
gsArgs[1] = "-q";
gsArgs[2] = "-r300x300";
gsArgs[3] = "-dNOPAUSE";
gsArgs[4] = "-dBATCH";
// gsArgs[5] = "-sDEVICE=tiffg4";
// gsArgs[5] = "-sDEVICE=tiffgray";
gsArgs[5] = "-sDEVICE=tiff24nc";
gsArgs[6] = "-sCompression=lzw";
gsArgs[7] = "-sOutputFile=" + OCR_OUTPUT_FOLDER + File.separator + tiffFile;
gsArgs[8] = OCR_INPUT_FOLDER + File.separator + pdfFile;
// execute and exit interpreter
gs.initialize(gsArgs);
gs.exit();
opSuccess = "true";
}
} catch (GhostscriptException e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
} catch (Exception e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
} finally {
try {
Ghostscript.deleteInstance();
} catch (GhostscriptException e) {
opSuccess = "false";
System.out.println("ERROR: " + e.getMessage());
}
}
return opSuccess;
}
public synchronized static String doOCR(String pdfFile, String tiffFile) {
System.out.println("Called======doOCR " + pdfFile + " tiffFile " + tiffFile);
String opSuccess = "false";
ITesseract instance = new Tesseract();
List<RenderedFormat> formats = new ArrayList<RenderedFormat>();
formats.add(RenderedFormat.PDF);
try {
instance.setDatapath(TESSDATA_PREFIX);
instance.setLanguage("eng+ara");
instance.setOcrEngineMode(1);
instance.setPageSegMode(3);
instance.createDocuments(OCR_OUTPUT_FOLDER + File.separator + tiffFile,
OCR_OUTPUT_FOLDER + File.separator + pdfFile.replaceAll(".pdf", "").replaceAll(".PDF", ""),
formats);
opSuccess = "true";
} catch (TesseractException e) {
opSuccess = "false";
System.out.println("OCR ERROR: " + e.getMessage());
System.err.println(e.getMessage());
} catch (Exception e) {
opSuccess = "false";
System.out.println("OCR ERROR: " + e.getMessage());
System.err.println(e.getMessage());
}
return opSuccess;
}
public void processAllFiles(ArrayList<String> ipFiles) throws Exception {
java.util.List<Callable<String>> tasks = new ArrayList<Callable<String>>(ipFiles.size());
for (String ipFileName : ipFiles) {
System.out.println("11111111" + ipFileName);
tasks.add(processPartTask1(ipFileName));
}
ExecutorService es = Executors.newFixedThreadPool(ipFiles.size());
java.util.List<Future<String>> results = es.invokeAll(tasks);
for (Future<String> result : results)
System.out.println(result.get());
es.shutdown();
}
public Callable<String> processPartTask1(String ipFileName) {
return new Callable<String>() {
public String call() throws Exception {
System.out.println("22222222" + ipFileName);
String tiffFileName = "";
String inputFileName = ipFileName;
String returnvalue = "false";
if (inputFileName != null && inputFileName.length() > 0
&& inputFileName.toLowerCase().indexOf(".pdf") > 0) {
tiffFileName = ipFileName.replaceAll(".pdf", ".tif").replaceAll(".PDF", ".tif");
}
if (SerachablePDFConversionService.convertPDFToTiff(inputFileName, tiffFileName).equals("true")) {
System.out.println("PDF to tiff conversion is successful");
if (SerachablePDFConversionService.doOCR(inputFileName, tiffFileName).equals("true")) {
System.out.println("Searchable PDF creation is successful");
Files.move(FileSystems.getDefault().getPath(OCR_OUTPUT_FOLDER + File.separator + inputFileName),
FileSystems.getDefault().getPath(OCR_SUCCESS_FOLDER + File.separator + inputFileName),
StandardCopyOption.REPLACE_EXISTING);
System.out.println("End Time" + new Date());
returnvalue = "true " + inputFileName;
} else {
System.out.println("Searchable PDF creation is failed");
}
}
return returnvalue;// this needs to be changed
}
};
}
public void processPDFFiles() throws Exception {
File inputFiles[] = new File(OCR_INPUT_FOLDER).listFiles();
String inputFileName = "";
ArrayList<String> files = new ArrayList<String>();
try {
for (File inputFile : inputFiles) {
inputFileName = inputFile.getName();
files.add(inputFileName);
}
} catch (Exception e) {
}
SerachablePDFConversionService serachablePDFConversionService = new SerachablePDFConversionService();
serachablePDFConversionService.processAllFiles(files);
}
}

Related

FileInputStream leaving weird garbage text after skip() call

The need:
I want to write data into compressed and normal format as well. When I'll have to write data into compressed format "useCompression" will be sent as "true" and "useCompression" will be false when data needs to be stored in normal(as it is given to the Writer class) format.
The problem here is, how will I identify whether the data is compressed or not later when Reader class is trying to read the data?
So, to solve the problem, I am writing "1" into file if is "useCompression" is true and "0" if "useCompression" is false.
writing is fine, but when we try to skip the first element using "fIn.skip(1)" cause it is the identifier and not actual data, it is leaving behind some garbage value.
For, example, I am trying to write "2019-07-31" into a file and "useCompression" is false, so my file will hold "02019-07-31" and post "fIn.skip(1)" call it should hold "2019-07-31" but it is holding "^#2019-07-31".
Please help me figure out what I am doing wrong here
I've tried to update Reader class's constructor as:
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
boolean shouldUseDecompression = (1 == firstByte[0]);
if (shouldUseDecompression) {
mFin = new GZIPInputStream(fIn);
}
else {
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
But it does not solve the problem.
The actual code is:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
public class forStackOverflow {
public static void main(String []args) {
// Write to normal file
mReader1 = new Reader(mInputFileName);
mWriter1 = new Writer(mOutputFilename1, false);
int availableBytes = mReader1.availableBytes();
int readBytes = 1000;
while (availableBytes > 0)
{
if (availableBytes >= 1000) {
availableBytes = availableBytes - readBytes;
}
else {
readBytes = availableBytes;
availableBytes = availableBytes - readBytes;
}
mWriter1.write(mReader1.read(readBytes), 0, readBytes);
}
mReader1.close();
mWriter1.close();
}
private static File streamFileForKey(String key)
{
return new File(key);
}
static String mInputFileName = "~/Downloads/inputStream.txt";
static String mOutputFilename1 = "~/Downloads/outputStream.txt";
static Reader mReader1;
static Writer mWriter1;
private static class Writer
{
public Writer(String key, boolean useCompression) {
mKey = key;
try {
FileOutputStream fileOutput = new FileOutputStream(streamFileForKey(key));
if (useCompression) {
fileOutput.write(1);
gOutputStream = new GZIPOutputStream(fileOutput);
}
else {
fileOutput.write(0);
gOutputStream = new DataOutputStream(fileOutput);
}
}
catch (Exception e) {
System.out.println("Got error while opening stream for " + mKey + ". Ex: " + e);
}
}
public boolean write(byte[] bytes, int pos, int len)
{
boolean retVal = true;
if (gOutputStream == null) {
return false;
}
try {
gOutputStream.write(bytes, pos, len);
retVal = true;
}
catch (Exception e) {
System.out.println("Failed to write " + len + " bytes to key " +
mKey + e);
retVal = false;
}
return retVal;
}
public void close()
{
if (gOutputStream != null) {
try {
gOutputStream.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + e);
}
gOutputStream = null;
}
}
private String mKey;
private OutputStream gOutputStream;
}
private static class Reader
{
public Reader(String key)
{
mKey = key;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(key));
if (shouldUseDecompression()) {
long skipped = fIn.skip(1);
mFin = new GZIPInputStream(fIn);
}
else {
long skipped = fIn.skip(1);
mFin = fIn;
}
}
catch (Exception e) {
System.out.println("Failed to open (r) key " + key + " exception : " + e);
}
}
public byte[] read(int len)
{
if (mFin == null) {
return null;
}
byte[] b = null;
try {
b = new byte[len];
int read;
read = mFin.read(b, 0, len);
if (read <= 0) {
return null;
}
}
catch (Exception e) {
System.out.println("Failed to read " + len + " bytes from key " +
mKey + " exception : " + e);
}
return b;
}
public void close()
{
if (mFin != null) {
try {
mFin.close();
}
catch (Exception e) {
System.out.println("Failed to close key " + mKey + " exception : " + e);
}
mFin = null;
}
}
private boolean shouldUseDecompression()
{
boolean retVal = false;
try {
FileInputStream fIn = new FileInputStream(streamFileForKey(mKey));
byte[] firstByte = new byte[1];
int read = fIn.read(firstByte);
// If first byte is `1` the we need to use decompression on it.
retVal = (1 == firstByte[0]);
fIn.close();
}
catch(Exception e) {
System.out.println("Exception in shouldUseDecompression() : " + e);
retVal = false;
}
return retVal;
}
public int availableBytes()
{
int available = 0;
try {
if (mFin != null) {
available = mFin.available();
}
}
catch (IOException e) {
System.out.println("Failed to read available bytes for " + mKey + ". Exception : " + e);
}
return available;
}
private String mKey;
private InputStream mFin;
}
}
The expected result should be, post "fIn.skip(1)" call file should hold "2019-07-31" and not "^#2019-07-31".
After a lot of struggle, I found out that it was the expected result.
^# was nothing but the binary 0 I was writing from Writer class's constructor incase useCompression was false.
From line fileOutput.write(0);.

Google Contact API (No Authentication Header Information Error)

I am new to Google Contact Api. i am trying to retrieve all my contacts using Google Contact API. For this I used Oauth authentication and Google Contact API.
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthParameters.OAuthType;
import com.google.gdata.client.contacts.ContactsService;
import com.google.gdata.data.Link;
import com.google.gdata.data.contacts.ContactEntry;
import com.google.gdata.data.contacts.ContactFeed;
import com.google.gdata.data.contacts.GroupMembershipInfo;
import com.google.gdata.data.extensions.Email;
import com.google.gdata.data.extensions.ExtendedProperty;
import com.google.gdata.data.extensions.Im;
import com.google.gdata.data.extensions.Name;
import com.google.gdata.util.ServiceException;
public class GoogleContactsAccess{
/* This method will authenticate the user credentials passed to it and returns an instance of ContactService class.*/
public ContactsService authenticateId(){
GoogleOAuthParameters oAuthParameters = null;
ContactsService contactService = null;
try{
contactService = new ContactsService("API Project");
oAuthParameters = new GoogleOAuthParameters();
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
oAuthParameters.setScope("https://www.google.com/m8/feeds");
oAuthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oAuthParameters.addCustomBaseParameter("xoauth_requestor_id", "my ID#gmail.com");
contactService.setOAuthCredentials(oAuthParameters,new OAuthHmacSha1Signer());
contactService.getRequestFactory().setHeader("GData-Version", "3.0");
}catch(Exception e){
e.printStackTrace();
}
return contactService;
}
/* This method will print details of all the contacts available in that particular Google account. */
public void printAllContacts(ContactsService myService)throws ServiceException, IOException {
// Request the feed
URL feedUrl = new URL("https://www.google.com/m8/feeds/contacts/default/full?v=3.0&alt=json'");
// The query that will retrieve all contacts
Query myQuery = new Query(feedUrl);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
// Print the results
System.out.println(resultFeed.getTitle().getPlainText());
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName()) {
Name name = entry.getName();
if (name.hasFullName()) {
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi()) {
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
System.out.println("\t\t" + fullNameToDisplay);
} else {
System.out.println("\t\t (no full name found)");
}
if (name.hasNamePrefix()) {
System.out.println("\t\t" + name.getNamePrefix().getValue());
} else {
System.out.println("\t\t (no name prefix found)");
}
if (name.hasGivenName()) {
String givenNameToDisplay = name.getGivenName().getValue();
if (name.getGivenName().hasYomi()) {
givenNameToDisplay += " (" + name.getGivenName().getYomi() + ")";
}
System.out.println("\t\t" + givenNameToDisplay);
} else {
System.out.println("\t\t (no given name found)");
}
if (name.hasAdditionalName()) {
String additionalNameToDisplay = name.getAdditionalName().getValue();
if (name.getAdditionalName().hasYomi()) {
additionalNameToDisplay += " (" + name.getAdditionalName().getYomi() + ")";
}
System.out.println("\t\t" + additionalNameToDisplay);
} else {
System.out.println("\t\t (no additional name found)");
}
if (name.hasFamilyName()) {
String familyNameToDisplay = name.getFamilyName().getValue();
if (name.getFamilyName().hasYomi()) {
familyNameToDisplay += " (" + name.getFamilyName().getYomi() + ")";
}
System.out.println("\t\t" + familyNameToDisplay);
} else {
System.out.println("\t\t (no family name found)");
}
if (name.hasNameSuffix()) {
System.out.println("\t\t" + name.getNameSuffix().getValue());
} else {
System.out.println("\t\t (no name suffix found)");
}
} else {
System.out.println("\t (no name found)");
}
System.out.println("Email addresses:");
for (Email email : entry.getEmailAddresses()) {
System.out.print(" " + email.getAddress());
if (email.getRel() != null) {
System.out.print(" rel:" + email.getRel());
}
if (email.getLabel() != null) {
System.out.print(" label:" + email.getLabel());
}
if (email.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("IM addresses:");
for (Im im : entry.getImAddresses()) {
System.out.print(" " + im.getAddress());
if (im.getLabel() != null) {
System.out.print(" label:" + im.getLabel());
}
if (im.getRel() != null) {
System.out.print(" rel:" + im.getRel());
}
if (im.getProtocol() != null) {
System.out.print(" protocol:" + im.getProtocol());
}
if (im.getPrimary()) {
System.out.print(" (primary) ");
}
System.out.print("\n");
}
System.out.println("Groups:");
for (GroupMembershipInfo group : entry.getGroupMembershipInfos()) {
String groupHref = group.getHref();
System.out.println(" Id: " + groupHref);
}
System.out.println("Extended Properties:");
for (ExtendedProperty property : entry.getExtendedProperties()) {
if (property.getValue() != null) {
System.out.println(" " + property.getName() + "(value) = " +
property.getValue());
} else if (property.getXmlBlob() != null) {
System.out.println(" " + property.getName() + "(xmlBlob)= " +
property.getXmlBlob().getBlob());
}
}
Link photoLink = entry.getContactPhotoLink();
String photoLinkHref = photoLink.getHref();
System.out.println("Photo Link: " + photoLinkHref);
if (photoLink.getEtag() != null) {
System.out.println("Contact Photo's ETag: " + photoLink.getEtag());
}
System.out.println("Contact's ETag: " + entry.getEtag());
}
}
public static void main(String args[]){
try {
GoogleContactsAccess googleContactsAccess = new GoogleContactsAccess();
ContactsService contactSrv = googleContactsAccess.authenticateId();
googleContactsAccess.printAllContacts(contactSrv);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
i tried the above code. i am getting the below exception
java.lang.NullPointerException: No authentication header information
at com.google.gdata.util.AuthenticationException.initFromAuthHeader(AuthenticationException.java:96)
at com.google.gdata.util.AuthenticationException.(AuthenticationException.java:67)
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:608)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:564)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:560)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:538)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:536)
at com.google.gdata.client.Service.getFeed(Service.java:1135)
at com.google.gdata.client.Service.getFeed(Service.java:1077)
at com.google.gdata.client.GoogleService.getFeed(GoogleService.java:676)
at com.google.gdata.client.Service.getFeed(Service.java:1034)
at com.cohere.getcontacts.GoogleContactsAccess.printAllContacts(GoogleContactsAccess.java:59)
at com.cohere.getcontacts.GoogleContactsAccess.main(GoogleContactsAccess.java:197)
so any one help me to resolve the problem thanks in advance
It looks like you are using ConsumerKey as both key and secret in your code :
oAuthParameters.setOAuthConsumerKey("ConsumerKey");
oAuthParameters.setOAuthConsumerSecret("ConsumerKey");
You need to use the correct ConsumerSecret of your app

upload file is not store

The file which i am trying to store in the back end is not a valid directory.. I think the code has a Unix directory config which i need to change to make this work in your windows.
how i can identify the directory where the file is trying to be stored.
i am getting the following error.
[com.keenan.oacommon.forms.services.FormServiceImpl] [checkFileDtlPathCreateIfNotExists] - strFileMstPath is not valid
[INFO ] [java.lang.Class] [processListFiles] - strFinalUploadPath []
[INFO ] [com.keenan.oacommon.forms.services.FormServiceImpl] [verifyFilePath] - Validating path []
[ERROR] [com.keenan.oacommon.forms.services.FormServiceImpl] [verifyFilePath] - strFilePath is NULL
[ERROR] [java.lang.Class] [processListFiles] - File upload path is not valid
here is my java code..
#Override
public boolean verifyFilePath(String inFilePath) {
boolean isFilePathValid = false;
String strFilePath = inFilePath;
logger.info("Validating path [" + strFilePath + "]");
if (strFilePath == null || strFilePath.equalsIgnoreCase("")) {
logger.error("strFilePath is NULL");
isFilePathValid = false;
} else {
try {
File fileUploadDir = new File(strFilePath);
if (fileUploadDir.exists() && fileUploadDir.isDirectory()) {
logger.error("File Path [" + strFilePath + "] is good");
isFilePathValid = true;
} else {
logger.warn("File Path [" + strFilePath + "] is not valid");
isFilePathValid = false;
}
} catch (Exception e) {
isFilePathValid = false;
logger.error("Exception while validating File Path [" + strFilePath + "] - " + e.getMessage(), e);
}
}
return isFilePathValid;
}
#Override
public String checkFileDtlPathCreateIfNotExists(String inFilePath, String inAppSeqNo, String inUploadSeqNo) {
boolean isFilePathValid = false;
/* Main directory (all file uploads) */
String strFileMstPath = null;
File fileUploadMstDir = null;
/* Sub directory (file uploads per application) */
String strFileDtlAppPath = null;
File fileUploadDtlAppDir = null;
/* Sub-sub directory (file uploads per upload request) */
String strFileDtlAppUploadPath = null;
File fileUploadDtlAppUploadDir = null;
boolean fileDirExists = false;
String strFinalReturnPath = null;
if (inFilePath == null || inFilePath.equalsIgnoreCase("")) {
logger.error("inFilePath is NULL");
isFilePathValid = false;
} else {
try {
if (!inFilePath.endsWith("/"))
strFileMstPath = inFilePath + "/";
else
strFileMstPath = inFilePath;
fileUploadMstDir = new File(strFileMstPath);
if (fileUploadMstDir.exists() && fileUploadMstDir.isDirectory()) {
logger.error("strFileMstPath is good");
strFileDtlAppPath = strFileMstPath + inAppSeqNo + "/";
fileUploadDtlAppDir = new File(strFileDtlAppPath);
if (fileUploadDtlAppDir.exists() && fileUploadDtlAppDir.isDirectory()) {
fileDirExists = true;
logger.debug("fileUploadDtlAppDir [" + fileUploadDtlAppDir.toString() + "] exists and is a dir");
} else {
fileDirExists = fileUploadDtlAppDir.mkdir();
}
if (fileDirExists) {
/* Set fileDirExists to false for the next check */
fileDirExists = false;
strFileDtlAppUploadPath = strFileDtlAppPath + inUploadSeqNo + "/";
fileUploadDtlAppUploadDir = new File(strFileDtlAppUploadPath);
if (fileUploadDtlAppUploadDir.exists() && fileUploadDtlAppUploadDir.isDirectory()) {
fileDirExists = true;
logger.debug("fileUploadDtlAppUploadDir [" + fileUploadDtlAppUploadDir.toString()
+ "] exists and is a dir");
} else {
fileDirExists = fileUploadDtlAppUploadDir.mkdir();
}
strFinalReturnPath = strFileDtlAppUploadPath;
} else
logger.error("Could not create strFileDtlAppPath [" + strFileDtlAppPath
+ "] - not attempting to create strFileDtlAppUploadPath [" + strFileDtlAppUploadPath + "]");
if (fileDirExists)
isFilePathValid = true;
else
isFilePathValid = false;
} else {
logger.info("strFileMstPath is not valid");
isFilePathValid = false;
}
} catch (Exception e) {
isFilePathValid = false;
logger.error("Exception while validating filePath - " + e.getMessage(), e);
}
}
if (isFilePathValid)
return strFinalReturnPath;
else
return "";
}
#Override
#Transactional(readOnly = true)
public FileUpload getUploadedFileBySeqNo(int inFileSeqNo) {
FileUpload fileUploadInstance = null;
try {
logger.debug("Fetching FileUpload for inFileUploadSeqNo [" + inFileSeqNo + "]");
fileUploadInstance = FormsHelper.getFormDAO().getUploadedFileDetailsBySeqNo(inFileSeqNo);
logger.debug("FileUpload for inFileUploadSeqNo[" + inFileSeqNo + "] is [" + fileUploadInstance.toString() + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching FileUpload for inFileUploadSeqNo [" + inFileSeqNo + "] - " + e.getMessage(), e);
fileUploadInstance = null;
}
return fileUploadInstance;
}
#Override
#Transactional(readOnly = true)
public FileUpload getUploadedFileByName(String inFileName, String inUploadSeqNo, String inAppSeqNo) {
FileUpload fileUploadInstance = null;
int uploadSeqNo = 0;
int appSeqNo = 0;
try {
uploadSeqNo = Integer.parseInt(inUploadSeqNo);
appSeqNo = Integer.parseInt(inAppSeqNo);
logger.debug("Fetching FileUpload for inFileName [" + inFileName + "]");
fileUploadInstance = FormsHelper.getFormDAO().getUploadedFileDetailsByName(inFileName, uploadSeqNo, appSeqNo);
logger.debug("FileUpload for inFileName [" + inFileName + "] is [" + fileUploadInstance.toString() + "]");
} catch (Exception e) {
logger.error("Exception while fetching FileUpload for inFileName [" + inFileName + "] - " + e.getMessage(), e);
fileUploadInstance = null;
}
return fileUploadInstance;
}
#Override
#Transactional(readOnly = false)
public boolean saveUploadedFileInfo(FileUpload inFileUpload) {
boolean fileUploadInfoSavedSuccessfully = false;
try {
if (inFileUpload == null) {
logger.error("inFileUpload is NULL / Blank");
fileUploadInfoSavedSuccessfully = false;
} else {
FormsHelper.getFormDAO().saveUploadedFileInfo(inFileUpload);
fileUploadInfoSavedSuccessfully = true;
}
} catch (Exception e) {
logger.error("Exception while saving FileUpload - " + e.getMessage(), e);
fileUploadInfoSavedSuccessfully = false;
}
return fileUploadInfoSavedSuccessfully;
}
#Override
#Transactional(readOnly = true)
public List<FileUpload> getUploadedFilesList(int inUploadSeqNo) {
List<FileUpload> uploadedFilesList = null;
try {
logger.debug("Fetching FileUpload for inFileUploadSeqNo [" + inUploadSeqNo + "]");
uploadedFilesList = FormsHelper.getFormDAO().getUploadedFilesList(inUploadSeqNo);
logger.debug("FileUpload for inUploadSeqNo [" + inUploadSeqNo + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching FileUpload for inUploadSeqNo [" + inUploadSeqNo + "] - " + e.getMessage(), e);
uploadedFilesList = null;
}
return uploadedFilesList;
}
#Override
public Map<String, String> getUserNUploadDetailsForMail(int appSeqNo, String emailAddress) {
Map<String, String> details = new HashMap<String, String>();
try {
logger.debug("Fetching getUserNUploadDetailsForMail appSeqNo =[" + appSeqNo + "]" + "and emailAddress = [" + emailAddress
+ "]");
details = FormsHelper.getFormDAO().getUserNUploadDetailsForMail(appSeqNo, emailAddress);
logger.debug("Fetched details [" + details + "]");
} catch (Exception e) {
logger.error("Exceoption while fetching getUserNUploadDetailsForMail " + e.getMessage(), e);
}
return details;
}
Thanks..

WebLogic EJB 8.1 unhandled exception?

I am seeing the following error in logs from last week:
<Feb 7> <Warning> <WLW> <000000> <Id=top-level; Method=processes.FTPInboundProcess.subscription(); Failure=com.bea.wli.bpm.runtime.UnhandledProcessException: Unhandled process exception [ServiceException]>
<Feb 7> <Info> <EJB> <BEA-010213> <Message-Driven EJB: AsyncDispatcher's transaction was rolledback. The transaction details are: Xid=BEA1-3C63D2E9CC47D571774C(183265728),Status=Rolled back.
The code is below:
FTPInboundProcess.jpd
package processes;
import com.bea.data.RawData;
import com.bea.jpd.JpdContext;
import com.bea.jpd.JpdContext.ExceptionInfo;
import com.bea.jpd.ProcessDefinition;
import com.bea.wli.eventGenerator.FileEventGeneratorDocument;
import com.bea.wli.eventGenerator.TimerEventGeneratorDocument;
import com.bea.xml.XmlObject;
import com.bea.xml.XmlTokenSource;
import com.integration.exception.AppException;
import com.integration.util.EnvProperties;
import com.integration.util.KeyGenerator;
import com.integration.util.LogParameters;
import com.integration.util.MessageDataOperation;
import com.integration.util.PASLevel;
import com.integration.util.PASLogger;
import com.integration.util.StringEncrypter;
import com.integration.util.Utility;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import ftp.InterfaceDocument.Interface;
import ftp.InterfacesDocument;
import ftp.InterfacesDocument.Factory;
import ftp.InterfacesDocument.Interfaces;
import inbound.IFileAdapter;
import inbound.impl.FTPClientImpl;
import inbound.impl.FileClientImpl;
import inbound.impl.SFTPClientImpl;
import outbound.PostProcess;
public class FTPInboundProcess
implements ProcessDefinition
{
public boolean bIsFtpDeleteSuccess;
public boolean isWriteToLocalDirSuccess;
public String fileArchiveDir;
public boolean isChDirSuccess;
public byte[] ftpData;
public boolean isPutSuccess;
public TimerEventGeneratorDocument timerEventGeneratorDoc;
public FileEventGeneratorDocument fileEventGeneratorDoc;
public RawData inputRawData;
public IFileAdapter ftp;
public static String PROCESS_NAME = "FileXFRI";
public String processLabel;
public long processStartTime;
public long originalStartTime;
public long processId;
public long parentProcessId;
public String key;
public String protocol;
public String documentKey;
public boolean bAppException;
public boolean bMesageInorder;
public boolean bNewMessage;
public String errorStr;
public String sftpkey;
public String fileName;
public int fileCounter;
public String emailUser;
public transient Logger logger;
static final long serialVersionUID = 1L;
public FTPInboundProcess.Callback callback;
public String ftpHostName;
public int ftpPort;
public String ftpUserName;
public String ftpPassword;
public String ftpDir;
public String ftpArchDir;
public String ftpLocalDir;
public String filePattern;
public String isFtpPostActionDeleteRequired;
public String isFtpPostActionArchiveRequired;
public String isEncryptRequired;
public long fileSize;
public String interfaceId;
public String emailYN;
public HashMap dataMap;
public XmlObject inputXML;
public String[] listOfFTPFiles;
public boolean isFTPConnected;
JpdContext context;
int postProcessReturnvalue;
public void subscription(XmlObject x0, TimerEventGeneratorDocument x1)
{
this.inputXML = x0;
this.timerEventGeneratorDoc = x1;
}
void initProcessVariables()
{
this.processStartTime = System.currentTimeMillis();
this.processLabel = "";
this.processId = 0L;
this.postProcessReturnvalue = 0;
this.parentProcessId = 0L;
this.documentKey = "";
this.bAppException = false;
this.errorStr = "";
this.fileSize = 0L;
this.interfaceId = "";
this.emailYN = "";
this.emailUser = "";
this.dataMap = new HashMap();
}
public void init()
throws Exception
{
try
{
this.logger = PASLogger.getLogger("PAS." + PROCESS_NAME);
this.logger.log(PASLevel.FINER, "Timer InputXML :" + this.inputXML.xmlText());
this.logger.log(PASLevel.FINER, "Type::" + this.inputXML.getClass());
initProcessVariables();
String xmlText = this.inputXML.xmlText();
this.logger.log(PASLevel.FINER, "INPUT::" + xmlText);
InterfacesDocument input = InterfacesDocument.Factory.parse(xmlText);
this.interfaceId = input.getInterfaces().getInterfaceArray()[0].getId();
this.logger.log(PASLevel.FINER, "Interface id : " + ((InterfacesDocument)this.inputXML).getInterfaces().getInterfaceArray(0).getId());
this.processId = KeyGenerator.generateKey("PROCESS_ID");
this.documentKey = (PROCESS_NAME + "::FTP::" + this.interfaceId + "::" + this.processId);
this.key = (PROCESS_NAME + "::FTP::" + this.interfaceId + "::" + this.processId);
this.logger.log(PASLevel.FINER, "Parsing Input Document End:" + System.currentTimeMillis());
this.processLabel = ("Key=" + this.key + ",ProcessId=" + this.processId + ",InterfaceId=" + this.interfaceId);
this.processStartTime = System.currentTimeMillis();
MessageDataOperation.insertMessageData(this.processId, this.documentKey, PROCESS_NAME, this.key, this.processStartTime, this.parentProcessId);
updateProcessLabel(this.processLabel);
this.protocol = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".PROTOCOL");
this.ftpHostName = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPHOST");
this.logger.log(PASLevel.FINEST, " ftpHostName :" + this.ftpHostName);
try
{
this.ftpPort = Integer.parseInt(EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".PORT"));
}
catch (Exception e)
{
this.logger.log(PASLevel.WARNING, "FTP Port not defined for the Interface :" + this.interfaceId + " .... using default port");
this.ftpPort = 21;
}
this.logger.log(PASLevel.FINE, " ftpPort :" + this.ftpPort);
this.sftpkey = Utility.nullToStr(EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".SFTPKEY"));
this.logger.log(PASLevel.FINE, " SFTPKEY :" + this.sftpkey);
this.dataMap.put("SFTPKEY", this.sftpkey);
this.ftpUserName = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPUSER");
this.logger.log(PASLevel.FINE, " ftpUserName :" + this.ftpUserName);
this.ftpPassword = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPPASSWORD");
this.logger.log(PASLevel.FINE, " ftpPassword :" + this.ftpPassword);
this.filePattern = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FILEPATTERN");
this.logger.log(PASLevel.FINE, " filePattern :" + this.filePattern);
this.ftpArchDir = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPARCH");
this.logger.log(PASLevel.FINE, " ftpArchDir :" + this.ftpArchDir);
this.ftpDir = Utility.nullToStr(EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPDIR"));
this.ftpLocalDir = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPLOCALDIR");
this.fileArchiveDir = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FILEARCHIVEDIR");
this.isFtpPostActionDeleteRequired = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPPOSTDELETE");
this.isEncryptRequired = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".ENCRYPT");
this.isFtpPostActionArchiveRequired = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".FTPPOSTARCHIVE");
this.logger.log(PASLevel.FINE, " ftpLocalDir :" + this.ftpLocalDir);
this.logger.log(PASLevel.FINE, " isFtpPostActionArchiveRequired :" + this.isFtpPostActionArchiveRequired);
this.logger.log(PASLevel.FINE, " isFtpPostActionDeleteRequired :" + this.isFtpPostActionDeleteRequired);
return;
}
catch (Exception e)
{
e.printStackTrace();
this.logger.log(PASLevel.SYSTEM_ERROR, e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
void updateProcessLabel(String label)
{
this.context.setProcessLabel(this.processLabel);
}
public boolean isAppException()
{
return this.bAppException;
}
public boolean isMessageInorder()
{
return this.bMesageInorder;
}
String getErrorEmailUser(Object[] args)
throws Exception
{
try
{
if ((args == null) || (args.length == 0)) {
return "";
}
this.emailUser = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".EMAIL_USER");
return this.emailUser;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
}
return "";
}
public void context_onInitialMessageFailure(String methodName, Object[] args)
throws Exception
{
try
{
this.processId = Utility.context_onInitialMessageFailure(PROCESS_NAME, args, this.logger);
String body = "Due to the error the interface file could not be sent. \n";
body = body + "System will retry the file after sometime.";
this.errorStr = "";
sendErrorEmail(body, getErrorEmailUser(args));
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void globalExceptionHandler()
throws Exception
{
Exception e = null;
try
{
e = this.context.getExceptionInfo().getException();
this.errorStr = e.getMessage();
}
catch (Throwable localThrowable) {}
this.bAppException = Utility.globalExceptionHandler(e, this.logger, PROCESS_NAME, this.processId, this.parentProcessId, "", this.inputRawData.byteValue(), "xml", true);
if (this.bAppException) {
this.processLabel = (this.processLabel + ",AppException , " + e.getClass());
} else {
this.processLabel = (this.processLabel + ",SystemException , " + e.getClass());
}
updateProcessLabel(this.processLabel);
this.logger.log(PASLevel.INFO, "Exception Raised in Process , Process Label:" + this.processLabel);
}
public void systemExceptionProcessing()
throws Exception
{}
public void sendDataErrorEmail()
throws Exception
{
String body = "Due to the error the file could not sent \n\n\n";
body = body + ",Filename=" + this.fileName;
this.emailUser = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".EMAIL_USER");
sendErrorEmail(body, this.emailUser);
}
public void sendErrorEmail(String body, String to)
throws Exception
{
String subject = "";
String cc = "";
String bcc = "";
HashMap map = new HashMap();
try
{
body = body + this.errorStr;
subject = "Due to the error the interface file could not be sent. " + this.key;
if ((to == null) || (to.equals(""))) {
to = Utility.getErrorEmail();
}
Utility.sendEmail(PROCESS_NAME, this.processId, "Business", body, subject, to, "", cc, bcc, "");
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public boolean isMessageInorder1()
{
return this.bMesageInorder;
}
public void handleAppException()
throws Exception
{}
public void cleanup()
throws Exception
{
this.inputRawData = null;
}
public void setFilesCount()
throws Exception
{
this.fileCounter = 0;
}
public void decrementFileCount()
throws Exception
{
this.fileCounter += 1;
}
public boolean checkFileCounterCondition()
{
return this.fileCounter < this.listOfFTPFiles.length;
}
public void raiseFTPConnectionException()
throws Exception
{
Exception e = new Exception("Error: FTP Connection Failure");
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error: FTP Connection Failure", new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
public boolean isFTPConnected()
{
return this.ftp.isConnected();
}
public boolean checkNoOfFilesReceived()
{
if ((this.listOfFTPFiles != null) && (this.listOfFTPFiles.length > 0)) {
return true;
}
return false;
}
public void sendEmail()
throws Exception
{
String subject = "";
String to = "";
String cc = "";
String bcc = "";
String body = "";
HashMap map = new HashMap();
try
{
this.emailYN = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".EMAIL_YN");
if ((this.emailYN != null) && (!this.emailYN.equals("Y"))) {
return;
}
this.emailUser = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".EMAIL_USER");
body = "Interface has processed the following file succesfully. :Filename:" + this.fileName;
to = this.emailUser;
subject = "Interface has sent the following file succesfully. Key::" + this.key + ":Filename:" + this.fileName;
if ((to == null) || (to.equals("")))
{
this.logger.log(PASLevel.WARNING, "ProcessLabel:" + this.processLabel + ":Error:" + "Email Receipent not specified.", new LogParameters(this.processId, PROCESS_NAME, this.processLabel, null));
to = Utility.getErrorEmail();
}
this.logger.log(PASLevel.FINE, "SCPExtract ... Sending an Email");
Utility.sendEmail(PROCESS_NAME, this.processId, "Business", body, subject, to, "", cc, bcc, "");
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void createFTPClient()
throws Exception
{
if (this.protocol.equalsIgnoreCase("SFTP"))
{
this.ftp = new SFTPClientImpl();return;
}
if (this.protocol.equalsIgnoreCase("FTP"))
{
this.ftp = new FTPClientImpl();return;
}
this.ftp = new FileClientImpl();
}
public void connect()
throws Exception
{
try
{
if (((this.protocol.equals("FTP")) || (this.protocol.equals("SFTP"))) && ((this.ftpUserName == null) || (this.ftpPassword == null) || (this.ftpHostName == null)))
{
Exception e = new Exception("ftpUserName = null || this.ftpPassword = null || ftpHostName = null");
this.logger.log(PASLevel.SYSTEM_ERROR, e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
this.logger.log(PASLevel.FINE, "Connecting to the server .... :" + this.ftpHostName);
this.logger.log(PASLevel.FINE, "Host:" + this.ftpHostName + ":User:" + this.ftpUserName + ":Password:" + this.ftpPassword);
this.ftp.connect(this.ftpHostName, this.ftpPort, this.ftpUserName, this.ftpPassword, this.dataMap);
this.logger.log(PASLevel.FINE, "Connected to the server:" + this.ftpHostName);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void getRemoteFilesList()
throws Exception
{
try
{
this.logger.log(PASLevel.FINE, "Retriving List of Files .... :FtpDir:" + this.ftpDir);
this.logger.log(PASLevel.FINE, "File Pattern .... ::" + this.filePattern);
if (!this.ftpLocalDir.equals("")) {
this.ftp.setLocalDir(this.ftpLocalDir);
}
if (!this.ftpDir.equals("")) {
this.ftp.changeWorkingDirectory(this.ftpDir);
}
ArrayList list = this.ftp.listFiles(this.filePattern);
this.listOfFTPFiles = new String[list.size()];
System.arraycopy(list.toArray(), 0, this.listOfFTPFiles, 0, list.size());
for (int ind = 0; ind < this.listOfFTPFiles.length; ind++) {
this.logger.log(PASLevel.FINE, "List of Files:" + this.listOfFTPFiles[ind]);
}
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, "ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
e.printStackTrace();
throw e;
}
}
public void disconnect()
throws Exception
{
this.logger.log(PASLevel.FINE, "Zero input files ..... Disconnecting ...");
this.ftp.disconnect();
}
public void getFile()
throws Exception
{
try
{
this.fileName = this.listOfFTPFiles[this.fileCounter];
if (this.fileName == null) {
throw new Exception(" FTP fileName is null");
}
ByteArrayOutputStream getFileByteArrayOutputStream = this.ftp.getFile(this.fileName);
this.ftpData = getFileByteArrayOutputStream.toByteArray();
this.logger.log(PASLevel.FINE, "Got File Data ...");
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void backup()
throws Exception
{
try
{
String archiveYN = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".LOCALARCHIVE");
String asciiYN = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".ASCII_YN");
if (archiveYN.equals("Y"))
{
byte[] fileArchData;
if ((asciiYN.equals("Y")) && (this.isEncryptRequired.equals("Y")))
{
StringEncrypter encrypter = new StringEncrypter();
fileArchData = encrypter.encrypt(new String(this.ftpData)).getBytes();
}
else
{
fileArchData = this.ftpData;
}
Utility.createFile(this.fileArchiveDir + "/" + this.interfaceId + "_" + this.processId + "_" + this.fileName, fileArchData);
}
this.logger.log(PASLevel.FINE, "File Archieved ...::" + archiveYN + "::EncryptionYN::" + this.isEncryptRequired);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void disconnect1()
throws Exception
{
try
{
this.ftp.disconnect();
return;
}
catch (Throwable localThrowable) {}
}
public void disconnect2()
throws Exception
{
try
{
this.ftp.disconnect();
return;
}
catch (Throwable localThrowable) {}
}
public void doPostProcess()
throws Exception
{
try
{
String sapPostProcessClass = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".POSTPROCESS");
sapPostProcessClass = "washpost.pas.outbound.impl." + sapPostProcessClass;
Map fileMap = new HashMap();
this.logger.log(PASLevel.FINE, "PostProcess ::" + sapPostProcessClass);
if (!sapPostProcessClass.equals(""))
{
Class c = Class.forName(sapPostProcessClass);
PostProcess postProcess = (PostProcess)c.newInstance();
String passByRefFlag = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".REFERENCE_YN");
byte[] tempFtpData = this.ftpData;
if ((passByRefFlag != null) && (passByRefFlag.equalsIgnoreCase("Y")))
{
String localDir = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".LOCALDIR");
String localFileName = localDir + System.getProperty("file.separator") + this.fileName;
Utility.createFile(localFileName, this.ftpData);
tempFtpData = new byte[0];
}
this.postProcessReturnvalue = postProcess.doUpload(tempFtpData, this.fileName, this.interfaceId, this.processId, fileMap);
this.logger.log(PASLevel.FINE, "***** PostProcess Return::" + this.postProcessReturnvalue);
return;
}
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
this.postProcessReturnvalue = -1;
this.errorStr = e.getMessage();
throw e;
}
}
public void writeFileToExceptionDir()
throws Exception
{
String exceptionDirPath = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".EXCEPTION_DIR_PATH");
try
{
Utility.createFile(exceptionDirPath + "/" + this.fileName, this.ftpData);
String message = "Error while performing post process :: " + this.fileName + ", File is stored in Exception Directory. ";
message = message = "::ErrorMessage::" + this.errorStr;
performSendErrorEmail(message);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void writeFileToInputDir()
throws Exception
{
String inputDirPath = EnvProperties.getProperty(PROCESS_NAME + "." + this.interfaceId + ".INPUT_DIR_PATH");
try
{
String completeFileName = this.interfaceId + "." + this.fileName;
Utility.createFile(inputDirPath + "/" + completeFileName, this.ftpData);
String message = "Interface has saved the file: " + completeFileName + " to input Directory ";
performSendErrorEmail(message);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void updateLog()
throws Exception
{
try
{
this.processLabel = (this.processLabel + ",FilesProcessed=" + this.fileCounter);
updateProcessLabel(this.processLabel);
MessageDataOperation.updateMessageSentData(this.processId, "Y");
this.logger.log(PASLevel.INFO, "Process Completed, Process Label:" + this.processLabel);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
public void updateLog1()
throws Exception
{
try
{
this.processLabel += ",FilesProcessed=0";
updateProcessLabel(this.processLabel);
MessageDataOperation.updateMessageSentData(this.processId, "Y");
this.logger.log(PASLevel.INFO, "Process Completed, Process Label:" + this.processLabel);
return;
}
catch (Exception e)
{
this.logger.log(PASLevel.SYSTEM_ERROR, ":ProcessLabel:" + this.processLabel + ":Error:" + e.getMessage(), new LogParameters(this.processId, PROCESS_NAME, this.processLabel, e));
throw e;
}
}
}
This code makes use of a FTP timer even generator to kick off a transaction daily. The problem is, when the timer triggers its spitting out that error and at the same time the transaction is going through. I did try multiple try/catch blocks, but could not get any additional information so far. This has been happening ever since a server outage. Can anyone suggest

How to insert and retrieve key from registry editor

I am new to cryptography. I have to develop project based on cryptography..In part of my project I have to insert a key to the registry and afterwards I have to retrieve the same key for decryption.. I done until getting the path of the registry ..
Here I am showing my code:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public final class Project {
public static final String readRegistry(String location, String key) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"' + location + "\" /v " + key);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
if (!output.contains("\t")) {
return null;
}
// Parse out the value
String[] parsed = output.split("\t");
return parsed[parsed.length - 1];
} catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw = new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1) {
System.out.println("Reading" + c);
sw.write(c);
}
} catch (IOException e) {
System.out.println("Exception in run() " + e);
}
}
public String getResult() {
System.out.println("Content " + sw.toString());
return sw.toString();
}
}
public static boolean addValue(String key, String valName, String val) {
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg add \"" + key + "\" /v \"" + valName + "\" /d \"\\\"" + val + "\\\"\" /f");
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
String output = reader.getResult();
System.out.println("Processing........ggggggggggggggggggggg." + output);
// Output has the following format:
// \n<Version information>\n\n<key>\t<registry type>\t<value>
return output.contains("The operation completed successfully");
} catch (Exception e) {
System.out.println("Exception in addValue() " + e);
}
return false;
}
public static void main(String[] args) {
// Sample usage
JAXRDeleteConcept hc = new JAXRDeleteConcept();
System.out.println("Before Insertion");
if (JAXRDeleteConcept.addValue("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU", "REG_SZ", "Muthus")) {
System.out.println("Inserted Successfully");
}
String value = JAXRDeleteConcept.readRegistry("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\ComDlg32\\OpenSaveMRU" , "Project_Key");
System.out.println(value);
}
}
But i dont know how to insert a key in a registry and read the particular key which i inserted..Please help me..
Thanks in advance..
It would be a lot easier to use the JRegistry library to edit the registry, rather than execute commands.

Categories

Resources