Handle file name duplication when creating files in alfresco - 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();
}

Related

How to save objects in a proper way with the stream writer?

In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}

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

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));
}
}

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.

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