Example #1
1
  @Override
  protected void writeLayer(
      SlingHttpServletRequest req, SlingHttpServletResponse resp, ImageContext c, Layer layer)
      throws IOException, RepositoryException {

    Image image = new Image(c.resource);
    if (!image.hasContent()) {
      resp.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // get style and set constraints
    image.loadStyleData(c.style);

    // get pure layer
    layer = image.getLayer(false, false, false);
    boolean modified = false;

    if (layer != null) {
      // crop
      modified = image.crop(layer) != null;

      // rotate
      modified |= image.rotate(layer) != null;

      // resize
      modified |= image.resize(layer) != null;

      // apply diff if needed (because we create the layer inline)
      modified |= applyDiff(layer, c);
    }

    // don't cache images on authoring instances
    // Cache-Control: no-cache allows caching (e.g. in the browser cache) but
    // will force revalidation using If-Modified-Since or If-None-Match every time,
    // avoiding aggressive browser caching
    if (!WCMMode.DISABLED.equals(WCMMode.fromRequest(req))) {
      resp.setHeader("Cache-Control", "no-cache");
    }

    if (modified) {
      String mimeType = image.getMimeType();
      if (ImageHelper.getExtensionFromType(mimeType) == null) {
        // get default mime type
        mimeType = "image/png";
      }
      resp.setContentType(mimeType);
      layer.write(mimeType, mimeType.equals("image/gif") ? 255 : 1.0, resp.getOutputStream());
    } else {
      // do not re-encode layer, just spool
      Property data = image.getData();
      InputStream in = data.getStream();
      resp.setContentLength((int) data.getLength());
      resp.setContentType(image.getMimeType());
      IOUtils.copy(in, resp.getOutputStream());
      in.close();
    }
    resp.flushBuffer();
  }
 @Override
 public void execute(SlingHttpServletResponse response, File logFile, LogFilter filter)
     throws IOException {
   response.setContentType(CONTENT_TYPE_PLAIN);
   FileWriterDecorator fileWriter = new FileWriterDecorator(response.getWriter());
   fileWriter.printFile(logFile, filter);
 }
 public void send(
     SlingHttpServletRequest request, SlingHttpServletResponse response, HtmlLibrary library) {
   InputStream libraryInputStream = null;
   // NOTE: HtmlLibraryManager#getLibrary should have prepared ClientLibraryImpl
   // and related binary stream should be ready
   try {
     Node node =
         JcrUtils.getNodeIfExists(getLibraryNode(request, library), JcrConstants.JCR_CONTENT);
     response.setDateHeader(
         "Last-Modified", JcrUtils.getLongProperty(node, JcrConstants.JCR_LASTMODIFIED, 0L));
     response.setContentType(library.getType().contentType);
     response.setCharacterEncoding("utf-8");
     libraryInputStream = JcrUtils.readFile(node);
   } catch (RepositoryException re) {
     log.debug("JCR issue retrieving library node at {}: ", library.getPath(), re.getMessage());
   }
   try {
     if (libraryManager.isGzipEnabled()) {
       response.setHeader("Content-Encoding", "gzip");
       GZIPOutputStream gzipOut = new GZIPOutputStream(response.getOutputStream());
       IOUtils.copy(libraryInputStream, gzipOut);
       gzipOut.finish();
     } else {
       IOUtils.copy(libraryInputStream, response.getOutputStream());
     }
   } catch (IOException ioe) {
     log.debug("gzip IO issue for library {}: ", library.getPath(), ioe.getMessage());
   } finally {
     IOUtils.closeQuietly(libraryInputStream);
   }
 }
  @Override
  protected final void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final JSONArray jsonArray = new JSONArray();
    try {

      for (Map.Entry<String, TagDataConverter> entry : this.tagDataConverters.entrySet()) {
        final JSONObject jsonObject = new JSONObject();

        jsonObject.put("label", entry.getValue().getLabel());
        jsonObject.put("value", entry.getKey());

        jsonArray.put(jsonObject);
      }

      response.getWriter().print(jsonArray.toString());

    } catch (JSONException e) {
      response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
  }
Example #5
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    String[] prefixes;
    try {
      Session session = (Session) request.getResourceResolver().adaptTo(Session.class);
      prefixes = session.getNamespacePrefixes();
    } catch (RepositoryException re) {
      prefixes = new String[] {""};
    }

    try {
      TidyJSONWriter out = new TidyJSONWriter(response.getWriter());
      out.setTidy("true".equals(request.getParameter(TIDY)));
      out.object();
      out.key("namespaces");
      out.array();
      for (String p : prefixes) {
        out.value(p);
      }
      out.endArray();
      out.endObject();
    } catch (JSONException e) {
      // todo...
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    // setup SSE headers
    response.setContentType("text/event-stream");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Connection", "keep-alive");
    // needed to allow the JavaScript EventSource API to make a call from author to this server and
    // listen for the events
    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");

    String agentName =
        request.getResource().getParent().getParent().adaptTo(ReplicationAgent.class).getName();
    PrintWriter writer = response.getWriter();
    while (true) {
      try {
        synchronized (cachedEvents) {
          cachedEvents.wait();
          Collection<String> eventsForAgent = cachedEvents.get(agentName);
          if (eventsForAgent != null) {
            for (String event : eventsForAgent) {
              writeEvent(writer, agentName + "-queue-event", event);
            }
          }
        }
      } catch (InterruptedException e) {
        log.error("error during SSE", e);
        throw new ServletException(e);
      }
    }
  }
  /** {@inheritDoc} */
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      Node node = resource.adaptTo(Node.class);
      if (node == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
      }
      Version version = versionService.saveNode(node, request.getRemoteUser());

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.object();
      write.key("versionName");
      write.value(version.getName());
      ExtendedJSONWriter.writeNodeContentsToWriter(write, version);
      write.endObject();
    } catch (RepositoryException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    } catch (JSONException e) {
      LOGGER.info("Failed to save version ", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
      return;
    }
  }
Example #8
0
 /** list all collections from ~user-home */
 @Override
 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException {
   try {
     JSONArray jsonArr = list(request, response);
     response.setContentType(CONTENT_TYPE_JSON);
     response.setCharacterEncoding(ENCODING_UTF8);
     response.getWriter().write(jsonArr.toString());
   } catch (Exception e) {
     log.error("Error in list collections: " + e.getMessage(), e);
     throw new ServletException(e);
   }
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/plain");
    final PrintWriter w = response.getWriter();

    final int cycles = getIntParam(request, "cycles", 10);
    final int interval = getIntParam(request, "interval", 1000);
    final int flushEvery = getIntParam(request, "flushEvery", 2);

    // Use supplied RuntimeState if available
    final RuntimeState runtimeState =
        (RuntimeState) request.getAttribute(RuntimeState.class.getName());
    if (runtimeState == null) {
      log.warn("No RuntimeState attribute provided, won't report progress");
    } else {
      runtimeState.setEstimatedCompletionTime(
          new Date(System.currentTimeMillis() + cycles * interval));
    }

    w.println("Start at " + new Date());
    try {
      for (int i = 1; i <= cycles; i++) {
        if (i % flushEvery == 0) {
          w.println("Flushing output<br/>");
          w.flush();
        }

        final String msg = String.format("Cycle %d of %d", i, cycles);
        w.printf(msg);
        w.print("\n<br/>");

        if (runtimeState != null) {
          runtimeState.setProgressMessage(msg);
          final int remainingCycles = cycles - i;
          runtimeState.setEstimatedCompletionTime(
              new Date(System.currentTimeMillis() + remainingCycles * interval));
        }

        try {
          Thread.sleep(interval);
        } catch (InterruptedException iex) {
          throw new ServletException("InterruptedException", iex);
        }
      }
      w.println("All done.");
      w.flush();
    } catch (Throwable t) {
      log.info("Exception in doGet", t);
    }
  }
Example #10
0
 /**
  * creates empty collection under ~user-home/collection. If collection with same name exists, it
  * throws exception
  */
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException {
   try {
     JSONObject jsonObject = create(request, response);
     response.setContentType(CONTENT_TYPE_JSON);
     response.setCharacterEncoding(ENCODING_UTF8);
     response.setStatus(SlingHttpServletResponse.SC_CREATED);
     response.getWriter().write(jsonObject.toString());
   } catch (Exception e) {
     log.error("Error in create collection: " + e.getMessage(), e);
     throw new ServletException(e);
   }
 }
Example #11
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    if ("json".equals(request.getRequestPathInfo().getExtension())) {

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Cache-Control", "no-cache");

      CampaignsJSONWriter w = new CampaignsJSONWriter(request);
      w.write(response.getWriter());
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    // get current user
    String user = request.getRemoteUser();
    if (user == null) {
      response.sendError(
          HttpServletResponse.SC_UNAUTHORIZED, "User must be logged in to check their status");
    }
    LOGGER.info("GET to PresenceContactsServlet (" + user + ")");

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    try {
      Writer writer = response.getWriter();
      ExtendedJSONWriter output = new ExtendedJSONWriter(writer);
      // start JSON object
      output.object();
      PresenceUtils.makePresenceJSON(output, user, presenceService, true);
      // add in the list of contacts info
      Session session = request.getResourceResolver().adaptTo(Session.class);
      List<String> userIds = connectionManager.getConnectedUsers(user, ConnectionState.ACCEPTED);
      output.key("contacts");
      output.array();
      for (String userId : userIds) {
        output.object();
        // put in the basics
        PresenceUtils.makePresenceJSON(output, userId, presenceService, true);
        // add in the profile
        output.key("profile");
        Authorizable au = PersonalUtils.getAuthorizable(session, userId);
        Node profileNode = (Node) session.getItem(PersonalUtils.getProfilePath(au));
        ExtendedJSONWriter.writeNodeToWriter(output, profileNode);
        output.endObject();
      }
      output.endArray();
      // finish it
      output.endObject();
    } catch (JSONException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }

    return;
  }
  protected void dumpRequestAsProperties(
      SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    final Properties props = new Properties();
    response.setContentType("text/plain");
    props.put("servlet.class.name", getClass().getName());

    final Resource r = request.getResource();
    props.put("sling.resource.path", r == null ? "" : r.getPath());
    props.put("sling.resource.type", r == null ? "" : r.getResourceType());
    props.put("http.request.method", request.getMethod());

    props.store(
        response.getOutputStream(),
        "Data created by " + getClass().getName() + " at " + new Date());
    response.getOutputStream().flush();
  }
Example #14
0
  /**
   * Takes the original request and starts the batching.
   *
   * @param request
   * @param response
   * @throws IOException
   */
  protected void batchRequest(
      SlingHttpServletRequest request, SlingHttpServletResponse response, boolean allowModify)
      throws IOException {
    // Grab the JSON block out of it and convert it to RequestData objects we can use.
    String json = request.getParameter(REQUESTS_PARAMETER);
    List<RequestInfo> batchedRequests = new ArrayList<RequestInfo>();
    try {
      JSONArray arr = new JSONArray(json);
      for (int i = 0; i < arr.length(); i++) {
        JSONObject obj = arr.getJSONObject(i);
        RequestInfo r = new RequestInfo(obj);
        if (allowModify || r.isSafe()) {
          batchedRequests.add(r);
        }
      }
    } catch (JSONException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "Failed to parse the " + REQUESTS_PARAMETER + " parameter");
      LOGGER.warn("Failed to parse the " + REQUESTS_PARAMETER + " parameter");
      return;
    }

    // Loop over the requests and handle each one.
    try {
      StringWriter sw = new StringWriter();
      JSONWriter write = new JSONWriter(sw);
      write.object();
      write.key("results");
      write.array();

      for (RequestInfo r : batchedRequests) {
        doRequest(request, response, r, write);
      }
      write.endArray();
      write.endObject();
      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.getWriter().write(sw.getBuffer().toString());
    } catch (JSONException e) {
      LOGGER.warn("Failed to create a JSON response");
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to write JSON response");
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    RequestParameter p = request.getRequestParameter("p");
    if (p == null) {
      // Send out the categories.
      sendIndex(response);
    } else if ("style".equals(p.getString())) {
      // Send out the CSS file
      if (style == null) {
        InputStream in = this.getClass().getResourceAsStream("style.css");
        style = IOUtils.toByteArray(in);
        in.close();
      }
      response.setContentType("text/css; charset=UTF-8");
      response.setContentLength(style.length);
      response.getOutputStream().write(style);
    }
  }
Example #16
0
  public void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    if (!authenticate(request, response)) {
      return;
    }
    response.setContentType("text/plain; charset=utf-8");

    synchronized (connectionHold) {
      connectionHold.notifyAll();
    }
    synchronized (this) {
      writer = response.getWriter();
    }
    try {
      synchronized (connectionHold) {
        connectionHold.wait();
      }
    } catch (InterruptedException e) {
      throw new ServletException("Interrupted", e);
    }
  }
Example #17
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    String resourceType = request.getResource().getResourceType();

    Resource resource = null;
    if (UserConstants.GROUP_HOME_RESOURCE_TYPE.equals(resourceType)) {
      resource = request.getResourceResolver().getResource(groupHome);
    } else if (UserConstants.USER_HOME_RESOURCE_TYPE.equals(resourceType)) {
      resource = request.getResourceResolver().getResource(userHome);
    }

    if (resource == null) {
      response.sendError(
          500, "Somehow didn't get a user or group home resource [" + resourceType + "]");
    } else {
      response.setContentType("text/html");
      response.setCharacterEncoding("UTF-8");
      response.setStatus(HttpServletResponse.SC_OK);
      IOUtils.stream(resource.adaptTo(InputStream.class), response.getOutputStream());
    }
  }
Example #18
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    if ("json".equals(request.getRequestPathInfo().getExtension())) {

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      response.setHeader("Cache-Control", "no-cache");
      // String path = request.getRequestPathInfo().getResourcePath();

      String path = request.getParameter(PATH_PARAM);
      log.debug("Providing experiences for {} .", path);

      String filterParam = request.getParameter("filter");
      log.debug("Filter param: '{}'", filterParam);

      ExperiencesJSONWriter w = new ExperiencesJSONWriter(request, response);
      w.setMCMFacade(mcmFacade);
      try {
        MapFilter filter = new MapFilter();
        int filterCount = filter.ingestJson(filterParam);
        if (filterCount > 0) {
          w.setMapFilter(filter);
        }
      } catch (JSONException e) {
        log.error("Cannot parse filter params.", e);
      }

      ExtJsSortListOfMapsComparator comparator = new ExtJsSortListOfMapsComparator();
      comparator.init(request);
      if (comparator.isInitialized()) {
        log.info("Sorting with: {}", comparator);
        w.setExperienceComparator(comparator);
      }

      w.write(response.getWriter(), path);
    }
  }
  /** {@inheritDoc} */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    if ("json".equals(request.getRequestPathInfo().getExtension())) {
      response.setContentType("application/json");
      response.setCharacterEncoding("utf-8");
      String path = request.getParameter(PATH_PARAM);
      int numChildrenCheck = 20;
      if (request.getParameter(NUM_CHILDREN_CHECK) != null) {
        try {
          numChildrenCheck = Integer.parseInt(request.getParameter(NUM_CHILDREN_CHECK));
        } catch (NumberFormatException e) {
          // ignore and use default
        }
      }

      SiteAdminTreeJSONWriter w =
          new SiteAdminTreeJSONWriter(request.getResourceResolver(), numChildrenCheck);
      w.write(response.getWriter(), path);
    }
  }
 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws IOException {
   PrintWriter out = response.getWriter();
   try {
     response.setContentType("application/json");
     response.setCharacterEncoding("UTF-8");
     String coffee = request.getParameter("coffee");
     String sugar = request.getParameter("sugar");
     String milk = request.getParameter("milk");
     int coffee_price, sugar_price, milk_price, bill;
     JSONObject jsonObject = new JSONObject();
     JSONArray jsonArray = new JSONArray();
     if (coffee.equals("Latte")) {
       coffee_price = 150;
     } else if (coffee.equals("Cappuccino")) {
       coffee_price = 100;
     } else {
       coffee_price = 120;
     }
     if (sugar.equals("Sugar Free")) {
       sugar_price = 50;
     } else if (sugar.equals("Brown Sugar")) {
       sugar_price = 40;
     } else {
       sugar_price = 20;
     }
     if (milk.equals("Full Cream")) {
       milk_price = 50;
     } else if (milk.equals("Normal Milk")) {
       milk_price = 40;
     } else {
       milk_price = 30;
     }
     bill = coffee_price + sugar_price + milk_price;
     jsonObject.put("bill", bill);
     response.getWriter().write(jsonObject.toString());
   } catch (Exception e) {
   }
 }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    try {
      final ResourceResolver resolver = request.getResourceResolver();
      final String vanityPath = request.getParameter("vanityPath");
      final String pagePath = request.getParameter("pagePath");
      log.debug(
          "vanity path parameter passed is {}; page path parameter passed is {}",
          vanityPath,
          pagePath);

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");

      JSONWriter jsonWriter = new JSONWriter(response.getWriter());
      jsonWriter.array();

      if (StringUtils.isNotBlank(vanityPath)) {
        String xpath =
            "//element(*)[" + NameConstants.PN_SLING_VANITY_PATH + "='" + vanityPath + "']";
        @SuppressWarnings("deprecation")
        Iterator<Resource> resources = resolver.findResources(xpath, Query.XPATH);
        while (resources.hasNext()) {
          Resource resource = resources.next();
          String path = resource.getPath();
          if (path.startsWith("/content") && !path.equals(pagePath)) {
            jsonWriter.value(path);
          }
        }
      }
      jsonWriter.endArray();
    } catch (JSONException e) {
      throw new ServletException("Unable to generate JSON result", e);
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    String path = request.getResource().getPath();

    // check path is a valid DAM root folder path for asset service
    if (!damPathHandler.isAllowedDataVersionPath(path)) {
      log.debug("Path not allowed to get data version {}", path);
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
      return;
    }

    // return data version as JSON
    try {
      JSONObject jsonResponse = new JSONObject();
      jsonResponse.put("dataVersion", damPathHandler.getDataVersion());

      response.setContentType(ContentType.JSON);
      response.setCharacterEncoding(CharEncoding.UTF_8);
      response.getWriter().write(jsonResponse.toString());
    } catch (JSONException ex) {
      throw new ServletException("Unable to generate JSON.", ex);
    }
  }
Example #23
0
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      List<Content> contentList = null;
      RequestParameter rp = request.getRequestParameter("path");
      ResourceResolver resourceResolver = request.getResourceResolver();
      if (rp != null) {
        String contentPath = rp.getString("UTF-8");
        if (contentPath.startsWith("/_groupa:")) {
          contentPath = contentPath.replaceFirst("/_groupa:", "/~");
        }
        if (contentPath.endsWith("/")) {
          contentPath = contentPath.substring(0, contentPath.length() - 1);
        }

        Resource pagesResource = resourceResolver.getResource(contentPath);
        if (pagesResource != null) {
          contentList = getPageTree(pagesResource.adaptTo(Content.class));
          ;
        }
      }

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");
      PrintWriter w = response.getWriter();
      ExtendedJSONWriter writer = new ExtendedJSONWriter(w);
      writer.object();
      // pages info
      int messageCount = 0;
      writer.key("items");
      writer.value(255);

      writer.key("results");
      writer.array();
      if (contentList != null) {
        for (int i = 0; i < contentList.size(); i++) {
          Content page = contentList.get(i);

          writer.object();
          writer.key("jcr:path");
          writer.value(
              page.getPath()
                  .replaceFirst(
                      LitePersonalUtils.PATH_AUTHORIZABLE,
                      LitePersonalUtils.PATH_RESOURCE_AUTHORIZABLE));
          for (String messagePropKey : page.getProperties().keySet()) {
            writer.key(messagePropKey);
            writer.value(massageValue(messagePropKey, page.getProperty(messagePropKey)));
          }
          writer.endObject();
          messageCount++;
        }
      }
      writer.endArray();
      writer.key("total");
      writer.value(messageCount);

      writer.endObject();
    } catch (JSONException e) {
      LOG.error("Failed to create proper JSON response in /var/search/page", e);
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to create proper JSON response.");
    }
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    Authorizable authorizable = null;
    Resource resource = request.getResource();
    if (resource != null) {
      authorizable = resource.adaptTo(Authorizable.class);
    }

    if (authorizable == null || !authorizable.isGroup()) {
      response.sendError(HttpServletResponse.SC_NO_CONTENT, "Couldn't find group");
      return;
    }

    Group group = (Group) authorizable;

    List<String> selectors = Arrays.asList(request.getRequestPathInfo().getSelectors());
    ExtendedJSONWriter writer = new ExtendedJSONWriter(response.getWriter());
    writer.setTidy(selectors.contains("tidy"));

    // Get the sorting order, default is ascending or the natural sorting order (which is
    // null for a TreeMap.)
    Comparator<String> comparator = null;
    String order = "ascending";
    if (request.getRequestParameter("sortOrder") != null) {
      order = request.getRequestParameter("sortOrder").getString();
      if (order.equals("descending")) {
        comparator = Collections.reverseOrder();
      }
    }

    try {
      response.setContentType("application/json");
      TreeMap<String, Authorizable> map = null;
      if (selectors.contains("managers")) {
        map = getManagers(request, group, comparator);
      } else {
        // Members is the default.
        map = getMembers(request, group, comparator);
      }

      // Do some paging.
      long items =
          (request.getParameter(ITEMS) != null) ? Long.parseLong(request.getParameter(ITEMS)) : 25;
      long page =
          (request.getParameter(PAGE) != null) ? Long.parseLong(request.getParameter(PAGE)) : 0;
      if (page < 0) {
        page = 0;
      }
      if (items < 0) {
        items = 25;
      }
      Iterator<Entry<String, Authorizable>> iterator =
          getInPlaceIterator(request, map, items, page);

      // Write the whole lot out.
      Session session = request.getResourceResolver().adaptTo(Session.class);
      writer.array();
      int i = 0;
      while (iterator.hasNext() && i < items) {
        Entry<String, Authorizable> entry = iterator.next();
        Authorizable au = entry.getValue();
        ValueMap profile;
        if (selectors.contains("detailed")) {
          profile = profileService.getProfileMap(au, session);
        } else {
          profile = profileService.getCompactProfileMap(au, session);
        }
        if (profile != null) {
          writer.valueMap(profile);
          i++;
        } else {
          // profile wasn't found.  safe to ignore and not include the group
          logger.info("Profile not found for " + au.getID());
        }
      }
      writer.endArray();

    } catch (RepositoryException e) {
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to retrieve members/managers.");
      return;
    } catch (JSONException e) {
      response.sendError(
          HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to build a proper JSON output.");
      return;
    }
  }
  @Override
  protected final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    final JSONObject jsonResponse = new JSONObject();

    final TagManager tagManager = request.getResourceResolver().adaptTo(TagManager.class);

    final RequestParameter charsetParam = request.getRequestParameter("charset");
    final RequestParameter cleanParam = request.getRequestParameter("clean");
    final RequestParameter delimiterParam = request.getRequestParameter("delimiter");
    final RequestParameter fileParameter = request.getRequestParameter("file");
    final RequestParameter separatorParam = request.getRequestParameter("separator");
    final RequestParameter converterParam = request.getRequestParameter("converter");
    final RequestParameter fallbackConverterParam =
        request.getRequestParameter("fallbackConverter");

    boolean clean = DEFAULT_CLEAN;
    if (cleanParam != null) {
      clean =
          Boolean.valueOf(
              StringUtils.defaultIfEmpty(cleanParam.toString(), String.valueOf(DEFAULT_CLEAN)));
    }

    String converter = DEFAULT_CONVERTER;
    if (converterParam != null) {
      converter = StringUtils.defaultIfEmpty(converterParam.toString(), DEFAULT_CONVERTER);
    }

    String fallbackConverter = NONE_CONVERTER;
    if (fallbackConverterParam != null) {
      fallbackConverter =
          StringUtils.defaultIfEmpty(fallbackConverterParam.toString(), NONE_CONVERTER);
    }

    String charset = DEFAULT_CHARSET;
    if (charsetParam != null) {
      charset = StringUtils.defaultIfEmpty(charsetParam.toString(), DEFAULT_CHARSET);
    }

    Character delimiter = null;
    if (delimiterParam != null && StringUtils.isNotBlank(delimiterParam.toString())) {
      delimiter = delimiterParam.toString().charAt(0);
    }

    Character separator = null;
    if (separatorParam != null && StringUtils.isNotBlank(separatorParam.toString())) {
      separator = separatorParam.toString().charAt(0);
    }

    final List<TagDataConverter> tagDataConverters = new ArrayList<TagDataConverter>();

    final TagDataConverter primaryTagConverter = this.getTagDataConverter(converter);
    if (primaryTagConverter != null) {
      tagDataConverters.add(primaryTagConverter);
    }

    final TagDataConverter fallbackTagConverter = this.getTagDataConverter(fallbackConverter);
    if (fallbackTagConverter != null) {
      tagDataConverters.add(fallbackTagConverter);
    }

    if (tagDataConverters.isEmpty()) {
      log.error("Could not find Tag Data Converter [ {} ]", converter);

      response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    } else if (fileParameter != null && fileParameter.getInputStream() != null) {

      InputStream is = fileParameter.getInputStream();

      final Csv csv = new Csv();

      if (delimiter != null) {
        log.debug("Setting Field Delimiter to [ {} ]", delimiter);
        csv.setFieldDelimiter(delimiter);
      }

      if (separator != null) {
        log.debug("Setting Field Separator to [ {} ]", separator);
        csv.setFieldSeparatorRead(separator);
      }

      if (clean) {
        is = this.stripLineEnds(is, charset, csv.getFieldSeparatorRead());
      }

      final Iterator<String[]> rows = csv.read(is, charset);

      try {
        final List<String> result = this.makeTags(tagManager, tagDataConverters, rows);

        try {
          jsonResponse.put("tagIds", result);
        } catch (JSONException e) {
          log.error("Could not serialized Tag Maker results into JSON", e);
        }

        this.addMessage(jsonResponse, result.size() + " tags were processed");
      } catch (InvalidTagFormatException e) {
        log.error("Could not create Tag due to illegal formatting", e);
        this.addMessage(jsonResponse, "Could not create tags due to illegal formatting");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      } catch (RepositoryException e) {
        log.error("Could not save Tags to JCR", e);
        this.addMessage(jsonResponse, "Could not save tags");
        response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }
    } else {
      log.error("Could not find CSV file in request.");
      this.addMessage(jsonResponse, "CSV file is missing");
      response.setStatus(SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

    response.getWriter().print(jsonResponse.toString());
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doGet(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      // Grab the search node.
      Node node = request.getResource().adaptTo(Node.class);

      // Grab the node that holds the repository information.
      Node proxyNode = DocProxyUtils.getProxyNode(node);

      // Grab the correct processor
      String type = proxyNode.getProperty(REPOSITORY_PROCESSOR).getString();
      ExternalRepositoryProcessor processor = tracker.getProcessorByType(type);
      if (processor == null) {
        LOGGER.warn("No processor found for type - {}", type);
        response.sendError(
            HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not handle this repository type.");
        return;
      }

      // Handle properties.
      Map<String, Object> searchProperties = new HashMap<String, Object>();
      handleProperties(searchProperties, node, request);

      // Process search
      Iterator<ExternalDocumentResult> results = processor.search(proxyNode, searchProperties);

      // Do the default search paging.
      long toSkip = SearchUtil.getPaging(request, -1);
      while (toSkip > 0) {
        if (results.hasNext()) {
          results.next();
          toSkip--;
        } else {
          throw new NoSuchElementException();
        }
      }

      response.setContentType("application/json");
      response.setCharacterEncoding("UTF-8");

      ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
      write.array();
      long nitems =
          SearchUtil.longRequestParameter(
              request, SearchConstants.PARAMS_ITEMS_PER_PAGE, SearchConstants.DEFAULT_PAGED_ITEMS);
      for (long i = 0; i < nitems && results.hasNext(); i++) {
        ExternalDocumentResult result = results.next();
        DocProxyUtils.writeMetaData(write, result);
      }
      write.endArray();

    } catch (RepositoryException e) {
      LOGGER.error("Got a repository exception when trying to grab search node information.", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search.");
    } catch (JSONException e) {
      LOGGER.error("Got a JSON exception when trying to grab search node information.", e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to perform search.");
    } catch (DocProxyException e) {
      LOGGER.error("Got a DocProxy exception when trying to grab search node information.", e);
      response.sendError(e.getCode(), e.getMessage());
    }
  }
Example #27
0
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    try {
      Resource resource = request.getResource();
      if (!resource.getPath().startsWith(SEARCH_PATH_PREFIX)) {
        response.sendError(
            HttpServletResponse.SC_FORBIDDEN,
            "Search templates can only be executed if they are located under "
                + SEARCH_PATH_PREFIX);
        return;
      }

      Node node = resource.adaptTo(Node.class);
      if (node != null && node.hasProperty(SAKAI_QUERY_TEMPLATE)) {
        // TODO: we might want to use this ?
        @SuppressWarnings("unused")
        boolean limitResults = true;
        if (node.hasProperty(SAKAI_LIMIT_RESULTS)) {
          limitResults = node.getProperty(SAKAI_LIMIT_RESULTS).getBoolean();
        }

        // KERN-1147 Respond better when all parameters haven't been provided for a query
        Query query = null;
        try {
          query = processQuery(request, node);
        } catch (MissingParameterException e) {
          response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
          return;
        }

        long nitems =
            SolrSearchUtil.longRequestParameter(
                request, PARAMS_ITEMS_PER_PAGE, DEFAULT_PAGED_ITEMS);
        long page = SolrSearchUtil.longRequestParameter(request, PARAMS_PAGE, 0);

        // allow number of items to be specified in sakai:query-template-options
        if (query.getOptions().containsKey(PARAMS_ITEMS_PER_PAGE)) {
          nitems = Long.valueOf(query.getOptions().get(PARAMS_ITEMS_PER_PAGE));
        } else {
          // add this to the options so that all queries are constrained to a limited
          // number of returns per page.
          query.getOptions().put(PARAMS_ITEMS_PER_PAGE, Long.toString(nitems));
        }

        if (query.getOptions().containsKey(PARAMS_PAGE)) {
          page = Long.valueOf(query.getOptions().get(PARAMS_PAGE));
        } else {
          // add this to the options so that all queries are constrained to a limited
          // number of returns per page.
          query.getOptions().put(PARAMS_PAGE, Long.toString(page));
        }

        boolean useBatch = false;
        // Get the
        SolrSearchBatchResultProcessor searchBatchProcessor = defaultSearchBatchProcessor;
        if (node.hasProperty(SAKAI_BATCHRESULTPROCESSOR)) {
          searchBatchProcessor =
              batchProcessors.get(node.getProperty(SAKAI_BATCHRESULTPROCESSOR).getString());
          useBatch = true;
          if (searchBatchProcessor == null) {
            searchBatchProcessor = defaultSearchBatchProcessor;
          }
        }

        SolrSearchResultProcessor searchProcessor = defaultSearchProcessor;
        if (node.hasProperty(SAKAI_RESULTPROCESSOR)) {
          searchProcessor = processors.get(node.getProperty(SAKAI_RESULTPROCESSOR).getString());
          if (searchProcessor == null) {
            searchProcessor = defaultSearchProcessor;
          }
        }

        SolrSearchResultSet rs = null;
        try {
          // Prepare the result set.
          // This allows a processor to do other queries and manipulate the results.
          if (useBatch) {
            rs = searchBatchProcessor.getSearchResultSet(request, query);
          } else {
            rs = searchProcessor.getSearchResultSet(request, query);
          }
        } catch (SolrSearchException e) {
          response.sendError(e.getCode(), e.getMessage());
          return;
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter());
        write.setTidy(isTidy(request));

        write.object();
        write.key(PARAMS_ITEMS_PER_PAGE);
        write.value(nitems);
        write.key(JSON_RESULTS);

        write.array();

        Iterator<Result> iterator = rs.getResultSetIterator();
        if (useBatch) {
          LOGGER.info("Using batch processor for results");
          searchBatchProcessor.writeResults(request, write, iterator);
        } else {
          LOGGER.info("Using regular processor for results");
          // We don't skip any rows ourselves here.
          // We expect a rowIterator coming from a resultset to be at the right place.
          for (long i = 0; i < nitems && iterator.hasNext(); i++) {
            // Get the next row.
            Result result = iterator.next();

            // Write the result for this row.
            searchProcessor.writeResult(request, write, result);
          }
        }
        write.endArray();

        // write the total out after processing the list to give the underlying iterator
        // a chance to walk the results then report how many there were.
        write.key(TOTAL);
        write.value(rs.getSize());

        write.endObject();
      }
    } catch (RepositoryException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JSONException e) {
      LOGGER.error(e.getMessage(), e);
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
  }
Example #28
0
  @Test
  public void testProperPost()
      throws ServletException, IOException, RepositoryException, JSONException,
          AccessDeniedException, StorageClientException {
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class);

    javax.jcr.Session jcrSession =
        Mockito.mock(
            javax.jcr.Session.class,
            Mockito.withSettings().extraInterfaces(SessionAdaptable.class));
    Session mockSession = mock(Session.class);
    ContentManager contentManager = mock(ContentManager.class);
    when(mockSession.getContentManager()).thenReturn(contentManager);
    Mockito.when(((SessionAdaptable) jcrSession).getSession()).thenReturn(mockSession);
    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    Mockito.when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSession);
    expect(request.getResourceResolver()).andReturn(resourceResolver);

    // Provide parameters
    String[] dimensions = new String[] {"16x16", "32x32"};
    addStringRequestParameter(request, "img", "/~johndoe/people.png");
    addStringRequestParameter(request, "save", "/~johndoe/breadcrumbs");
    addStringRequestParameter(request, "x", "10");
    addStringRequestParameter(request, "y", "10");
    addStringRequestParameter(request, "width", "70");
    addStringRequestParameter(request, "height", "70");
    addStringRequestParameter(request, "dimensions", StringUtils.join(dimensions, 0, ';'));
    expect(request.getRemoteUser()).andReturn("johndoe");

    String imagePath = "a:johndoe/people.png";
    when(contentManager.getInputStream(imagePath))
        .thenReturn(getClass().getClassLoader().getResourceAsStream("people.png"));
    when(contentManager.get(anyString())).thenReturn(new Content("foo", null));

    SparseContentResource someResource = mock(SparseContentResource.class);
    when(someResource.adaptTo(Content.class))
        .thenReturn(
            new Content(
                imagePath,
                ImmutableMap.of(
                    "mimeType", (Object) "image/png", "_bodyLocation", "2011/lt/zz/x8")));
    JackrabbitSession jrSession = mock(JackrabbitSession.class);
    SparseMapUserManager userManager = mock(SparseMapUserManager.class);
    when(userManager.getSession()).thenReturn(mockSession);
    when(jrSession.getUserManager()).thenReturn(userManager);
    when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jrSession);
    when(resourceResolver.getResource(anyString())).thenReturn(someResource);

    // Capture output.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter write = new PrintWriter(baos);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    expect(response.getWriter()).andReturn(write);

    replay();
    servlet.doPost(request, response);
    write.flush();

    String s = baos.toString("UTF-8");
    JSONObject o = new JSONObject(s);

    JSONArray files = o.getJSONArray("files");
    assertEquals(2, files.length());
    for (int i = 0; i < files.length(); i++) {
      String url = files.getString(i);
      assertEquals("/~johndoe/breadcrumbs/" + dimensions[i] + "_people.png", url);
    }
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");

    TidyJSONWriter writer = new TidyJSONWriter(response.getWriter());
    writer.setTidy("true".equals(request.getParameter(TIDY)));

    ResourceResolver resolver = request.getResourceResolver();
    Session session = resolver.adaptTo(Session.class);

    String paths[] = request.getParameterValues(PATH);
    List<Reference> allReferences = new ArrayList<Reference>();
    if (paths != null) {
      // search all refs that may be contained in one of the passed paths
      for (String path : paths) {
        if (path.length() > 0) {
          // get content node
          Resource r = resolver.getResource(path + "/" + JcrConstants.JCR_CONTENT);
          if (r == null) {
            r = resolver.getResource(path);
          }

          if (r == null) {
            continue;
          }

          for (ReferenceProvider referenceProvider : referenceProviders) {
            allReferences.addAll(referenceProvider.findReferences(r));
          }
        }
      }
    }

    try {
      writer.object();
      writer.key("assets");
      writer.array();

      for (Reference reference : allReferences) {

        boolean published = false;
        boolean outdated = false;
        ReplicationStatus replStatus = null;
        final Resource resource = reference.getResource();
        boolean canReplicate = canReplicate(reference.getResource().getPath(), session);
        long lastPublished = 0;
        if (resource != null) {
          replStatus = resource.adaptTo(ReplicationStatus.class);
          if (replStatus != null) {
            published = replStatus.isDelivered() || replStatus.isActivated();
            if (published) {
              lastPublished = replStatus.getLastPublished().getTimeInMillis();
              outdated = lastPublished < reference.getLastModified();
            }
          }

          log.debug(
              "Considering reference at {} . Published: {}, outdated: {} ( lastPublished: {}, lastModified: {} )",
              new Object[] {
                reference.getResource().getPath(),
                published,
                outdated,
                new Date(lastPublished),
                new Date(reference.getLastModified())
              });
        }

        if (!published || outdated) {
          writer.object();
          writer.key("type").value(reference.getType());
          writer.key("path").value(reference.getResource().getPath());
          writer.key("name").value(reference.getName());
          if (replStatus != null) {
            writer.key("published").value(published);
          }
          writer.key("outdated").value(outdated);
          writer.key("status").value(outdated ? "outdated" : "not available");
          writer.key("disabled").value(!canReplicate);
          writer.endObject();
        }
      }

      writer.endArray();
      writer.endObject();
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }