How to add txt file programmatically in aem dam. | Community
Skip to main content
Level 2
May 18, 2022
Solved

How to add txt file programmatically in aem dam.

  • May 18, 2022
  • 3 replies
  • 5078 views

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

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by DEBAL_DAS

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.

 

3 replies

Shashi_Mulugu
Community Advisor
Community Advisor
May 18, 2022

@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?

Level 2
May 18, 2022

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

 

 

DEBAL_DAS
DEBAL_DASAccepted solution
New Member
May 18, 2022

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.

 

Debal Das, Senior AEM Consultant
Level 2
May 19, 2022

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 

DEBAL_DAS
New Member
May 21, 2022

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 -

 

Debal Das, Senior AEM Consultant
Level 4
May 18, 2022