@Override
 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   Resource resource = request.getResource();
   Node node = resource.adaptTo(Node.class);
   Content content = resource.adaptTo(Content.class);
   if (node != null) {
     try {
       Session jcrSession = request.getResourceResolver().adaptTo(Session.class);
       JSONWriter write = new JSONWriter(response.getWriter());
       FileUtils.writeLinkNode(node, jcrSession, write);
     } catch (JSONException e) {
       response.sendError(500, "Unable to parse JSON.");
     } catch (RepositoryException e) {
       LOGGER.warn("Unable to get file info for link.");
       response.sendError(500, "Unable get file info.");
     }
   } else {
     try {
       org.sakaiproject.nakamura.api.lite.Session session =
           resource.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class);
       JSONWriter write = new JSONWriter(response.getWriter());
       FileUtils.writeLinkNode(content, session, write);
     } catch (StorageClientException e) {
       LOGGER.warn("Unable to get file info for link.");
       response.sendError(500, "Unable get file info.");
     } catch (JSONException e) {
       response.sendError(500, "Unable to parse JSON.");
     }
   }
 }
 @Before
 public void setup() throws IOException {
   when(response.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
   when(request.getResource()).thenReturn(resource);
   servlet = new SiteDeleteServlet();
   servlet.bindSiteService(siteService);
 }
  public void setUp() throws IOException {
    // Init mocks
    MockitoAnnotations.initMocks(this);

    Map<String, String[]> properties = new HashMap<String, String[]>();
    properties.put(WidgetServiceImpl.WIDGET_IGNORE_NAMES, new String[] {"bundles"});
    properties.put(
        WidgetServiceImpl.WIDGET_VALID_MIMETYPES,
        new String[] {
          "text/plain", "text/css", "text/html", "application/json", "application/xml"
        });
    properties.put(WidgetServiceImpl.WIDGET_FOLDERS, new String[] {"/widgets"});

    widgetService = new WidgetServiceImpl();
    widgetService.cacheManagerService = cacheManagerService;
    widgetService.activate(properties);

    when(request.getResourceResolver()).thenReturn(resolver);

    // For test cases we will always assume that a locale of nl_NL is request.
    RequestParameter localeParam = mock(RequestParameter.class);
    when(localeParam.getString()).thenReturn("nl_NL");
    when(request.getRequestParameter("locale")).thenReturn(localeParam);

    // Mock the response print writer.
    stringWriter = new StringWriter();
    printWriter = new PrintWriter(stringWriter);
    when(response.getWriter()).thenReturn(printWriter);

    // Mock all the test resources as "Sling Resources".
    File file = new File(getClass().getResource("/widgets").getPath());
    mockResource("/widgets", file);
  }
Beispiel #4
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...
    }
  }
  /** {@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;
    }
  }
  @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);
      }
    }
  }
  @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);
    }
  }
 /**
  * @param response
  * @throws IOException
  */
 private void sendIndex(SlingHttpServletResponse response) throws IOException {
   PrintWriter writer = response.getWriter();
   writer.append(DocumentationConstants.HTML_HEADER);
   writer.append("<h1>List of Services</h1>");
   writer.append("<ul>");
   Map<String, ServletDocumentation> m = servletTracker.getServletDocumentation();
   List<ServletDocumentation> o = new ArrayList<ServletDocumentation>(m.values());
   Collections.sort(o);
   for (ServletDocumentation k : o) {
     String key = k.getKey();
     if (key != null) {
       writer.append("<li><a href=\"");
       writer.append(DocumentationConstants.PREFIX + "/servlet");
       writer.append("?p=");
       writer.append(k.getKey());
       writer.append("\">");
       writer.append(k.getName());
       writer.append("</a><p>");
       writer.append(k.getShortDescription());
       writer.append("</p></li>");
     }
   }
   writer.append("</ul>");
   writer.append(DocumentationConstants.HTML_FOOTER);
 }
 @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);
 }
 /**
  * @param request
  * @param response
  * @param doc
  * @throws IOException
  */
 private void send(
     SlingHttpServletRequest request, SlingHttpServletResponse response, ServletDocumentation doc)
     throws IOException {
   PrintWriter writer = response.getWriter();
   writer.append(DocumentationConstants.HTML_HEADER);
   writer.append("<h1>Service: ");
   writer.append(doc.getName());
   writer.append("</h1>");
   doc.send(request, response);
   writer.append(DocumentationConstants.HTML_FOOTER);
 }
 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) {
   }
 }
Beispiel #12
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);
    }
  }
Beispiel #14
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 {
    String path = TemplateUtils.getParameterValue("path", request);
    boolean success = false;

    if (path != null) {
      resourceResolver = request.getResourceResolver();
      session = resourceResolver.adaptTo(Session.class);
      success = removeNode(path);
    }

    response.getWriter().write("{\"success\":" + success + "}");
  }
Beispiel #16
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);
   }
 }
  @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;
  }
  @Override
  protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    response.setHeader("Content-Type", "application/json");
    //		response.getWriter().print("{\"coming\":\"soon\"}");

    String[] keys = repository.getDescriptorKeys();
    JSONObject jsonObj = new JSONObject();
    for (String key : keys) {
      try {
        jsonObj.put(key, repository.getDescriptor(key));
      } catch (JSONException e) {
        e.printStackTrace();
      }
    }
    response.getWriter().print(jsonObj.toString());
  }
Beispiel #19
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");
    }
  }
  @Test
  public void testGet()
      throws VersionException, UnsupportedRepositoryOperationException, InvalidItemStateException,
          LockException, RepositoryException, IOException, ServletException {
    SlingHttpServletRequest request = createNiceMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createNiceMock(SlingHttpServletResponse.class);
    Resource resource = createNiceMock(Resource.class);
    Node node = createNiceMock(Node.class);
    Version version = createNiceMock(Version.class);
    PropertyIterator propertyIterator = createNiceMock(PropertyIterator.class);
    VersionHistory versionHistory = createNiceMock(VersionHistory.class);
    VersionIterator versionIterator = createNiceMock(VersionIterator.class);
    Node versionNode = createNiceMock(Node.class);
    Session session = createNiceMock(Session.class);
    Workspace workspace = createNiceMock(Workspace.class);
    VersionManager versionManager = createNiceMock(VersionManager.class);

    EasyMock.expect(request.getResource()).andReturn(resource).anyTimes();
    EasyMock.expect(resource.adaptTo(Node.class)).andReturn(node).anyTimes();
    PrintWriter pw = new PrintWriter(new ByteArrayOutputStream());
    EasyMock.expect(response.getWriter()).andReturn(pw).anyTimes();

    EasyMock.expect(node.getSession()).andReturn(session);
    EasyMock.expect(session.getWorkspace()).andReturn(workspace);
    EasyMock.expect(workspace.getVersionManager()).andReturn(versionManager);
    EasyMock.expect(versionManager.getVersionHistory("/foo")).andReturn(versionHistory);
    EasyMock.expect(node.getPath()).andReturn("/foo").anyTimes();
    EasyMock.expect(versionHistory.getAllVersions()).andReturn(versionIterator);
    EasyMock.expect(versionIterator.getSize()).andReturn(2L);
    EasyMock.expect(versionIterator.hasNext()).andReturn(true);
    EasyMock.expect(versionIterator.nextVersion()).andReturn(version);
    EasyMock.expect(versionIterator.hasNext()).andReturn(true);
    EasyMock.expect(versionIterator.nextVersion()).andReturn(version);

    EasyMock.expect(version.getName()).andReturn("NameVersioNode").anyTimes();
    EasyMock.expect(version.getNode(JcrConstants.JCR_FROZENNODE)).andReturn(versionNode).anyTimes();
    EasyMock.expect(version.getProperties()).andReturn(propertyIterator).anyTimes();
    EasyMock.expect(propertyIterator.hasNext()).andReturn(false).anyTimes();

    replay();

    listVersionsServlet.doGet(request, response);
    verify();
  }
  /**
   * Perform the actual request. {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingSafeMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  protected void doGet(SlingHttpServletRequest req, SlingHttpServletResponse resp)
      throws IOException {

    Servlet servlet = ((SlingHttpServletRequest) req).getResource().adaptTo(Servlet.class);
    if (servlet != null) {
      try {
        servlet.service((ServletRequest) req, (ServletResponse) resp);
      } catch (ServletException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      // send error
      PrintWriter p = resp.getWriter();
      p.print("Failed miserably");
      p.flush();
    }

    return;
  }
Beispiel #22
0
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    if (!authenticate(request, response)) {
      return;
    }

    final String msgId = StringUtils.removeStart(request.getRequestPathInfo().getSuffix(), "/");
    if (StringUtils.isBlank(msgId)) {
      throw new ServletException("No suffix found");
    }
    if (!sentMessages.contains(msgId)) {
      throw new ServletException("No one is waiting for confirmation for " + msgId);
    } else {
      receivedConfirmations.add(msgId);
      synchronized (receivedConfirmations) {
        receivedConfirmations.notifyAll();
      }
      response.getWriter().append("Message " + msgId + " confirmed");
      LOG.debug("Message " + msgId + " confirmed");
    }
  }
Beispiel #23
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);
    }
  }
  /** {@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);
    }
  }
Beispiel #25
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);
    }
  }
  @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);
    }
  }
Beispiel #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);
    }
  }
  @Test
  public void testCreate() throws Exception {

    // activate
    when(slingRepository.loginAdministrative(null)).thenReturn(adminSession);

    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(resourceResolver.adaptTo(javax.jcr.Session.class)).thenReturn(jcrSesson);
    Session session = repository.loginAdministrative("ieb");
    when(jcrSesson.getUserManager()).thenReturn(sparseMapUserManager);
    when(sparseMapUserManager.getSession()).thenReturn(session);
    when(clusterTrackingService.getClusterUniqueId())
        .thenReturn(String.valueOf(System.currentTimeMillis()));

    when(request.getRequestPathInfo()).thenReturn(requestPathInfo);
    when(requestPathInfo.getExtension()).thenReturn(null);

    when(adminSession.getUserManager()).thenReturn(userManager);
    when(adminSession.getPrincipalManager()).thenReturn(principalManager);
    when(adminSession.getAccessControlManager()).thenReturn(accessControlManager);
    when(request.getRemoteUser()).thenReturn("ieb");

    when(request.getRequestParameterMap()).thenReturn(requestParameterMap);
    Map<String, RequestParameter[]> map = new HashMap<String, RequestParameter[]>();

    RequestParameter[] requestParameters =
        new RequestParameter[] {
          requestParameter1, requestParameterNot, requestParameter2,
        };
    map.put("files", requestParameters);

    when(requestParameterMap.entrySet()).thenReturn(map.entrySet());

    when(requestParameter1.isFormField()).thenReturn(false);
    when(requestParameter1.getContentType()).thenReturn("application/pdf");
    when(requestParameter1.getFileName()).thenReturn("testfilename.pdf");
    InputStream input1 = new ByteArrayInputStream(new byte[10]);
    when(requestParameter1.getInputStream()).thenReturn(input1);

    when(requestParameter2.isFormField()).thenReturn(false);
    when(requestParameter2.getContentType()).thenReturn("text/html");
    when(requestParameter2.getFileName()).thenReturn("index.html");
    InputStream input2 = new ByteArrayInputStream(new byte[10]);
    when(requestParameter2.getInputStream()).thenReturn(input2);

    when(requestParameterNot.isFormField()).thenReturn(true);

    // deep create
    // when(adminSession.nodeExists(CreateContentPoolServlet.POOLED_CONTENT_ROOT)).thenReturn(true);
    when(adminSession.itemExists(Mockito.anyString())).thenReturn(true);

    // Because the pooled content paths are generated by a private method,
    // mocking the repository is more problematic than usual. The test
    // therefore relies on inside knowledge that there should be three
    // calls to deepGetOrCreateNode for each file: one for the pooled content
    // node, one for its members node, and one for the manager node.
    when(adminSession.getItem(Mockito.anyString()))
        .thenAnswer(
            new Answer<Item>() {
              public Item answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                String path = (String) args[0];
                if (path.endsWith(POOLED_CONTENT_MEMBERS_NODE)) {
                  return membersNode;
                } else if (path.endsWith("ieb")) {
                  return memberNode;
                } else {
                  return parentNode;
                }
              }
            });

    when(parentNode.addNode(JCR_CONTENT, NT_RESOURCE)).thenReturn(resourceNode);
    when(adminSession.getValueFactory()).thenReturn(valueFactory);
    when(valueFactory.createBinary(Mockito.any(InputStream.class))).thenReturn(binary);

    // access control utils
    accessControlList =
        new AccessControlList() {

          // Add an "addEntry" method so AccessControlUtil can execute something.
          // This method doesn't do anything useful.
          @SuppressWarnings("unused")
          public boolean addEntry(Principal principal, Privilege[] privileges, boolean isAllow)
              throws AccessControlException {
            return true;
          }

          public void removeAccessControlEntry(AccessControlEntry ace)
              throws AccessControlException, RepositoryException {}

          public AccessControlEntry[] getAccessControlEntries() throws RepositoryException {
            return new AccessControlEntry[0];
          }

          public boolean addAccessControlEntry(Principal principal, Privilege[] privileges)
              throws AccessControlException, RepositoryException {
            return false;
          }
        };
    when(accessControlManager.privilegeFromName(Mockito.anyString())).thenReturn(allPrivilege);
    AccessControlPolicy[] acp = new AccessControlPolicy[] {accessControlList};
    when(accessControlManager.getPolicies(Mockito.anyString())).thenReturn(acp);

    StringWriter stringWriter = new StringWriter();
    when(response.getWriter()).thenReturn(new PrintWriter(stringWriter));

    CreateContentPoolServlet cp = new CreateContentPoolServlet();
    cp.eventAdmin = eventAdmin;
    cp.clusterTrackingService = clusterTrackingService;
    cp.sparseRepository = repository;

    cp.doPost(request, response);

    // Verify that we created all the nodes.

    JSONObject jsonObject = new JSONObject(stringWriter.toString());
    Assert.assertNotNull(jsonObject.getString("testfilename.pdf"));
    Assert.assertNotNull(jsonObject.getString("index.html"));
    Assert.assertEquals(2, jsonObject.length());
  }
  /**
   * {@inheritDoc}
   *
   * @see
   *     org.apache.sling.api.servlets.SlingAllMethodsServlet#doPost(org.apache.sling.api.SlingHttpServletRequest,
   *     org.apache.sling.api.SlingHttpServletResponse)
   */
  @Override
  protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {

    // Check if the current user is logged in.
    if (request.getRemoteUser().equals("anonymous")) {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images.");
      return;
    }

    RequestParameter imgParam = request.getRequestParameter("img");
    RequestParameter saveParam = request.getRequestParameter("save");
    RequestParameter xParam = request.getRequestParameter("x");
    RequestParameter yParam = request.getRequestParameter("y");
    RequestParameter widthParam = request.getRequestParameter("width");
    RequestParameter heightParam = request.getRequestParameter("height");
    RequestParameter dimensionsParam = request.getRequestParameter("dimensions");

    if (imgParam == null
        || saveParam == null
        || xParam == null
        || yParam == null
        || widthParam == null
        || heightParam == null
        || dimensionsParam == null) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters are required: img, save, x, y, width, height, dimensions");
      return;
    }

    try {
      // Grab the session
      ResourceResolver resourceResolver = request.getResourceResolver();
      Session session = resourceResolver.adaptTo(Session.class);

      String img = imgParam.getString();
      String save = saveParam.getString();
      int x = Integer.parseInt(xParam.getString());
      int y = Integer.parseInt(yParam.getString());
      int width = Integer.parseInt(widthParam.getString());
      int height = Integer.parseInt(heightParam.getString());
      String[] dimensionsList = StringUtils.split(dimensionsParam.getString(), ';');
      List<Dimension> dimensions = new ArrayList<Dimension>();
      for (String s : dimensionsList) {
        Dimension d = new Dimension();
        String[] size = StringUtils.split(s, 'x');
        int diWidth = Integer.parseInt(size[0]);
        int diHeight = Integer.parseInt(size[1]);

        diWidth = checkIntBiggerThanZero(diWidth, 0);
        diHeight = checkIntBiggerThanZero(diHeight, 0);

        d.setSize(diWidth, diHeight);
        dimensions.add(d);
      }

      x = checkIntBiggerThanZero(x, 0);
      y = checkIntBiggerThanZero(y, 0);
      width = checkIntBiggerThanZero(width, 0);
      height = checkIntBiggerThanZero(height, 0);

      // Make sure the save path is correct.
      save = PathUtils.normalizePath(save) + "/";

      String[] crop = CropItProcessor.crop(session, x, y, width, height, dimensions, img, save);

      JSONWriter output = new JSONWriter(response.getWriter());
      output.object();
      output.key("files");
      output.array();
      for (String url : crop) {
        output.value(url);
      }
      output.endArray();
      output.endObject();

    } catch (ArrayIndexOutOfBoundsException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The dimensions have to be specified in a widthxheight;widthxheight fashion.");
      return;
    } catch (NumberFormatException e) {
      response.sendError(
          HttpServletResponse.SC_BAD_REQUEST,
          "The following parameters have to be integers: x, y, width, height. (Dimensions has to be of the form widthxheight;widthxheight");
      return;
    } catch (ImageException e) {
      // Something went wrong..
      logger.warn("ImageException e: " + e.getMessage());
      response.sendError(e.getCode(), e.getMessage());
    } catch (JSONException e) {
      response.sendError(500, "Unable to output JSON.");
    }
  }