public int copyCollectionResource(
      WebDAVRequest webDavRequest,
      Resource resource,
      String destination,
      boolean overwrite,
      long depth)
      throws WebDAVException {

    try {
      String[] destinationArray = WebDAVUtil.getPathArray(destination, true);

      long companyId = webDavRequest.getCompanyId();

      long parentFolderId = IGFolderConstants.DEFAULT_PARENT_FOLDER_ID;

      try {
        parentFolderId = getParentFolderId(companyId, destinationArray);
      } catch (NoSuchFolderException nsfe) {
        return HttpServletResponse.SC_CONFLICT;
      }

      IGFolder folder = (IGFolder) resource.getModel();

      long groupId = WebDAVUtil.getGroupId(companyId, destination);
      String name = WebDAVUtil.getResourceName(destinationArray);
      String description = folder.getDescription();

      int status = HttpServletResponse.SC_CREATED;

      if (overwrite) {
        if (deleteResource(groupId, parentFolderId, name)) {
          status = HttpServletResponse.SC_NO_CONTENT;
        }
      }

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(isAddCommunityPermissions(groupId));
      serviceContext.setAddGuestPermissions(true);
      serviceContext.setScopeGroupId(groupId);

      if (depth == 0) {
        IGFolderServiceUtil.addFolder(parentFolderId, name, description, serviceContext);
      } else {
        IGFolderServiceUtil.copyFolder(
            folder.getFolderId(), parentFolderId, name, description, serviceContext);
      }

      return status;
    } catch (DuplicateFolderNameException dfne) {
      return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (PrincipalException pe) {
      return HttpServletResponse.SC_FORBIDDEN;
    } catch (Exception e) {
      throw new WebDAVException(e);
    }
  }
  public int moveSimpleResource(
      WebDAVRequest webDavRequest, Resource resource, String destination, boolean overwrite)
      throws WebDAVException {

    try {
      String[] destinationArray = WebDAVUtil.getPathArray(destination, true);

      IGImage image = (IGImage) resource.getModel();

      long companyId = webDavRequest.getCompanyId();
      long groupId = WebDAVUtil.getGroupId(companyId, destinationArray);
      long parentFolderId = getParentFolderId(companyId, destinationArray);
      String name = WebDAVUtil.getResourceName(destinationArray);
      String description = image.getDescription();
      File file = null;
      String contentType = null;

      ServiceContext serviceContext = new ServiceContext();

      int status = HttpServletResponse.SC_CREATED;

      if (overwrite) {
        if (deleteResource(groupId, parentFolderId, name)) {
          status = HttpServletResponse.SC_NO_CONTENT;
        }
      }

      IGImageServiceUtil.updateImage(
          image.getImageId(),
          groupId,
          parentFolderId,
          name,
          description,
          file,
          contentType,
          serviceContext);

      return status;
    } catch (PrincipalException pe) {
      return HttpServletResponse.SC_FORBIDDEN;
    } catch (DuplicateFileException dfe) {
      return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (DuplicateFolderNameException dfne) {
      return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (Exception e) {
      throw new WebDAVException(e);
    }
  }
  @Override
  public String getURL(PortletRequest portletRequest, PortletResponse portletResponse) {

    ThemeDisplay themeDisplay = (ThemeDisplay) portletRequest.getAttribute(WebKeys.THEME_DISPLAY);

    PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();

    Portlet portlet = _portletLocalService.getPortletById(portletDisplay.getId());

    PortletURL portletURL =
        PortletURLFactoryUtil.create(
            portletRequest,
            PortletProviderUtil.getPortletId(
                DDMStructure.class.getName(), PortletProvider.Action.VIEW),
            PortletRequest.RENDER_PHASE);

    portletURL.setParameter("mvcPath", "/view.jsp");
    portletURL.setParameter("backURL", themeDisplay.getURLCurrent());
    portletURL.setParameter("groupId", String.valueOf(themeDisplay.getScopeGroupId()));
    portletURL.setParameter("refererPortletName", DLPortletKeys.DOCUMENT_LIBRARY);
    portletURL.setParameter("refererWebDAVToken", WebDAVUtil.getStorageToken(portlet));
    portletURL.setParameter("showAncestorScopes", Boolean.TRUE.toString());
    portletURL.setParameter("showManageTemplates", Boolean.FALSE.toString());

    return portletURL.toString();
  }
  protected long getFolderId(long companyId, String[] pathArray, boolean parent) throws Exception {

    long folderId = IGFolderConstants.DEFAULT_PARENT_FOLDER_ID;

    if (pathArray.length <= 1) {
      return folderId;
    } else {
      long groupId = WebDAVUtil.getGroupId(companyId, pathArray);

      int x = pathArray.length;

      if (parent) {
        x--;
      }

      for (int i = 2; i < x; i++) {
        String name = pathArray[i];

        IGFolder folder = IGFolderServiceUtil.getFolder(groupId, folderId, name);

        if (groupId == folder.getGroupId()) {
          folderId = folder.getFolderId();
        }
      }
    }

    return folderId;
  }
  public Resource getResource(WebDAVRequest webDavRequest) throws WebDAVException {

    try {
      String[] pathArray = webDavRequest.getPathArray();

      long companyId = webDavRequest.getCompanyId();
      long parentFolderId = getParentFolderId(companyId, pathArray);
      String name = WebDAVUtil.getResourceName(pathArray);

      if (Validator.isNull(name)) {
        String path = getRootPath() + webDavRequest.getPath();

        return new BaseResourceImpl(path, StringPool.BLANK, getToken());
      }

      try {
        IGFolder folder =
            IGFolderServiceUtil.getFolder(webDavRequest.getGroupId(), parentFolderId, name);

        if ((folder.getParentFolderId() != parentFolderId)
            || (webDavRequest.getGroupId() != folder.getGroupId())) {

          throw new NoSuchFolderException();
        }

        return toResource(webDavRequest, folder, false);
      } catch (NoSuchFolderException nsfe) {
        try {
          long groupId = webDavRequest.getGroupId();

          IGImage image =
              IGImageServiceUtil.getImageByFolderIdAndNameWithExtension(
                  groupId, parentFolderId, name);

          return toResource(webDavRequest, image, false);
        } catch (NoSuchImageException nsie) {
          return null;
        }
      }
    } catch (Exception e) {
      throw new WebDAVException(e);
    }
  }
  public Status makeCollection(WebDAVRequest webDavRequest) throws WebDAVException {

    try {
      HttpServletRequest request = webDavRequest.getHttpServletRequest();

      if (request.getContentLength() > 0) {
        return new Status(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
      }

      String[] pathArray = webDavRequest.getPathArray();

      long companyId = webDavRequest.getCompanyId();
      long groupId = webDavRequest.getGroupId();
      long parentFolderId = getParentFolderId(companyId, pathArray);
      String name = WebDAVUtil.getResourceName(pathArray);
      String description = StringPool.BLANK;

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(isAddCommunityPermissions(groupId));
      serviceContext.setAddGuestPermissions(true);
      serviceContext.setPlid(getPlid(webDavRequest.getGroupId()));
      serviceContext.setScopeGroupId(webDavRequest.getGroupId());

      IGFolderServiceUtil.addFolder(parentFolderId, name, description, serviceContext);

      String location = StringUtil.merge(pathArray, StringPool.SLASH);

      return new Status(location, HttpServletResponse.SC_CREATED);
    } catch (DuplicateFolderNameException dfne) {
      return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (NoSuchFolderException nsfe) {
      return new Status(HttpServletResponse.SC_CONFLICT);
    } catch (PrincipalException pe) {
      return new Status(HttpServletResponse.SC_FORBIDDEN);
    } catch (Exception e) {
      throw new WebDAVException(e);
    }
  }
  protected void sendGroups(HttpServletResponse response, User user, String path) throws Exception {

    if (!PropsValues.WEB_SERVER_SERVLET_DIRECTORY_INDEXING_ENABLED) {
      response.setStatus(HttpServletResponse.SC_FORBIDDEN);

      return;
    }

    List<WebServerEntry> webServerEntries = new ArrayList<WebServerEntry>();

    List<Group> groups = WebDAVUtil.getGroups(user);

    for (Group group : groups) {
      String name = HttpUtil.fixPath(group.getFriendlyURL());

      WebServerEntry webServerEntry =
          new WebServerEntry(path, name + StringPool.SLASH, null, null, group.getDescription(), 0);

      webServerEntries.add(webServerEntry);
    }

    sendHTML(response, path, webServerEntries);
  }
Beispiel #8
0
  public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVStorage webDAVStorage = new DLWebDAVStorageImpl();

    webDAVStorage.setToken("document_library");

    WebDAVUtil.addStorage(webDAVStorage);

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {
      mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
      Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
      headers = new HashMap<String, String>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
      throw new Exception();
    } catch (Exception e) {
      StackTraceElement[] stackTraceElements = e.getStackTrace();

      for (StackTraceElement stackTraceElement : stackTraceElements) {
        String methodName = stackTraceElement.getMethodName();

        if (methodName.equals("setUp")
            || methodName.equals("tearDown")
            || methodName.startsWith("test")) {

          String testName =
              StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

          testName =
              StringUtil.replace(testName, new String[] {"WebDAV", "Test"}, new String[] {"", ""});

          headers.put(
              "X-Litmus",
              testName
                  + ": ("
                  + stackTraceElement.getMethodName()
                  + ":"
                  + stackTraceElement.getLineNumber()
                  + ")");

          break;
        }
      }
    }

    if (data != null) {
      mockHttpServletRequest.setContent(data);

      String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

      if (contentType != null) {
        mockHttpServletRequest.setContentType(contentType);
      } else {
        mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
      }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
      String key = entry.getKey();
      String value = entry.getValue();

      mockHttpServletRequest.addHeader(key, value);
    }

    try {
      MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

      webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

      int statusCode = mockHttpServletResponse.getStatus();
      byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

      Map<String, String> responseHeaders = new HashMap<String, String>();

      for (String name : mockHttpServletResponse.getHeaderNames()) {
        responseHeaders.put(name, (String) mockHttpServletResponse.getHeader(name));
      }

      return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
  public int putResource(WebDAVRequest webDavRequest) throws WebDAVException {
    File file = null;

    try {
      HttpServletRequest request = webDavRequest.getHttpServletRequest();

      String[] pathArray = webDavRequest.getPathArray();

      long companyId = webDavRequest.getCompanyId();
      long groupId = webDavRequest.getGroupId();
      long parentFolderId = getParentFolderId(companyId, pathArray);
      String name = WebDAVUtil.getResourceName(pathArray);
      String description = StringPool.BLANK;

      file = FileUtil.createTempFile(FileUtil.getExtension(name));

      FileUtil.write(file, request.getInputStream());

      String contentType = MimeTypesUtil.getContentType(name);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(isAddCommunityPermissions(groupId));
      serviceContext.setAddGuestPermissions(true);

      try {
        IGImage image =
            IGImageServiceUtil.getImageByFolderIdAndNameWithExtension(
                groupId, parentFolderId, name);

        long imageId = image.getImageId();

        description = image.getDescription();

        String[] assetTagNames =
            AssetTagLocalServiceUtil.getTagNames(IGImage.class.getName(), imageId);

        serviceContext.setAssetTagNames(assetTagNames);

        IGImageServiceUtil.updateImage(
            imageId, groupId, parentFolderId, name, description, file, contentType, serviceContext);
      } catch (NoSuchImageException nsie) {
        IGImageServiceUtil.addImage(
            groupId, parentFolderId, name, description, file, contentType, serviceContext);
      }

      return HttpServletResponse.SC_CREATED;
    } catch (PrincipalException pe) {
      return HttpServletResponse.SC_FORBIDDEN;
    } catch (PortalException pe) {
      if (_log.isWarnEnabled()) {
        _log.warn(pe, pe);
      }

      return HttpServletResponse.SC_CONFLICT;
    } catch (Exception e) {
      throw new WebDAVException(e);
    } finally {
      if (file != null) {
        file.delete();
      }
    }
  }
  public int copySimpleResource(
      WebDAVRequest webDavRequest, Resource resource, String destination, boolean overwrite)
      throws WebDAVException {

    File file = null;

    try {
      String[] destinationArray = WebDAVUtil.getPathArray(destination, true);

      long companyId = webDavRequest.getCompanyId();

      long parentFolderId = IGFolderConstants.DEFAULT_PARENT_FOLDER_ID;

      try {
        parentFolderId = getParentFolderId(companyId, destinationArray);
      } catch (NoSuchFolderException nsfe) {
        return HttpServletResponse.SC_CONFLICT;
      }

      IGImage image = (IGImage) resource.getModel();

      long groupId = WebDAVUtil.getGroupId(companyId, destination);
      String name = WebDAVUtil.getResourceName(destinationArray);
      String description = image.getDescription();
      String contentType = MimeTypesUtil.getContentType(image.getNameWithExtension());

      file = FileUtil.createTempFile(image.getImageType());

      InputStream is = resource.getContentAsStream();

      FileUtil.write(file, is);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddCommunityPermissions(isAddCommunityPermissions(groupId));
      serviceContext.setAddGuestPermissions(true);

      int status = HttpServletResponse.SC_CREATED;

      if (overwrite) {
        if (deleteResource(groupId, parentFolderId, name)) {
          status = HttpServletResponse.SC_NO_CONTENT;
        }
      }

      IGImageServiceUtil.addImage(
          groupId, parentFolderId, name, description, file, contentType, serviceContext);

      return status;
    } catch (DuplicateFolderNameException dfne) {
      return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (DuplicateFileException dfe) {
      return HttpServletResponse.SC_PRECONDITION_FAILED;
    } catch (PrincipalException pe) {
      return HttpServletResponse.SC_FORBIDDEN;
    } catch (Exception e) {
      throw new WebDAVException(e);
    } finally {
      if (file != null) {
        file.delete();
      }
    }
  }
  protected int doProcess(WebDAVRequest webDAVRequest) throws Exception {
    WebDAVStorage storage = webDAVRequest.getWebDAVStorage();

    if (!storage.isSupportsClassTwo()) {
      return HttpServletResponse.SC_METHOD_NOT_ALLOWED;
    }

    HttpServletRequest request = webDAVRequest.getHttpServletRequest();
    HttpServletResponse response = webDAVRequest.getHttpServletResponse();

    Lock lock = null;
    Status status = null;

    String lockUuid = webDAVRequest.getLockUuid();
    long timeout = WebDAVUtil.getTimeout(request);

    if (Validator.isNull(lockUuid)) {

      // Create new lock

      String owner = null;
      String xml = new String(FileUtil.getBytes(request.getInputStream()));

      if (Validator.isNotNull(xml)) {
        if (_log.isDebugEnabled()) {
          _log.debug("Request XML\n" + XMLFormatter.toString(xml));
        }

        Document document = SAXReaderUtil.read(xml);

        Element rootElement = document.getRootElement();

        boolean exclusive = false;

        Element lockscopeElement = rootElement.element("lockscope");

        for (Element element : lockscopeElement.elements()) {
          String name = GetterUtil.getString(element.getName());

          if (name.equals("exclusive")) {
            exclusive = true;
          }
        }

        if (!exclusive) {
          return HttpServletResponse.SC_BAD_REQUEST;
        }

        Element ownerElement = rootElement.element("owner");

        owner = ownerElement.getTextTrim();

        if (Validator.isNull(owner)) {
          List<Element> hrefElements = ownerElement.elements("href");

          for (Element hrefElement : hrefElements) {
            owner = "<D:href>" + hrefElement.getTextTrim() + "</D:href>";
          }
        }
      } else {
        _log.error("Empty request XML");

        return HttpServletResponse.SC_PRECONDITION_FAILED;
      }

      status = storage.lockResource(webDAVRequest, owner, timeout);

      lock = (Lock) status.getObject();
    } else {
      try {

        // Refresh existing lock

        lock = storage.refreshResourceLock(webDAVRequest, lockUuid, timeout);

        status = new Status(HttpServletResponse.SC_OK);
      } catch (WebDAVException wde) {
        if (wde.getCause() instanceof NoSuchLockException) {
          return HttpServletResponse.SC_PRECONDITION_FAILED;
        } else {
          throw wde;
        }
      }
    }

    // Return lock details

    if (lock == null) {
      return status.getCode();
    }

    long depth = WebDAVUtil.getDepth(request);

    String xml = getResponseXML(lock, depth);

    if (_log.isDebugEnabled()) {
      _log.debug("Response XML\n" + xml);
    }

    String lockToken = "<" + WebDAVUtil.TOKEN_PREFIX + lock.getUuid() + ">";

    response.setContentType(ContentTypes.TEXT_XML_UTF8);
    response.setHeader("Lock-Token", lockToken);
    response.setStatus(status.getCode());

    if (_log.isDebugEnabled()) {
      _log.debug("Returning lock token " + lockToken);
    }

    try {
      ServletResponseUtil.write(response, xml);
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e);
      }
    }

    return status.getCode();
  }