March 21, 2020
Estimated Post Reading Time ~

How to create a file in Adobe CQ5 /AEM

Create a new file under jcr node
In some cases, we need to create a text or XML file under jcr nodes in CQ. In below code, we are creating a text file with the current jcr node name under specified location

private static final String TEXT_RENDERER_NODE_URL = "/content/projectname";
try {

// writing to file in temp location
FileOutputStream fop = null;
File file = null;
File testFile = null;
StreamResult result = new StreamResult(new StringWriter());
try {

Path filePath = Files.createTempFile("Test", ".txt");
file = filePath.toFile();
fop = new FileOutputStream(file);
// get the content in bytes

byte[] contentInBytes = pagePropertiesString.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
testFile = file;
} catch (IOException ioExc) {
log.error(
"TestFile :: IOException: ",
ioExc);
} finally {
try {
if (fop != null) {
fop.close();
}
} catch (IOException ioExc) {
log.error(
"TestFile :: IOException while closing output stream :",
ioExc);
}
}
} catch (Exception exc) {
log.error("TestFile Creation Failed :: Exception: ", exc);
}

//Create file under jcr node

try {
FileInputStream fileInputStream = new FileInputStream(testFile);

ValueFactory valueFactory = currentSession.getValueFactory();
Binary contentValue;
contentValue = valueFactory.createBinary(fileInputStream);
Node textRendererNode = currentSession.getNode(TEXT_RENDERER_NODE_URL + "/textRenderer");
//We are creating a new text file based on current jcr node name after converting to lower case, '' to _
Node fileNode = textRendererNode.addNode(jcrTitle.replace(' ', '-').toLowerCase() + ".txt", "nt:file");
Node actualNode = (childNode.getParent()).addNode(jcrTitle + ".txt", "nt:file");
actualNode.addMixin("mix:referenceable");
fileNode.addMixin("mix:referenceable");
Node resNode = fileNode.addNode("jcr:content", "nt:resource");
resNode.setProperty("jcr:data", contentValue);
Calendar lastModified = Calendar.getInstance();
lastModified.setTimeInMillis(lastModified.getTimeInMillis());
resNode.setProperty("jcr:lastModified", lastModified);
currentSession.save();
} catch (RepositoryException rpe) {
log.error("Exception in Text Renderer :" + rpe.getMessage());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception exc) {
// TODO Auto-generated catch block
exc.printStackTrace();

}


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.