Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

minimize this java code

Avatar

Level 2

package com.sdm.community.core.servlets;

import java.io.IOException;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.Servlet;

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.resource.ResourceResolverFactory;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.search.PredicateGroup;
import com.day.cq.search.Query;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;

@component(service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=View All Condition data Data Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=" + "/bin/viewallconditiondata" })

public class ViewAllConditionData extends SlingSafeMethodsServlet{
private static final long serialVersionUID = 2598426539169789515L;

private static final Logger log = LoggerFactory.getLogger(ViewAllConditionData.class);

protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServerException, IOException {
log.info("Begin doGet for ViewAllConditionData");
StringBuilder resultList = new StringBuilder();

Map<String,Object> paramMap = new HashMap<String,Object>();
paramMap.put(ResourceResolverFactory.SUBSERVICE, "readService");
ResourceResolver resourceResolver=null;
Session session = null;
QueryBuilder builder = null;

try {
resourceResolver = request.getResourceResolver();
session = resourceResolver.adaptTo(Session.class);
builder=resourceResolver.adaptTo(QueryBuilder.class);

PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
List<String> conditionPagePathsList = new ArrayList<String> ();
Map<String, String> map= new HashMap<String, String> ();

map.put("path", SearchConstants.CONDITION_WORKBOOK_URL);
map.put("type", "cq:Page");
map.put("p.limit", "3000");
map.put("path.flat", "true");

Query query = builder.createQuery(PredicateGroup.create(map), session);

SearchResult result = query.getResult();

for (Hit hit: result.getHits()) {
try {
conditionPagePathsList.add(hit.getPath());
} catch (RepositoryException e) {
log.error("Error while getting the treatment page paths :: " + e.getMessage());
}
}

for (int i = 0; i < conditionPagePathsList.size(); i++) {
Page conditionPage = pageManager.getPage(conditionPagePathsList.get(i));
if (conditionPage != null && conditionPage.listChildren() != null) {
Resource resource = conditionPage.getContentResource();
if(resource != null){
Node node = resource.adaptTo(Node.class);
PropertyIterator subNode = null;
if (node.hasProperty(SearchConstants.JCR_TITLE)) {
subNode = node.getProperties();
while (subNode.hasNext()) {
Property property = subNode.nextProperty();
String titleValue = "";
if(SearchConstants.JCR_TITLE.equalsIgnoreCase(property.getName())) {
titleValue = property.getValue().toString();
}
if(!titleValue.equalsIgnoreCase("") && !titleValue.equalsIgnoreCase(SearchConstants.NO_CONDITION) &&
!titleValue.equalsIgnoreCase("Generic")) {
String id = titleValue.replace(" ", "");
resultList.append(titleValue + ":" + id + "<>");
}
}
}
}
}
}
response.getWriter().write(resultList.toString().substring(0, resultList.length() - 2));
} catch (Exception e) {
log.error("Exception : " + e.getMessage());
} finally {
if (session != null) {
session.logout();
}
if (resourceResolver != null) {
resourceResolver.close();
}
}
}

}

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @sampath_kumar_g 

 

You can check following

- Use try-with-resource instead of basic try-catch and closing resolver at the end. See -https://cqdump.joerghoh.de/2018/11/14/try-with-resource-or-i-will-never-forget-to-close-a-resource-resolver/

- There is a for loop that is looping conditionPagePathsList in which the gethits based page paths were added. Instead Get a List of nodes or resources directly using results.getNodes() or results.getResources(). You will prevent a for loop there. 

- There is a while loop "while (subNode.hasNext()) " you could use valuemap to get the desired property instead of looping all properties.

- Along with above try to separate the sections of your logics in different methods private or util based if applicable.

View solution in original post

2 Replies

Avatar

Community Advisor

Hi,

Why do you want to minimize this code?

 

If you want to reuse some of the code then start creating util classs and pu common code there e.g. get services session utils, query utils



Arun Patidar

Avatar

Correct answer by
Community Advisor

Hi @sampath_kumar_g 

 

You can check following

- Use try-with-resource instead of basic try-catch and closing resolver at the end. See -https://cqdump.joerghoh.de/2018/11/14/try-with-resource-or-i-will-never-forget-to-close-a-resource-resolver/

- There is a for loop that is looping conditionPagePathsList in which the gethits based page paths were added. Instead Get a List of nodes or resources directly using results.getNodes() or results.getResources(). You will prevent a for loop there. 

- There is a while loop "while (subNode.hasNext()) " you could use valuemap to get the desired property instead of looping all properties.

- Along with above try to separate the sections of your logics in different methods private or util based if applicable.