Solved
Reference code to create a csv file and place in it given path.
Hi all,
I just want to create a .csv file programmatically, please share a reference code if anyone has it.
Hi all,
I just want to create a .csv file programmatically, please share a reference code if anyone has it.
I have done something like reading all the page title, name and URL and creating a CSV out of it. Hope the below code will give idea.
I have done this using Open CSV API.
Please add the below dependency in POM:
<!-- Open CSV Dependencies -->
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.1</version>
</dependency>
try (ResourceResolver resourceResolver = JcrUtilService.getResourceResolver()) {
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
AtomicInteger validPageCount = new AtomicInteger();
List<String[]> linkData = new ArrayList<>();
linkData.add(new String[]{URL_HEADING, PAGE_NAME_HEADING, PAGE_TITLE_HEADING});
for (String rootPagePath : brandRootPagePath) {
String brandName = StringUtils.substringBetween(rootPagePath, "/content/project/", "/en_us");
Page rootPage = pageManager != null ? pageManager.getContainingPage(rootPagePath) : null;
SiteMapUtil siteMapUtil = new SiteMapUtil(rootPage);
List<SiteMapUtil.Link> siteMapLinks = siteMapUtil.getLinks();
siteMapLinks.forEach(link -> {
String currentPagePath = link.getPath();
String currentPagePathJcrContent = new StringBuilder(currentPagePath).append(ServiceConstants.SLASH).append(JcrConstants.JCR_CONTENT).toString();
Resource currentPageResource = resourceResolver.getResource(currentPagePathJcrContent);
Page containingPage = pageManager.getContainingPage(currentPageResource);
ValueMap valueMap = containingPage.getProperties();
boolean isValidPage = getValidPage(currentPageResource);
Resource resource = resourceResolver.getResource(new StringBuilder(currentPagePathJcrContent).append(ServiceConstants.SLASH).append(ROOT_NODE).toString());
if ((isValidPage || (resource != null && resource.hasChildren())) && !StringUtils.equalsIgnoreCase(rootPagePath, currentPagePath)
&& !(StringUtils.endsWithIgnoreCase(currentPagePath, new StringBuilder(ServiceConstants.SLASH).append(EXCLUDE_ERRORS_PATH).toString())
|| StringUtils.endsWithIgnoreCase(currentPagePath, new StringBuilder(ServiceConstants.SLASH).append(EXCLUDE_HCP_PATH).toString()))) {
String pageTitle = valueMap.get(PAGE_TITLE_JCR_PROPERTY, StringUtils.EMPTY);
String pageName = valueMap.get(JcrConstants.JCR_TITLE, StringUtils.EMPTY);
pageTitle = StringUtils.isNotBlank(pageTitle) ? pageTitle : pageName;
String pageURL = externalizer.externalLink(resourceResolver, brandName, String.format("%s.html", currentPagePath));
linkData.add(new String[]{pageURL, pageName, pageTitle});
validPageCount.incrementAndGet();
}
});
}
// Write Data to CSV and Download to local file system
return writeDataToCSV(validPageCount, linkData);
} catch (Exception e) {
log.error(":: Generate Report :: Exception -->", e);
}
private boolean getValidPage(Resource currentPageResource) {
boolean isValidPage = false;
if (currentPageResource != null && currentPageResource.hasChildren()) {
Iterable<Resource> iterable = currentPageResource.getChildren();
int size = Iterables.size(iterable);
List<String> resourceNameList = new ArrayList<>();
iterable.forEach(resource -> {
String resourceName = resource.getName();
resourceNameList.add(resourceName);
});
isValidPage = !resourceNameList.isEmpty() && resourceNameList.contains(ROOT_NODE) && size > 1;
}
return isValidPage;
}
private boolean writeDataToCSV(AtomicInteger validPageCount, List<String[]> linkData) throws IOException {
boolean generateSuccess = false;
if (validPageCount.get() > 0) {
File file = new File(tempReportPath, getReportFileName());
FileWriter fileWriter = new FileWriter(file);
CSVWriter csvWriter = new CSVWriter(fileWriter, ',', CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
csvWriter.writeAll(linkData);
csvWriter.close();
generateSuccess = true;
}
return generateSuccess;
}
private static String getReportFileName() {
final String currentDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
return new StringBuilder("Report").append(currentDate).append(".csv").toString();
}
You can get the file from here and keep it wherever you want:
final String filePath = new StringBuilder(tempReportPath).append(getReportFileName()).toString();
Hope this helps!
Thanks
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.