minimize this java code

Avatar

Avatar
Give Back 3
Level 2
sampath_kumar_g
Level 2

Likes

4 likes

Total Posts

17 posts

Correct reply

0 solutions
Top badges earned
Give Back 3
Give Back
Ignite 1
Validate 1
Boost 3
View profile

Avatar
Give Back 3
Level 2
sampath_kumar_g
Level 2

Likes

4 likes

Total Posts

17 posts

Correct reply

0 solutions
Top badges earned
Give Back 3
Give Back
Ignite 1
Validate 1
Boost 3
View profile
sampath_kumar_g
Level 2

01-07-2021

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();
}
}
}

}

Accepted Solutions (1)

Accepted Solutions (1)

Avatar

Avatar
Boost 100
Level 6
snbaem
Level 6

Likes

115 likes

Total Posts

246 posts

Correct reply

37 solutions
Top badges earned
Boost 100
Springboard
Establish
Validate 25
Validate 10
View profile

Avatar
Boost 100
Level 6
snbaem
Level 6

Likes

115 likes

Total Posts

246 posts

Correct reply

37 solutions
Top badges earned
Boost 100
Springboard
Establish
Validate 25
Validate 10
View profile
snbaem
Level 6

18-07-2021

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.

Answers (1)

Answers (1)

Avatar

Avatar
Coach
MVP
Arun_Patidar
MVP

Likes

1,442 likes

Total Posts

3,318 posts

Correct reply

941 solutions
Top badges earned
Coach
Contributor 2
Ignite 10
Give Back 700
Boost 1000
View profile

Avatar
Coach
MVP
Arun_Patidar
MVP

Likes

1,442 likes

Total Posts

3,318 posts

Correct reply

941 solutions
Top badges earned
Coach
Contributor 2
Ignite 10
Give Back 700
Boost 1000
View profile
Arun_Patidar
MVP

03-07-2021

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