Hi All,
We have a requirement where we need to use the querybuilder search api and search the content path of the particular site and after that we need to add the searched content path in a txt file and we need to upload this file in aem dam. I have done all the thing except adding the txt file in the dam, even though I have added the code for this but the changes are not working. File is getting added in the aem dam but there is no content inside the file.
For uploading the content in dam I am using below code snippet.
AssetManager manager = resourceResolver.adaptTo(AssetManager.class);
is = new FileInputStream(site[2]+".txt");
log.info("inputstream value check:{}->",is.available());
Asset asset = manager.createAsset("/content/dam/" + site[2]+".txt", is, "text/plain", true);
Please help me on the above issue.
Thanks,
Aaqib Khan
Solved! Go to Solution.
Views
Replies
Total Likes
I wrote the below code to add some content into a csv file and upload into DAM -
AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class); String filename = "Some-Name"+".csv"; File csvFile = new File(filename); FileWriter fileWriter = new FileWriter(csvFile); for(String[] data : listdata){ StringBuilder line = new StringBuilder(); for (int i=0; i<data.length;i++){ line.append("\""); line.append(data[i].replaceAll("\"","\"\"")); line.append("\""); if(i!=data.length-1){ line.append(','); } } line.append("\n"); fileWriter.write(line.toString()); } fileWriter.close(); InputStream fileInputStream = new FileInputStream(csvFile); assetManager.createAsset("/content/dam/debal/"+ filename,fileInputStream, null, true);
Here, listdata was an ArrayList which was containing search result. Please review this as a reference.
@aaqibk92586681 welcome to Communities, you are using correct AEM DAM Api but can you recheck your logic of creating inputstream?
If you are trying to store output of paths from your query, can you create input stream from striing or string builder and then pass that IS to create asset method?
Hi @Shashi_Mulugu ,
PFB the code snippet. Getting the searched results and after that created a file test.txt and added the path there. Please let me know if you need additional detail.
SearchResult result = query.getResult();
List<Hit> hits =result.getHits();
writer = new FileWriter("test.txt");
for(Hit hit: hits){
Page page=hit.getResource().adaptTo(Page.class);
String str = req.getHeader("Host")+page.getPath()+".html";
writer.write(str + System.lineSeparator());
}
AssetManager manager = resourceResolver.adaptTo(AssetManager.class);
is = new FileInputStream("test.txt");
log.info("inputstream value check:{}->",is.available());
Asset asset = manager.createAsset("/content/dam/" + site[2]+".txt", is, "text/plain", true);
Thanks,
Aaqib
I wrote the below code to add some content into a csv file and upload into DAM -
AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class); String filename = "Some-Name"+".csv"; File csvFile = new File(filename); FileWriter fileWriter = new FileWriter(csvFile); for(String[] data : listdata){ StringBuilder line = new StringBuilder(); for (int i=0; i<data.length;i++){ line.append("\""); line.append(data[i].replaceAll("\"","\"\"")); line.append("\""); if(i!=data.length-1){ line.append(','); } } line.append("\n"); fileWriter.write(line.toString()); } fileWriter.close(); InputStream fileInputStream = new FileInputStream(csvFile); assetManager.createAsset("/content/dam/debal/"+ filename,fileInputStream, null, true);
Here, listdata was an ArrayList which was containing search result. Please review this as a reference.
Thanks @DEBAL_DAS ,
I am able to add the all the searched content inside the txt file and added in dam also.
But the requirement is changed I need to do the same thing with the xml file instead of txt file. Can you please help me on the above issue.
Thanks,
Aaqib
Just created this sample servlet to create and upload xml file into DAM -
package com.aem.demo.core.servlets; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import javax.jcr.Session; import javax.servlet.Servlet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.osgi.service.component.annotations.Component; import org.osgi.service.component.annotations.Reference; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.day.cq.dam.api.AssetManager; import com.day.cq.search.PredicateGroup; import com.day.cq.search.Query; import com.day.cq.search.QueryBuilder; import com.day.cq.search.result.SearchResult; @Component(service = Servlet.class, property = { "sling.servlet.paths=" + "/bin/damData", "sling.servlet.methods=" + HttpConstants.METHOD_GET }) public class WriteDatatoDamServlet extends SlingAllMethodsServlet { @Reference private QueryBuilder queryBuilder; protected void doGet(SlingHttpServletRequest slingHttpServletRequest, SlingHttpServletResponse slingHttpServletResponse) { Map<String, String> map = new HashMap<String, String>(); List<String> arrayList = new ArrayList<String>(); try (ResourceResolver resourceResolver = slingHttpServletRequest.getResourceResolver()) { Session session = resourceResolver.adaptTo(Session.class); if (Objects.nonNull(session)) { map.put("path", "/content/dam/we-retail/en/people"); map.put("type", "dam:Asset"); map.put("p.limit", "-1"); Query searchquery = queryBuilder.createQuery(PredicateGroup.create(map), session); SearchResult searchResult = searchquery.getResult(); Iterator<Resource> resources = searchResult.getResources(); while (resources.hasNext()) { Resource searchResultResource = resources.next(); String searchrseourcePath = searchResultResource.getPath(); arrayList.add(searchrseourcePath); } writeToxml(arrayList, resourceResolver); } } } private void writeToxml(List<String> arrayList, ResourceResolver resourceResolver) { AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class); String filename = "Asset".concat(".xml"); File file = new File(filename); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; try { documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element root = document.createElement("AssetPaths"); document.appendChild(root); for (String path : arrayList) { Element assetPath = document.createElement("AssetPath"); root.appendChild(assetPath); assetPath.appendChild(document.createTextNode(path)); } TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource domSource = new DOMSource(document); StreamResult streamResult = new StreamResult(file); transformer.transform(domSource, streamResult); InputStream fileInputStream = new FileInputStream(file); assetManager.createAsset("/content/dam/we-retail/en/people/" + filename, fileInputStream, "application/xml", true); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
Xml file in DAM-
Output -
Check this if helpful https://aemsimplifiedbynikhil.wordpress.com/2019/10/04/read-write-data-in-json-file-of-dam-in-aem-ma...
Here they are creating JSON file instead of text file