Пример #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();
  }
Пример #2
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...
    }
  }
Пример #3
0
  @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);
    }
  }
Пример #4
0
 @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);
 }
Пример #5
0
 @Override
 protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   String paramUser = request.getParameter(SiteService.SiteEvent.USER);
   logger.info("Request to add user " + paramUser);
   String paramGroup = "";
   try {
     Node requestedNode = request.getResource().adaptTo(Node.class);
     Value[] authorizables = requestedNode.getProperty("sakai:authorizables").getValues();
     paramGroup = authorizables[1].getString();
     request.setAttribute(JoinRequestConstants.PARAM_SITENODE, requestedNode);
     Session session = slingRepository.loginAdministrative(null);
     UserManager userManager = AccessControlUtil.getUserManager(session);
     Authorizable userAuth = userManager.getAuthorizable(paramUser);
     Group groupAuth = (Group) userManager.getAuthorizable(paramGroup);
     if (siteJoinIsAuthorized(request)) {
       groupAuth.addMember(userAuth);
       logger.info(paramUser + " added as member of group " + paramGroup);
     } else {
       response.sendError(403, "Not authorized to add member to site.");
     }
     if (session.hasPendingChanges()) {
       session.save();
     }
   } catch (Exception e) {
     response.sendError(500, e.getMessage());
   }
 }
Пример #6
0
  @Test
  public void testAnon() throws IOException, ServletException {
    SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class);
    SlingHttpServletResponse response = createMock(SlingHttpServletResponse.class);

    expect(request.getRemoteUser()).andReturn("anonymous");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Anonymous user cannot crop images.");
    replay();
    servlet.doPost(request, response);
  }
Пример #7
0
 private boolean authenticate(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws IOException {
   final String userId = request.getResourceResolver().getUserID();
   if (!isPublish()) {
     response.sendError(404);
     return false;
   } else if (!"admin".equals(userId)) {
     response.sendError(403);
     return false;
   } else {
     return true;
   }
 }
 /**
  * Allow origin access control.
  *
  * @param request The sling request
  * @param response The sling response
  */
 protected void allowCORS(
     final SlingHttpServletRequest request, final SlingHttpServletResponse response) {
   if (null == externalizer) {
     return;
   }
   final String localOrigin = externalizer.absoluteLink(request, request.getScheme(), "");
   if (!(localOrigin.equals(request.getHeader("Origin")))) {
     response.setHeader("Access-Control-Allow-Credentials", "true");
     response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
     response.setHeader("Access-Control-Allow-Headers", "CONTENT-TYPE, LOCATION, *");
     response.setHeader("Access-Control-Expose-Headers", "Content-Type, Location");
   }
 }
Пример #9
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);
   }
 }
Пример #10
0
  @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);
    }
  }
Пример #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());
    }
  }
 /**
  * {@inheritDoc}
  *
  * @throws IOException
  * @see
  *     org.sakaiproject.nakamura.api.proxy.ProxyPostProcessor#process(org.apache.sling.api.SlingHttpServletResponse,
  *     org.sakaiproject.nakamura.api.proxy.ProxyResponse)
  */
 public void process(
     Map<String, Object> templateParams,
     SlingHttpServletResponse response,
     ProxyResponse proxyResponse)
     throws IOException {
   for (Entry<String, String[]> h : proxyResponse.getResponseHeaders().entrySet()) {
     for (String v : h.getValue()) {
       response.setHeader(h.getKey(), v);
     }
   }
   int code = proxyResponse.getResultCode();
   response.setStatus(code);
   IOUtils.stream(proxyResponse.getResponseBodyAsInputStream(), response.getOutputStream());
 }
Пример #13
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);
   }
 }
  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);
  }
 /**
  * @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
 protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp)
     throws ServletException, IOException {
   final Resource resource = req.getResource();
   resp.getOutputStream().println(resource.toString());
   resp.getOutputStream().println("This content is generated by the SimpleServlet");
 }
Пример #17
0
  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();
  }
 @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);
 }
Пример #19
0
  @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());
  }
  @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);
      }
    }
  }
Пример #21
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();
  }
Пример #23
0
 private void setupRedirect(String target) throws JspException {
   Page currentPage = getContextAttribute("currentPage");
   SlingHttpServletResponse response = getContextAttribute("slingResponse");
   // The target must be checked here - if an empty target then you send the error, not just if
   // the target equals the current page (which you check to ensure you don't get any infinite
   // loops.
   if (StringUtils.isNotEmpty(target) && !target.equals(currentPage.getPath())) {
     response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
     //            response.setHeader( "Location", UtilityFunctions.createValidLink( target, "" )
     // );
     response.setHeader("Connection", "close");
   } else if (sendError) {
     try {
       response.sendError(HttpServletResponse.SC_NOT_FOUND);
     } catch (IOException e) {
       throw new JspException(e);
     }
   }
 }
 /**
  * @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);
 }
  @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);
    }
  }
 @Override
 protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
     throws ServletException, IOException {
   DefaultServletDelegate delegate =
       (DefaultServletDelegate) request.getAttribute(DefaultServletSwitch.class.getName());
   if (delegate != null) {
     delegate.doDelegateGet(request, response);
   } else {
     response.sendError(404);
   }
 }
Пример #27
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);
    }
  }
 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);
   }
 }
Пример #29
0
 @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.");
     }
   }
 }
  /** {@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;
    }
  }