Fixing a Zip Path Traversal Vulnerability in Android app in Google Play Store - android-security

The question has been asked (and answered) but I have not been able to get it to work in my code.
This is the support document:
https://support.google.com/faqs/answer/9294009
I have tried to use the answer from here:
Fixing a Zip Path Traversal Vulnerability In Android
My original code:
public void copyFiles() {
try {
String roms_dir = mm.getMainHelper().getInstallationDIR();
File fm = new File(roms_dir + File.separator + "saves/"
+ "dont-delete-" + getVersion() + ".bin");
if (fm.exists())
return;
fm.mkdirs();
fm.createNewFile();
// Create a ZipInputStream to read the zip file
BufferedOutputStream dest = null;
InputStream fis = mm.getResources().openRawResource(R.raw.files);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
// Loop over all of the entries in the zip file
int count;
byte data[] = new byte[BUFFER_SIZE];
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (!entry.isDirectory()) {
String destination = roms_dir;
String destFN = destination + File.separator
+ entry.getName();
// Write the file to the file system
FileOutputStream fos = new FileOutputStream(destFN);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} else {
File f = new File(roms_dir + File.separator
+ entry.getName());
f.mkdirs();
}
}
zis.close();
String dir = this.getInstallationDIR();
if(!dir.endsWith("/"))dir+="/";
String rompath = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR()!="" ? mm
.getPrefsHelper().getROMsDIR() : dir + "roms";
mm.getDialogHelper()
.setInfoMsg(
"Created or updated: '"
+ dir
+ "' to store save states, cfg files and MAME assets.\n\nBeware, copy or move your zipped ROMs under '"
+ rompath
+ "' directory!\n\nMAME4droid 0.139 uses only 0.139 MAME romset.");
mm.showDialog(DialogHelper.DIALOG_INFO);
} catch (Exception e) {
e.printStackTrace();
}
}
I have tried this:
public void copyFiles() {
try {
String roms_dir = mm.getMainHelper().getInstallationDIR();
File fm = new File(roms_dir + File.separator + "saves/"
+ "dont-delete-" + getVersion() + ".bin");
if (fm.exists())
return;
fm.mkdirs();
fm.createNewFile();
// Create a ZipInputStream to read the zip file
BufferedOutputStream dest = null;
InputStream fis = mm.getResources().openRawResource(R.raw.files);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
// Loop over all of the entries in the zip file
int count;
byte data[] = new byte[BUFFER_SIZE];
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
// Create an outputFile object and check that the path is safe with ensureZipPathSafety
//*
String outputDir = "";
File outputFile = new File(outputDir, entry.getName());
String outputFileName = outputFile.getCanonicalPath();
System.out.println(outputFileName);
try {
ensureZipPathSafety(outputFile, outputDir);
} catch (Exception e) {
e.printStackTrace();
return;
}
//*/
if (!entry.isDirectory()) {
System.out.println("We get past !entry.isDirectory check");
String destination = roms_dir;
String destFN = destination + File.separator
+ entry.getName();
// Write the file to the file system
FileOutputStream fos = new FileOutputStream(destFN);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
} else {
File f = new File(roms_dir + File.separator
+ entry.getName());
f.mkdirs();
}
}
zis.close();
String dir = this.getInstallationDIR();
if(!dir.endsWith("/"))dir+="/";
String rompath = mm.getPrefsHelper().getROMsDIR() != null && mm.getPrefsHelper().getROMsDIR()!="" ? mm
.getPrefsHelper().getROMsDIR() : dir + "roms";
mm.getDialogHelper()
.setInfoMsg(
"Created or updated: '"
+ dir
+ "' to store save states, cfg files and MAME assets.\n\nBeware, copy or move your zipped ROMs under '"
+ rompath
+ "' directory!\n\nMAME4droid 0.139 uses only 0.139 MAME romset.");
mm.showDialog(DialogHelper.DIALOG_INFO);
} catch (Exception e) {
e.printStackTrace();
}
}
private void ensureZipPathSafety(final File outputFile, final String destDirectory) throws Exception {
String destDirCanonicalPath = (new File(destDirectory)).getCanonicalPath();
String outputFilecanonicalPath = outputFile.getCanonicalPath();
String outputFileCanonicalPath = "";
if (!outputFileCanonicalPath.startsWith(destDirCanonicalPath)) {
Object canonicalPath = null;
throw new Exception(String.format("Found Zip Path Traversal Vulnerability with %s", canonicalPath));
}
}

Related

How to download and extract large files from email using window service

I am using the following code in window service to download zip file with particular format from email attachments:
Method to get Emails:
public void GetdownloadfromGmail()
{
try
{
ConfigDetails ConfigDetails = new ConfigDetails();
DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
using (IDbConnection con = Connections.Getsynchconnection())
{
try
{
con.Open();
ConnectionState state = con.State;
con.Close();
if (state == ConnectionState.Open)
{
SentmailCount = 0;
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
if (SentmailCount == 0)
{
string ContentMessage = "SqlConnection is Not Open :" + ex.Message.ToString();
Process SharedProc = new Process();
string EmailID = SharedProc.GetReceipientmailid(new Context(new MailContext()), "", 3);
string[] Receipients = EmailID.Split(',');
//time being profile,pwd is hard coded
GmailClient.GmailClient gc = new GmailClient.GmailClient();
/*Sending attachment(s) with the mail*/
gc.SMTPHost = SecTable.Rows[0]["SmtpHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["SmtpPort"].ToString());
bool IsEnableSsl = Convert.ToBoolean(SecTable.Rows[0]["IsEnableSsl"].ToString());
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["Password"].ToString());
System.Net.Mail.MailAddress address = new System.Net.Mail.MailAddress(SecTable.Rows[0]["Username"].ToString(), SecTable.Rows[0]["DisplayName"].ToString());
gc.sendMail("Connection", Receipients, ContentMessage, null, "", credentials, address, true, IsEnableSsl);
SentmailCount = 1;
}
return;
}
}
Common.Synch.Factory.LogHelpFactory.log.Info("Start Download Mails From Mailbox");
//ConfigDetails ConfigDetails = new ConfigDetails();
//time being profile,pwd is hard coded
// DataTable SecTable = ConfigDetails.GetConfigTableCol(Constant.Seccurity);
if (SecTable.Columns["UserName"] == null && SecTable.Columns["Password"] == null)
{
throw (new Exception("Invalid Profile settings"));
}
using (GmailClient.GmailClient gc = new GmailClient.GmailClient())
{
gc.UseSSL = true;
/*Part to fetch mails from gmail; List<MailMessage> will have all the mails fetched which can be used later to send mails.
The attachments get downloaded as the mails are read.
The MailMessage only includes the basic header information along with the number of attachments processed.
Once all emails are fetched, the client disconnects automatically*/
//Following property will not delete the email from gmail server if set to False, but deletes if it set to True
gc.SMTPHost = SecTable.Rows[0]["IncomingEmailHost"].ToString();
gc.SMTPPortNumber = Convert.ToInt32(SecTable.Rows[0]["IncomingEmailPort"].ToString());
gc.DeleteProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["DeleteEmail"].ToString());
ConfigDetails = new ConfigDetails();
TempPath = ConfigDetails.GetPath(Constant.TempFolder);
//Default AttachmentPath is the path of dll directory. Howeve it can be set exclusilvely as below.
gc.AttachmentPath = TempPath + "\\";
string strUname = SecTable.Rows[0]["Username"].ToString();
string strPwd = SecTable.Rows[0]["Password"].ToString();
gc.Connect(strUname, strPwd);
gc.CopyProcessedMails = Convert.ToBoolean(SecTable.Rows[0]["CopyProcessedEmail"].ToString()); ;
gc.CopyMailTargetFolder = Convert.ToString(SecTable.Rows[0]["CopyMailTargetFolder"].ToString()); ;
Common.Synch.Factory.LogHelpFactory.log.Info("Test ");
if (gc.IsConnected)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Connected");
List<MailMessage> mails = gc.GetMailList();
Common.Synch.Factory.LogHelpFactory.log.Info("Unread Mail Count:" + mails.Count.ToString()); try
{
foreach (MailMessage Mail in mails)
{
try
{
isDeleted = false;
if (null != Mail.Subject)
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.Subject.ToString());
else
Common.Synch.Factory.LogHelpFactory.log.Info(Mail.FromEmail + " (no subject)");
GetMaiilboxtotable(Mail);
//if (isDeleted)
//{
//Mail.UnRead = false;
//Mail.Delete();
//}
}
catch (Exception Ex)
{
//if (Ex.Message == "Could not save attachment to a file")
//{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while processing email:" + Ex.Message.ToString());
Common.Synch.Factory.LogHelpFactory.log.Info("Subject:" + Mail.Subject + ", From:" + Mail.FromName);
//Mail.UnRead = false;
//Mail.Delete();
//}
}
}
}
//if (ListofMails.Count > 0)
//{
//OutlookClient.MovFolderselection();
//}
catch (Exception Ex)
{
//if (ListofMails != null)
//{
// Marshal.ReleaseComObject(ListofMails);
//}
//ListofMails = null;
////OutlookClient.Dispose();
mails = null;
gc.Dispose();
Common.Synch.Factory.LogHelpFactory.log.Error("SearchMails(GetMailFromGmail) failed : ", Ex);
}
finally
{
if (m_MailTable.Rows.Count > 0)
{
SaveEmail();
Common.Synch.Factory.LogHelpFactory.log.Info("Save Email Complete");
}
int Sleeptime = Convert.ToInt32(ConfigDetails.GetResourceSleeptime(Constant.InboundProcess));
if (Sleeptime == 0)
{
Sleeptime = 10000;
}
ConfigDetails = null;
try
{
Thread.Sleep(Sleeptime);
}
catch (ThreadAbortException ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error on thread.Sleep:" + ex.Message.ToString());
}
try
{
this.DownLoadCompleteEventArgs(this, new DownLoadCompleteEventArgs("DownLoad Complete"));
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Info("Error while invoking the thread:" + ex.Message.ToString());
}
Common.Synch.Factory.LogHelpFactory.log.Info("End Download Mails From Inbox");
}
}
// Log
}
}
catch (Exception ex)
{
Common.Synch.Factory.LogHelpFactory.log.Error(ex.Message.ToString());
}
}
Method to save extracted files in database:
public void GetMaiilboxtotable(MailMessage Message)
{
Common.Synch.Common.DeleteFile(TempPath);
try
{
if (Initalize())
{
if (Message.Attachments != null && Message.AttachmentsCount > 0)
{
for (int Count = 0; Count <= Message.AttachmentsCount - 1; Count++)
{
//if (Message.Attachments[Count].AttachmentAttachmentFileName.Substring(Message.Attachments[Count].AttachmentAttachmentFileName.Length - 3, 3).ToUpper() == "MSG")
//{
// Message.Attachments[Count].SaveAsFile(TempPath + "Temp.msg");
// outlookApp = new OutLook.ApplicationClass();
// MsgMail = (OutLook.MailItem)outlookApp.CreateItemFromTemplate(TempPath + "Temp.msg", Type.Missing);
// GetMaiilboxtotable(MsgMail);
// outlookApp = null;
// MsgMail = null;
//}
if (Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "ZIP" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XML" ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "XLS" ||
(Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "DAT"
&& Message.Attachments[Count].AttachmentFileName.Substring(0, 2).ToUpper() == "HJ") ||
Message.Attachments[Count].AttachmentFileName.Substring(Message.Attachments[Count].AttachmentFileName.Length - 3, 3).ToUpper() == "BIN")
{
if (m_MailTable.Columns.Count <= 0)
{
CreateMailTable();
}
isDeleted = true;
DataRow MailRows = m_MailTable.NewRow();
MailRows["MailID"] = Message.FromEmail;
MailRows["MsgDate"] = Message.ReceivedDate;
MailRows["MsgSubject"] = (null == Message.Subject ? string.Empty : Message.Subject);
MailRows["CreateDateTime"] = DateTime.Now;
//string GwAttachmentName = Message.Attachments[Count].AttachmentFileName;
Message.Attachments[Count].DownloadAttachment();// SaveAsFile(TempPath + Message.Attachments[Count].AttachmentFileName);
MailRows["AttachmentName"] = Message.Attachments[Count].AttachmentFileName;
ConvertBinary ConvertBinary = new ConvertBinary();
MailRows["AttachmentFile"] = ConvertBinary.ConverTOBinaryFile(TempPath + "\\" + Message.Attachments[Count].AttachmentFileName);
ConvertBinary.Dispose();
ConvertBinary = null;
//Marshal.ReleaseComObject(synchGwAttachment);
m_MailTable.Rows.Add(MailRows);
//Log
Common.Synch.Factory.LogHelpFactory.log.Info("Add Mail to MailBox Temp Table -" + Message.Attachments[Count].AttachmentFileName);
}
}
}
}
}
catch (Exception ex)
{
Message = null;
Common.Synch.Factory.LogHelpFactory.log.Info(Message.Subject + ":" + ex.ToString());
}
}
Attachment structure is:
In attachment we are sending bin files of objects and these objects further extracted and saved in database.
Problem:
Some times we are receiving large files, so while extracting service hang and stop processing in between. Could you provide me some suggestions and ideas to overcome this issue.
Please let me know if you need more information, I will try my best to provide.
Thanks in advance.
You are using DataTables.
A DataTable is an in-memory copy of relational data.
So all the data you are going to save have to fit into memory.
If you have a lot of records, big records or both this will not do.
I suggest to:
decompress the file inside a temp folder on local file system
insert into the database one file at a time using a SqlCommand
Use parameters in your INSERT command (ie insert into mytable (col1, col2) values (#col1, # col2))

How can i append a pdf into another? Alfresco

How can i append a pdf into another?
I tried using this code, but I am getting java.lang.NullPointerException when i try to getContentInputStream.
what am I doing wrong? How can I attach one pdf to another?
PDDocument pdfTarget = null;
InputStream is = null;
InputStream tis = null;
for (ChildAssociationRef file: quotationsFiles) {
try {
NodeRef toAppend = file.getChildRef(); //workspace://SpacesStore/11bce382-45bf-4c67-95bc-a65361b323ef
ContentReader append = getReader(toAppend);
is = append.getContentInputStream(); // Here iam getting java.lang.NullPointerException
NodeRef targetNodeRef = reportFile.getNodeRef();
ContentReader targetReader = getReader(targetNodeRef);
tis = targetReader.getContentInputStream();
String fileName = String.valueOf(serviceRegistry.getNodeService().getProperty(targetNodeRef, ContentModel.PROP_NAME));
// stream the document in
pdf = PDDocument.load(is);
pdfTarget = PDDocument.load(tis);
// Append the PDFs
PDFMergerUtility merger = new PDFMergerUtility();
merger.appendDocument(pdfTarget, pdf);
merger.setDestinationFileName(fileName);
merger.mergeDocuments();
} catch (Exception e) {
//throw new AlfrescoRuntimeException("IOException", e);
ColorLogUtil.debug(LOGGER, "IOException Error caused by :" + e);
}
}
private ContentReader getReader(NodeRef nodeRef) {
if (serviceRegistry.getNodeService().exists(nodeRef) == false) {
throw new AlfrescoRuntimeException("NodeRef: " + nodeRef + " does not exist");
}
QName typeQName = serviceRegistry.getNodeService().getType(nodeRef);
if (serviceRegistry.getDictionaryService().isSubClass(typeQName, ContentModel.TYPE_CONTENT) == false) {
throw new AlfrescoRuntimeException("The selected node is not a content node");
}
ContentReader contentReader = serviceRegistry.getContentService().getReader(nodeRef, ContentModel.PROP_CONTENT);
if (contentReader == null) {
throw new AlfrescoRuntimeException("The content reader for NodeRef: " + nodeRef + "is null");
}
return contentReader;
}
See if this code works for you:
public NodeRef mergePdfs(List<NodeRef> nodeRefList, String fileName,NodeRef destinationNode)
throws FileNotFoundException,FileExistsException,Exception {
InputStream originalInputStream = null;
ContentReader reader = null;
NodeRef newDocNoderef = null;
PDFMergerUtility PDFmerger = new PDFMergerUtility();
ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
try {
LOGGER.debug("Merging of Doc Started");
for (NodeRef node : nodeRefList) {
reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
originalInputStream = reader.getContentInputStream();
PDFmerger.addSource(originalInputStream);
}
PDFmerger.setDestinationStream(outputstream);
PDFmerger.mergeDocuments();
if(originalInputStream!=null) {
originalInputStream.close();
}
newDocNoderef = writeContentToAlfresco(outputstream, nodeRefList, fileName,destinationNode);
LOGGER.debug("Documents are merged and new pdf is created at "+newDocNoderef);
} finally {
if(outputstream!=null)
outputstream.close();
}
return newDocNoderef;
}
public NodeRef writeContentToAlfresco(ByteArrayOutputStream outputstream, List<NodeRef> childRefList,
String fileName,NodeRef destinationNode) throws FileExistsException,IOException,Exception {
NodeRef pdf = null;
Map<QName, Serializable> props = new HashMap<>();
Map<Date, NodeRef> dateMap = new HashMap<Date, NodeRef>();
NodeRef parentNodeRef=null;
try {
LOGGER.debug("Upload to Alfresco Started");
for(NodeRef noderef : childRefList) {
Date date = (Date) nodeService.getProperty(noderef, ContentModel.PROP_MODIFIED);
dateMap.put(date, noderef);
}
Map<Date, NodeRef> m1 = new TreeMap<Date, NodeRef>(dateMap);
Map.Entry<Date, NodeRef> entry = m1.entrySet().iterator().next();
NodeRef finalnodeRef = entry.getValue();
if(destinationNode!=null) {
parentNodeRef = destinationNode;
}else {
parentNodeRef = nodeService.getPrimaryParent(finalnodeRef).getParentRef();
}
QName[] myModelProps = CommonConstants.myModelProps;
for (QName myModelProp : myModelProps) {
Serializable object = nodeService.getProperty(finalnodeRef, myModelProp);
props.put(myModelProp, object);
}
FileInfo pdfInfo = fileFolderService.create(parentNodeRef, fileName + ".pdf",
MyModel.TYPE_CUSTOM_MYMODEL_TYPE);
pdf = pdfInfo.getNodeRef();
nodeService.setProperties(pdf,props);
nodeService.setProperty(pdf, ContentModel.PROP_TITLE,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_TITLE));
nodeService.setProperty(pdf, ContentModel.PROP_DESCRIPTION,
nodeService.getProperty(finalnodeRef, ContentModel.PROP_DESCRIPTION));
nodeService.setProperty(pdf,ContentModel.PROP_NAME,fileName + ".pdf");
ContentWriter writer = contentService.getWriter(pdf, ContentModel.PROP_CONTENT, true);
writer.setMimetype(MimetypeMap.MIMETYPE_PDF);
writer.setEncoding("UTF-8");
writer.putContent(new ByteArrayInputStream(outputstream.toByteArray()));
LOGGER.debug("Upload to Alfresco Ended");
} catch(FileExistsException fee) {
ExceptionUtils.printRootCauseStackTrace(fee);
throw new FileExistsException(parentNodeRef, fileName);
}
catch (Exception e) {
ExceptionUtils.printRootCauseStackTrace(e);
throw new Exception(e);
} finally {
if (outputstream != null)
outputstream.close();
}
return pdf;
}
This actually seems like one of the features we support in alfresco-pdf-toolkit out of the box. You could either use that addon, or get some inspiration from the code backing it.

ProcessBuilder&Runtime exec could not find or load main class in Spring Project

I want to compile a java file and exec its class in another class ( ← This class is a #service of a Spring MVC project ).
The service code is:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
// exec the class file
String[] execmd = {"java", "P" + pz_id};
ProcessBuilder epb = new ProcessBuilder(execmd);
epb.directory(new File(fd));
p = epb.start();
// get normal output
BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ptmp = pin.readLine();
while (ptmp != null) {
pout = pout == null ? ptmp + '\n' : pout + ptmp + '\n';
ptmp = pin.readLine();
}
// get error output
pin = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String wout = null;
ptmp = pin.readLine();
while (ptmp != null) {
wout = wout == null ? ptmp + '\n' : wout + ptmp + '\n';
ptmp = pin.readLine();
}
// print output
System.out.println(pout);
System.out.println(wout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
When this Service is invoked, I always get a Error: Could not find or load main class: P[id]
I cd theFilePath, the P[id].class file is existing.
And I can run java P[id] successfully in theFilePath.
And I try to replace ProcessBuilder with Runtime, like:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
// exec the class file
String execmd = "java", fd + "/P" + pz_id;
p = Runtime.getRuntime().exec(execmd);
// get normal output
BufferedReader pin = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ptmp = pin.readLine();
while (ptmp != null) {
pout = pout == null ? ptmp + '\n' : pout + ptmp + '\n';
ptmp = pin.readLine();
}
// get error output
pin = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String wout = null;
ptmp = pin.readLine();
while (ptmp != null) {
wout = wout == null ? ptmp + '\n' : wout + ptmp + '\n';
ptmp = pin.readLine();
}
// print output
System.out.println(pout);
System.out.println(wout);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
I get the same Error again T^T
IDE is sts-bundle, server is tomcat8
I know what is wrong here.
pb.start(); does not mean the command of pb will be executed immediately.
So if I set pb of command javac hello.java; set epb of command java hello
And I call pb.start(); epb.start(); continuously, I will get an Error: could not find or load main class: hello, because when I exec epb.start(); The former command(pb.start) may have not been executed!
I got 2 solution:
First: set a finally field and exec epb.start() in this field, like:
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile the java file
String[] cmd = {"javac", "P" + id + ".java"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// exec the class file
String[] execmd = {"java", "P" + pz_id};
ProcessBuilder epb = new ProcessBuilder(execmd);
epb.directory(new File(fd));
Process p = epb.start();
}
return null; // for test
}
Second: a trick of bash
#Service
public class MRServiceImp implements MRService {
#Override
public String submitMR(int id, String fd) {
try {
// compile & exec the java file
String[] cmd = {"/bin/bash"};
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(fd));
Process p = pb.start();
BufferedWriter pbw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
pbw.write("javac *.java;java P" + pz_id+";exit;");
pbw.newLine();
pbw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null; // for test
}
I use the second one.

Handle file name duplication when creating files in alfresco

I have a Java-backed webscript in repo tier that creates files (with given name) in a given folder in Alfresco.
To handle the file name duplication issue I wrote this code:
NodeRef node = null;
try {
node = createNode(fullName, folderNodeRefId);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRefId);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
ContentWriter writer = serviceRegistry.getContentService().getWriter(node, ContentModel.PROP_CONTENT, true);
writer.setMimetype(getFileFormatMimetype(fileFormat));
writer.putContent(inputStream);
writer.guessEncoding();
and
private NodeRef createNode(String filename, String folderNodeRefId)
throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
NodeRef folderNodeRef = new NodeRef(folderNodeRefId);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService()
.createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,
props)
.getChildRef();
}
The codes work very fine if there is no file name duplication (a new name). But it does nothing when there is a duplication, although it executes without any errors! When I test it it doesn't throw any exceptions but no file is created either!
Any hints about the cause of that?
Thanks,
I tested this code , It's working fine
#Test
public void createNode() {
AuthenticationUtil.setFullyAuthenticatedUser(ADMIN_USER_NAME);
NodeRef node = null;
String fileFormat = "txt";
String filename = "test";
NodeRef folderNodeRef = getCompanyHome();
//Create first node
node = createNode(filename, folderNodeRef);
try {
node = createNode(filename, folderNodeRef);
} catch (DuplicateChildNodeNameException e) {
System.out.println("Catched");
boolean done = false;
for (int i = 1; !done; i++) {
String newName = filename + "_" + i + "." + fileFormat;
System.out.println("Duplicate Name. Trying: " + newName);
try {
node = createNode(newName, folderNodeRef);
done = true;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
System.out.println("Done");
}
private NodeRef getCompanyHome() {
return nodeLocatorService.getNode("companyhome", null, null);
}
private NodeRef createNode(String filename, NodeRef folderNodeRef) throws InvalidNodeRefException, InvalidTypeException, InvalidQNameException {
System.out.println("In " + filename);
Map<QName, Serializable> props = new HashMap<QName, Serializable>(1);
props.put(ContentModel.PROP_NAME, filename);
return serviceRegistry.getNodeService().createNode(folderNodeRef, ContentModel.ASSOC_CONTAINS,
QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, filename), ContentModel.TYPE_CONTENT,props).getChildRef();
}

asp.net upload control is not working in ipad

The asp.net upload control is uploading the file for first time in Ipad but not after that and not even showing any error
The code is as below
protected void UploadThisFile(FileUpload upload)
{
try
{
string folderpath = ConfigurationManager.AppSettings["BTCommDynamic"].ToString() + ConfigurationManager.AppSettings["Attachments"].ToString();
Guid fileguid = Guid.NewGuid();
string filename = fileguid + upload.FileName;
if (upload.HasFile && dtFiles != null)
{
DataRow drFileRow = dtFiles.NewRow();
drFileRow["FileName"] = upload.FileName;
string theFileName = Path.Combine(Server.MapPath(folderpath), filename);
string theFileName1 = Path.Combine(folderpath, filename);
//string theFileName = folderpath;
//to save the file in specified path
upload.SaveAs(theFileName);
drFileRow["FilePath"] = theFileName1;
double Filesize = (upload.FileContent.Length);
if (Filesize > 1024)
{
drFileRow["FileSize"] = (upload.FileContent.Length / 1024).ToString() + " KB";
}
else
{
drFileRow["FileSize"] = (upload.FileContent.Length).ToString() + " Bytes";
}
dtFiles.Rows.Add(drFileRow);
gvAttachment.DataSource = dtFiles;
gvAttachment.DataBind();
}
}
catch (Exception ex)
{
string message = Utility.GetExceptionMessage(ex.GetType().ToString(), ex.Message);
Display_Message(message);
}
}
Do you use firebug? There might be an error on a client side that prevents the work of your functionality.
Do you have any logic on your client side? Some kinda jquery/ajax calls?

Resources