3

I want to check if a Sling ressource already exists. Currently I use CQ.HTTP.get(url) to accomplish this. The problem is that if the ressource does not exist, JS logs a 404 error to the console which I think is ugly.

Is there a better way to check if a ressource exists which doesn't pollute the console?

Robert Munteanu
  • 67,031
  • 36
  • 206
  • 278
Jdv
  • 962
  • 10
  • 34

1 Answers1

3

Here is a simple servlet that does what you're asking:

/**
 * Servlet that checks if resource exists.
 */
@SlingServlet
(
    paths = "/bin/exists",
    extensions = "html",
    methods = "GET"
)
public class ResourceExistsServlet extends SlingSafeMethodsServlet {

    @Override
    protected void doGet(final SlingHttpServletRequest request,
                         final SlingHttpServletResponse response) throws ServletException, IOException {
        // get the resource by the suffix
        // for example, in the request /bin/exists.htm/apps, "/apps" is the suffix and that's the resource obtained here.
        Resource resource = request.getRequestPathInfo().getSuffixResource();
        // resource is null, does not exist, not null, exists
        boolean exists = resource != null;
        // make the response content type JSON
        response.setContentType(JSONResponse.APPLICATION_JSON_UTF8);
        // Write the json to the response
        // TODO: use a library for more complicated JSON, like google's gson. In this case, this string suffices.
        response.getWriter().write("{\"exists\": "+exists+"}");
    }
}

And here is some sample JS to call the servlet:

// Check if a path exists exists
function exists(path){
  return $.getJSON("/bin/exists.html"+path);
}

// check if /apps exists
exists("/apps")
.then(function(res){console.log(res.exists)})
// prints: true


// check if /apps123 exists
exists("/apps123")
.then(function(res){console.log(res.exists)})
// prints: false
Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47
  • I would suggest the following improvements: - use [org.apache.sling.commons.json.JSONObject](https://sling.apache.org/apidocs/sling7/org/apache/sling/commons/json/JSONObject.html) to generate the json string - change the extension to .json or drop it because it has not effect when you set "paths" property – d33t Oct 15 '17 at 11:36
  • 1
    That package is deprecated in AEM 6.3 – Ahmed Musallam Oct 15 '17 at 12:57
  • That's true, thanks for poiting this out. The library was deprecated because of [legal reasons](http://markmail.org/thread/3kx7kkeaksqiduz5), you can find [here](http://blogs.perficient.com/adobe/2017/08/02/aem-6-3-handing-feelings-of-deprecation/) some alternatives. Beside this the question is for cq5 where this is the common way dealing with json. – d33t Oct 16 '17 at 12:31
  • Either way, I did write a todo in my code for using a library like gson for generating JSON. – Ahmed Musallam Oct 16 '17 at 13:41