I am using AEM6. Using
@Reference private QueryBuilder builder;
is not making my servlet work.. is there any Solution for this? is there any other alternative to get the Query builder instance with out using "@Reference"?
package com.kicker.disolutions; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.rmi.ServerException; import java.util.ArrayList; import java.util.Dictionary; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; //QUeryBuilder APIs import com.day.cq.search.QueryBuilder; import com.day.cq.search.Query; import com.day.cq.search.PredicateGroup; import com.day.cq.search.result.SearchResult; import com.day.cq.search.result.Hit; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.apache.sling.api.adapter.Adaptable; import org.apache.sling.api.resource.Resource; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.resource.ResourceResolverFactory; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Properties; import org.apache.felix.scr.annotations.Property; import org.apache.felix.scr.annotations.Reference; import org.apache.felix.scr.annotations.Service; import org.apache.felix.scr.annotations.sling.SlingServlet; import org.apache.jackrabbit.commons.JcrUtils; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.servlets.SlingSafeMethodsServlet; import org.apache.sling.commons.osgi.OsgiUtil; import org.apache.sling.jcr.api.SlingRepository; import org.apache.felix.scr.annotations.Reference; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.jcr.Session; import javax.jcr.Node; import org.json.simple.JSONObject; import java.util.UUID; @Component(immediate = true, metatype = false, label = "HelloFormServlet") @Service @Properties(value = { @org.apache.felix.scr.annotations.Property(name = "sling.servlet.methods", value = "POST"), @org.apache.felix.scr.annotations.Property(name = "sling.servlet.paths", value = "/bin/HelloFormServlet") }) /* @SlingServlet(paths="/bin/HelloForm", methods = "POST", metatype=true) */ public class PollController extends org.apache.sling.api.servlets.SlingAllMethodsServlet { private static final long serialVersionUID = 2598426539166789515L; /* * @Reference private SlingRepository repository; */ Logger log = LoggerFactory.getLogger(PollController.class); @Reference public QueryBuilder builder; @Override protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException { int custRec = 0; try { ResourceResolver resourceResolver = request.getResourceResolver(); Session session = resourceResolver.adaptTo(Session.class); String UserName = session.getUserID(); log.info(" session User ---->"+UserName); Node customerRoot = null; String pollsGraphsPath =request.getParameter("path"); injestCustData(UserName,resourceResolver,pollsGraphsPath); log.info("out of Injest data"); //Session session1 = resourceResolver.adaptTo(Session.class); // Create a node that represents the root node Node root = session.getRootNode(); log.info("after session"); // Get the content node in the JCR //Node content = root.getNode("content/geometrixx-outdoors/Test/jcr:content/par/pollsgraph"); Node content = root.getNode(pollsGraphsPath); // Determine if the content/customer node exists custRec = doesCustExist(content); log.info("after doesCustExist ==="+custRec); // -1 means that content/customer does not exist if (custRec == -1) // content/customer does not exist -- create it log.info("no data for Users Saved.. No Polls Taken"); else // content/customer does exist -- retrieve it CheckCustomerCustomerData(UserName, resourceResolver, pollsGraphsPath,session); log.info("getting values from jsp"); response.getWriter().write("This is some text from an external ASP file"); } catch (Exception e) { e.printStackTrace(); } log.info("passing off jsp"); } public String getCustomerData(String firstName,ResourceResolver resourceResolver, String pollsGraphsPath) { UsersInfo cust = null; List<UsersInfo> custList = new ArrayList<UsersInfo>(); Map<String, Object> param = new HashMap<String, Object>(); try { Session session1 = resourceResolver.adaptTo(Session.class); // Create a node that represents the root node Node root = session1.getRootNode(); // Get the content node in the JCR //Node content = root.getNode("content/geometrixx-outdoors/Test/jcr:content/par/pollsgraph"); Node content = root.getNode(pollsGraphsPath); // Determine if the content/customer node exists Node customerRoot = null; int custRec = doesCustExist(content); session1.logout(); /* return convertToString(toXml(custList)); */ } catch (Exception e) { e.printStackTrace(); } return null; } public int injestCustData(String firstName,ResourceResolver resourceResolver, String pollsGraphsPath) { String desc = "PollsUser"; int num = 0; try { // Inject a Sling ResourceResolverFactory // Invoke the adaptTo method to create a Session used to create a // QueryManager //ResourceResolver resourceResolver = resolverFactory.getAdministrativeResourceResolver(null); Session session1 = resourceResolver.adaptTo(Session.class); // Create a node that represents the root node Node root = session1.getRootNode(); // Get the content node in the JCR //Node content = root.getNode("content/geometrixx-outdoors/Test/jcr:content/par/pollsgraph"); Node content = root.getNode(pollsGraphsPath); // Determine if the content/customer node exists Node customerRoot = null; int custRec = doesCustExist(content); // -1 means that content/customer does not exist if (custRec == -1) // content/customer does not exist -- create it customerRoot = content.addNode("pollsAlready", "nt:unstructured"); else // content/customer does exist -- retrieve it customerRoot = content.getNode("pollsAlready"); int custId = custRec + 1; // assign a new id to the customer node // Store content from the client JSP in the JCR Node custNode = customerRoot.addNode("PollUser" + firstName + custId, "nt:unstructured"); // make sure name of node is unique custNode.setProperty("id", custId); custNode.setProperty("firstName", firstName); custNode.setProperty("desc", desc); // Save the session changes and log out session1.save(); //session1.logout(); log.info("out of injestCustData(String, ResourceResolver, String)"); return 0; } catch (Exception e) { log.error("RepositoryException: " + e); } return 0; } private int doesCustExist(Node content) { try { int index = 0; int childRecs = 0; java.lang.Iterable<Node> custNode = JcrUtils.getChildNodes(content, "pollsAlready"); Iterator it = custNode.iterator(); // only going to be 1 pollsgraph/pollsAlready node if it exists if (it.hasNext()) { // Count the number of child nodes to pollsAlready Node customerRoot = content.getNode("pollsAlready"); Iterable itCust = JcrUtils.getChildNodes(customerRoot); Iterator childNodeIt = itCust.iterator(); // Count the number of customer child nodes while (childNodeIt.hasNext()) { childRecs++; childNodeIt.next(); } return childRecs; } else return -1; // content/customer does not exist } catch (Exception e) { e.printStackTrace(); } return 0; } int CheckCustomerCustomerData(String UserName,ResourceResolver resourceResolver, String pollsGraphsPath,Session Session) { String desc = "PollsUser"; int num = 0; try { log.info("in CheckCustomerCustomerData"); PredicateGroup group = new PredicateGroup(); Map<String, String> map = new HashMap<String, String>(); map.put("type", "nt:unstructured"); map.put("nodename", "PollUser*"); map.put("p.offset", "0"); // same as query.setStart(0) below map.put("p.limit", "20"); // same as query.setHitsPerPage(20) below Query query = builder.createQuery(PredicateGroup.create(map), Session); log.info("after building query"); query.setStart(0); query.setHitsPerPage(20); SearchResult result = query.getResult(); log.info("Search Results: " +result.getTotalMatches() ) ; for (Hit hit : result.getHits()) { //Convert the HIT to an asset - each asset will be placed into a ZIP for downloading String path = hit.getPath(); log.info("path--->"+path); Resource rs = resourceResolver.getResource(path); log.info("Resource object-->"+rs); log.info("Resource-->"+rs.getName()); } } catch (Exception e) { log.error("RepositoryException: " + e); } return 0; } }
Solved! Go to Solution.
As I thought - there is no issue using @Reference QueryBuilder in a Sling Servlet.
@SlingServlet(paths="/bin/myQueryBuilderSearch", methods = "GET", metatype=true)
public class SearchServlet extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;
//Inject a Sling ResourceResolverFactory
@Reference
private ResourceResolverFactory resolverFactory;
@Reference
private QueryBuilder builder;
private Session session;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
try
{
.../
I have it working:
[img]client.png[/img]
http://scottsdigitalcommunity.blogspot.ca/2015/09/using-query-builder-api-from-within.html
Views
Replies
Total Likes
what exactly is going on your end?
is the object null?
Views
Replies
Total Likes
Feike Visser wrote...
what exactly is going on your end?
is the object null?
piece of the error log i am getting
02.09.2015 01:48:20.450 *ERROR* [0:0:0:0:0:0:0:1 [1441138700435] POST /bin/HelloFormServlet HTTP/1.1] org.apache.sling.servlets.post.impl.operations.ModifyOperation Exception during response processing. javax.jcr.RepositoryException: org.apache.sling.api.resource.PersistenceException: Resource at '/bin/HelloFormServlet' is not modifiable. at org.apache.sling.servlets.post.impl.operations.ModifyOperation.doRun(ModifyOperation.java:113) at org.apache.sling.servlets.post.AbstractPostOperation.run(AbstractPostOperation.java:92) at org.apache.sling.servlets.post.impl.SlingPostServlet.doPost(SlingPostServlet.java:200) at org.apache.sling.api.servlets.SlingAllMethodsServlet.mayService(SlingAllMethodsServlet.java:148) at org.apache.sling.api.servlets.SlingSafeMethodsServlet.service(SlingSafeMethodsServlet.java:344) at org.apache.sling.api.servlets.SlingSafeMethodsServlet.service(SlingSafeMethodsServlet.java:375) at org.apache.sling.engine.impl.request.RequestData.service(RequestData.java:511) at org.apache.sling.engine.impl.filter.SlingComponentFilterChain.render(SlingComponentFilterChain.java:45) at org.apache.sling.en
when using @Reference
Views
Replies
Total Likes
Hi,
In this case the DefaultPostSerlvet kicks in, as there is no other resourcetype registered to this resource, which can handle the POST. This is just a signal, that your servlet is not registered.
When you use Java annotations, don't put them in a comment.
kind regards,
Jörg
Views
Replies
Total Likes
Hi jorh,
If we have defined paths for the servlet from which it can be accessed, i dont think so we need to define resourceType as only one will be considered.
Please check this one: https://sling.apache.org/documentation/the-sling-engine/servlets.html
Views
Replies
Total Likes
Jörg Hoh wrote...
Hi,
In this case the DefaultPostSerlvet kicks in, as there is no other resourcetype registered to this resource, which can handle the POST. This is just a signal, that your servlet is not registered.
When you use Java annotations, don't put them in a comment.
kind regards,
Jörg
My servlet is registered and showing in "sling servlet resolver" pointing to the correct class.. when i keep @Reference the servlet class is not showing in "sling servlet resolver"
Views
Replies
Total Likes
Hi,
in that case the reference is not available. You can you check for your class in /system/console/components and find out, which dependency is not resolved (likely the QueryBuilder). In the same view you can also check for the QueryBuilder.
kind regards,
Jörg
The article that i referenced uses QueryBuilder in a custom service - not a Sling Servlet. I will port the logic to an AEM sling Servlet and post it tomorrow (weds Sept 2). There is no reason why @Reference (dependency injection) of QUeryBuiler will not work in a Sling Servlet.
Views
Replies
Total Likes
Hi,
I see the dependency issue is there int the bundle. but for time being had to bypass Querybuider and used the code below. once in find time i will look
into dependency..!
void getOnlyPollData(SlingHttpServletRequest request){ Map<String, Object> param = new HashMap<String, Object>(); /* param.put(ResourceResolverFactory.SUBSERVICE, "datawrite"); */ // ResourceResolver resolver = null; StringBuffer tagQuery = new StringBuffer(); try { tagQuery.append("SELECT * FROM [nt:unstructured] AS s WHERE NAME() = 'pollValues'"); ResourceResolver resourceResolver = request.getResourceResolver(); Iterator<Resource> Resources = resourceResolver.findResources(tagQuery.toString(),"JCR-SQL2"); while (Resources!= null && Resources.hasNext()){ Resource resource = Resources.next(); Node node=resource.adaptTo(Node.class); NodeAprop=Integer.valueOf(node.getProperty("A").getString()); NodeBprop=Integer.valueOf(node.getProperty("B").getString()); NodeCprop=Integer.valueOf(node.getProperty("C").getString()); NodeDprop=Integer.valueOf(node.getProperty("D").getString()); NodeEprop=Integer.valueOf(node.getProperty("E").getString()); } } catch (Exception e) { e.printStackTrace(); } }
Views
Replies
Total Likes
Jörg Hoh wrote...
Hi,
in that case the reference is not available. You can you check for your class in /system/console/components and find out, which dependency is not resolved (likely the QueryBuilder). In the same view you can also check for the QueryBuilder.
kind regards,
Jörg
Hi,
I see the dependency issue is there int the bundle. but for time being i had to bypass Querybuider and used the code below. once i find time i will look
into dependency..!
void getOnlyPollData(SlingHttpServletRequest request){ Map<String, Object> param = new HashMap<String, Object>(); /* param.put(ResourceResolverFactory.SUBSERVICE, "datawrite"); */ // ResourceResolver resolver = null; StringBuffer tagQuery = new StringBuffer(); try { tagQuery.append("SELECT * FROM [nt:unstructured] AS s WHERE NAME() = 'pollValues'"); ResourceResolver resourceResolver = request.getResourceResolver(); Iterator<Resource> Resources = resourceResolver.findResources(tagQuery.toString(),"JCR-SQL2"); while (Resources!= null && Resources.hasNext()){ Resource resource = Resources.next(); Node node=resource.adaptTo(Node.class); NodeAprop=Integer.valueOf(node.getProperty("A").getString()); NodeBprop=Integer.valueOf(node.getProperty("B").getString()); NodeCprop=Integer.valueOf(node.getProperty("C").getString()); NodeDprop=Integer.valueOf(node.getProperty("D").getString()); NodeEprop=Integer.valueOf(node.getProperty("E").getString()); } } catch (Exception e) { e.printStackTrace(); } }
Views
Replies
Total Likes
As I thought - there is no issue using @Reference QueryBuilder in a Sling Servlet.
@SlingServlet(paths="/bin/myQueryBuilderSearch", methods = "GET", metatype=true)
public class SearchServlet extends org.apache.sling.api.servlets.SlingAllMethodsServlet {
private static final long serialVersionUID = 2598426539166789515L;
//Inject a Sling ResourceResolverFactory
@Reference
private ResourceResolverFactory resolverFactory;
@Reference
private QueryBuilder builder;
private Session session;
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServerException, IOException {
try
{
.../
I have it working:
[img]client.png[/img]
http://scottsdigitalcommunity.blogspot.ca/2015/09/using-query-builder-api-from-within.html
Views
Replies
Total Likes
from your code:
/*@Reference*/ private QueryBuilder builder;
The annotation looks like its in a comment.
Have a look at this community article to learn how to use QueryBuilder:
https://helpx.adobe.com/experience-manager/using/using-query-builder-api1.html
Views
Replies
Total Likes
smacdonald2008 wrote...
from your code:
/*@Reference*/ private QueryBuilder builder;
The annotation looks like its in a comment.
Have a look at this community article to learn how to use QueryBuilder:
https://helpx.adobe.com/experience-manager/using/using-query-builder-api1.html
yes u r right..with Annotation the servlet is not detecting and without annotation "Builder" instance is not creating
Views
Replies
Total Likes