コード例 #1
0
  /** @return Creates a unique path to an activity in the form of 2010-01-21-09-randombit */
  public static String createId() {
    Calendar c = Calendar.getInstance();

    String[] vals = new String[4];
    vals[0] = "" + c.get(Calendar.YEAR);
    vals[1] = StringUtils.leftPad("" + (c.get(Calendar.MONTH) + 1), 2, "0");
    vals[2] = StringUtils.leftPad("" + c.get(Calendar.DAY_OF_MONTH), 2, "0");
    vals[3] = StringUtils.leftPad("" + c.get(Calendar.HOUR_OF_DAY), 2, "0");

    StringBuilder id = new StringBuilder();

    for (String v : vals) {
      id.append(v).append("-");
    }

    byte[] bytes = new byte[20];
    String randomHash = "";
    try {
      if (random == null) {
        random = SecureRandom.getInstance("SHA1PRNG");
      }
      random.nextBytes(bytes);
      randomHash = Arrays.toString(bytes);
      randomHash = org.sakaiproject.nakamura.util.StringUtils.sha1Hash(randomHash);
    } catch (NoSuchAlgorithmException e) {
    } catch (UnsupportedEncodingException e) {
    }

    id.append(randomHash);
    return id.toString();
  }
コード例 #2
0
 private String generatePoolId() throws UnsupportedEncodingException, NoSuchAlgorithmException {
   synchronized (lock) {
     String newId = String.valueOf(startingPoint++) + "-" + serverId;
     MessageDigest md = MessageDigest.getInstance("SHA-1");
     return StringUtils.encode(md.digest(newId.getBytes("UTF-8")), ENCODING);
   }
 }
コード例 #3
0
ファイル: IDTest.java プロジェクト: xiannenglin/nakamura
  @Test
  public void testId() {

    for (int i = 0; i < 10; i++) {
      Thread t =
          new Thread(
              new Runnable() {

                public void run() {
                  synchronized (lockObject) {
                    nrunning++;
                  }
                  try {
                    for (int j = 0; j < 100; j++) {
                      BigInteger id = getId();
                      assertFalse("Failed for " + id + " after " + j, hash.containsKey(id));
                      hash.put(id, id);
                    }
                  } finally {
                    synchronized (lockObject) {
                      nrunning--;
                    }
                  }
                }
              });
      t.start();
    }

    do {
      LOGGER.info("Running " + nrunning + " Hash Size is " + hash.size());
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        LOGGER.info(e.getMessage(), e);
      }
    } while (nrunning > 0);

    for (Entry<BigInteger, BigInteger> e : hash.entrySet()) {
      LOGGER.info(
          " Entry is "
              + e.getValue()
              + " "
              + StringUtils.encode(e.getValue().toByteArray(), StringUtils.URL_SAFE_ENCODING).trim()
              + " Epoch "
              + String.valueOf(epoch)
              + " Size "
              + String.valueOf(System.currentTimeMillis() - epoch));
    }
  }
コード例 #4
0
 private String hash(String poolId) throws NoSuchAlgorithmException, UnsupportedEncodingException {
   MessageDigest md = MessageDigest.getInstance("SHA-1");
   String encodedId = StringUtils.encode(md.digest(poolId.getBytes("UTF-8")), HASHENCODING);
   LOGGER.info("Hashing [{}] gave [{}] ", poolId, encodedId);
   return "/_p/"
       + encodedId.charAt(0)
       + "/"
       + encodedId.substring(1, 3)
       + "/"
       + encodedId.substring(3, 5)
       + "/"
       + encodedId.substring(5, 7)
       + "/"
       + poolId;
 }
コード例 #5
0
  /**
   * Get the path from an activity id.
   *
   * @param id The ID for an activity.
   * @param startPath The starting path.
   * @return Given an id '2010-01-21-09-randombit' and startPath '/foo/bar' this will return
   *     '/foo/bar/2010/01/21/09/2010-01-21-09-randombit'.
   */
  public static String getPathFromId(String id, String startPath) {
    String[] hashes = org.sakaiproject.nakamura.util.StringUtils.split(id, '-');
    StringBuilder sb;

    if (startPath == null) {
      sb = new StringBuilder();
    } else {
      startPath = PathUtils.normalizePath(startPath);
      sb = new StringBuilder(startPath);
    }

    for (int i = 0; i < (hashes.length - 1); i++) {
      sb.append("/").append(hashes[i]);
    }
    return sb.append("/").append(id).toString();
  }
コード例 #6
0
ファイル: LinkServlet.java プロジェクト: Cyntech/nakamura
  @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);

    System.err.println("Node is " + node + " content is " + content);
    String link = null;
    try {
      if (node != null && node.hasProperty(FilesConstants.SAKAI_LINK)) {
        link = node.getProperty(FilesConstants.SAKAI_LINK).getString();
      } else if (content != null && content.hasProperty(FilesConstants.SAKAI_LINK)) {
        link = (String) content.getProperty(FilesConstants.SAKAI_LINK);
      }
      System.err.println("Link is " + link);

      if (link != null) {
        String[] linkProps = StringUtils.split(link, ':');
        LinkHandler handler = null;
        String path = null;
        if (linkProps.length == 2) {
          handler = fileHandlerTracker.getProcessorByName(linkProps[0]);
          path = linkProps[1];
        } else {
          if (node != null) {
            handler = new JcrInternalFileHandler();
          } else {
            handler = new SparseContentInternalFileHandler();
          }
          path = link;
        }
        if (handler != null) {
          handler.handleFile(request, response, path);
        }
      }
    } catch (RepositoryException e) {
      LOGGER.warn(e.getMessage(), e);
      response.sendError(500, "Unable to handle linked file.");
    }
  }
コード例 #7
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);
    }
  }
コード例 #8
0
  /**
   * {@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.");
    }
  }