Webdav Report method implementation.

@param session current session
@param path resource path
@param body request bidy
@param depth report depth
@param baseURI base Uri
@return the instance of javax.ws.rs.core.Response
962203
public Response report(Session session, String path, HierarchicalProperty body, Depth depth, String baseURI)
   {
      try
      {
         Node node = (Node)session.getItem(path);
         WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session);
         String strUri = baseURI + node.getPath();
         URI uri = new URI(TextUtil.escape(strUri, '%', true));

         if (!ResourceUtil.isVersioned(node))
         {
            return Response.status(HTTPStatus.PRECON_FAILED).build();
         }

         VersionedResource resource;
         if (ResourceUtil.isFile(node))
         {
            resource = new VersionedFileResource(uri, node, nsContext);
         }
         else
         {
            resource = new VersionedCollectionResource(uri, node, nsContext);
         }

         Set<QName> properties = getProperties(body);

         VersionTreeResponseEntity response = new VersionTreeResponseEntity(nsContext, resource, properties);

         return Response.status(HTTPStatus.MULTISTATUS).entity(response).build();

      }
      catch (PathNotFoundException exc)
      {
         return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build();
      }
      catch (RepositoryException exc)
      {
         LOG.error(exc.getMessage(), exc);
         return Response.serverError().entity(exc.getMessage()).build();
      }
      catch (Exception exc)
      {
         LOG.error(exc.getMessage(), exc);
         return Response.serverError().entity(exc.getMessage()).build();
      }
   }
833272
@GET
    @Timed
    public Response getPartitions(@Context final UriInfo uriInfo, @Context final HttpHeaders headers) {

        final IRI identifier = rdf.createIRI(
                properties.getProperty("baseUrl", uriInfo.getBaseUri().toString()));

        LOGGER.debug("Request for root resource at: {}", identifier.getIRIString());

        final List<Triple> graph = new ArrayList<>();
        partitions.entrySet().stream().map(e -> rdf.createIRI(e.getValue() + e.getKey()))
            .map(obj -> rdf.createTriple(identifier, LDP.contains, obj)).forEach(graph::add);

        properties.stringPropertyNames().stream().filter(propMapping::containsKey)
            .map(name -> rdf.createTriple(identifier, propMapping.get(name), isUrl(properties.getProperty(name)) ?
                        rdf.createIRI(properties.getProperty(name)) :
                        rdf.createLiteral(properties.getProperty(name))))
            .forEach(graph::add);

        final RDFSyntax syntax = getSyntax(headers.getAcceptableMediaTypes(), empty())
            .orElseThrow(NotAcceptableException::new);

        final IRI profile = ofNullable(getProfile(headers.getAcceptableMediaTypes(), syntax))
            .orElseGet(() -> getDefaultProfile(syntax, identifier));

        final StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(final OutputStream out) throws IOException {
                ioService.write(graph.stream(), out, syntax, profile);
            }
        };

        return ok().header(ALLOW, join(",", HttpMethod.GET, HEAD, OPTIONS))
                    .link(LDP.Resource.getIRIString(), "type")
                    .link(LDP.RDFSource.getIRIString(), "type")
                    .type(syntax.mediaType).entity(stream).build();
    }
239702
public static URI appendUri(URI baseUri, String... pathComponents) {
        StringBuilder builder = new StringBuilder(baseUri.toASCIIString());
        for (String path : pathComponents) {
            if (path != null && path.length() > 0) {
                path = normalizePath(path);
                if (path.startsWith("/")) {
                    if (builder.charAt(builder.length() - 1) == '/') {
                        builder.setLength(builder.length() - 1);
                    }
                } else {
                    if (builder.charAt(builder.length() - 1) != '/') {
                        builder.append('/');
                    }
                }
                builder.append(path);
            }
        }
        try {
            return new URI(builder.toString());
        } catch (URISyntaxException e) {
            throw new RuntimeException("Unexpected error", e);
        }
    }
1257846
@GET
  @Path(WEBUI_OVERVIEW)
  @ReturnType("alluxio.wire.WorkerWebUIOverview")
  public Response getWebUIOverview() {
    return RestUtils.call(() -> {
      WorkerWebUIOverview response = new WorkerWebUIOverview();

      response.setWorkerInfo(new UIWorkerInfo(mWorkerProcess.getRpcAddress().toString(),
          mWorkerProcess.getStartTimeMs(),
          ServerConfiguration.get(PropertyKey.USER_DATE_FORMAT_PATTERN)));

      BlockStoreMeta storeMeta = mBlockWorker.getStoreMeta();
      long capacityBytes = 0L;
      long usedBytes = 0L;
      Map<String, Long> capacityBytesOnTiers = storeMeta.getCapacityBytesOnTiers();
      Map<String, Long> usedBytesOnTiers = storeMeta.getUsedBytesOnTiers();
      List<UIUsageOnTier> usageOnTiers = new ArrayList<>();
      for (Map.Entry<String, Long> entry : capacityBytesOnTiers.entrySet()) {
        String tier = entry.getKey();
        long capacity = entry.getValue();
        Long nullableUsed = usedBytesOnTiers.get(tier);
        long used = nullableUsed == null ? 0 : nullableUsed;

        capacityBytes += capacity;
        usedBytes += used;

        usageOnTiers.add(new UIUsageOnTier(tier, capacity, used));
      }

      response.setCapacityBytes(FormatUtils.getSizeFromBytes(capacityBytes))
          .setUsedBytes(FormatUtils.getSizeFromBytes(usedBytes)).setUsageOnTiers(usageOnTiers)
          .setVersion(RuntimeConstants.VERSION);

      List<UIStorageDir> storageDirs = new ArrayList<>(storeMeta.getCapacityBytesOnDirs().size());
      for (Pair<String, String> tierAndDirPath : storeMeta.getCapacityBytesOnDirs().keySet()) {
        storageDirs.add(new UIStorageDir(tierAndDirPath.getFirst(), tierAndDirPath.getSecond(),
            storeMeta.getCapacityBytesOnDirs().get(tierAndDirPath),
            storeMeta.getUsedBytesOnDirs().get(tierAndDirPath)));
      }

      response.setStorageDirs(storageDirs);

      return response;
    }, ServerConfiguration.global());
  }
1318430
@RequestMapping(
            headers = {"org.apereo.portal.url.UrlType=ACTION"},
            method = RequestMethod.POST)
    public void actionRequest(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        final IPortalRequestInfo portalRequestInfo =
                this.urlSyntaxProvider.getPortalRequestInfo(request);
        final IPortletRequestInfo portletRequestInfo =
                portalRequestInfo.getTargetedPortletRequestInfo();

        final IPortalUrlBuilder actionRedirectUrl;
        if (portletRequestInfo != null) {
            final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId();
            actionRedirectUrl =
                    this.portalUrlProvider.getPortalUrlBuilderByPortletWindow(
                            request, targetWindowId, UrlType.RENDER);
        } else {
            final String targetedLayoutNodeId = portalRequestInfo.getTargetedLayoutNodeId();

            if (targetedLayoutNodeId != null) {
                actionRedirectUrl =
                        this.portalUrlProvider.getPortalUrlBuilderByLayoutNode(
                                request, targetedLayoutNodeId, UrlType.RENDER);
            } else {
                actionRedirectUrl = this.portalUrlProvider.getDefaultUrl(request);
            }
        }

        // Stuff the action-redirect URL builder into the request so other code can use it during
        // request processing
        this.portalUrlProvider.convertToPortalActionUrlBuilder(request, actionRedirectUrl);

        if (portletRequestInfo != null) {
            final IPortletWindowId targetWindowId = portletRequestInfo.getPortletWindowId();

            try {
                this.portletExecutionManager.doPortletAction(targetWindowId, request, response);
            } catch (RuntimeException e) {
                this.logger.error(
                        "Exception thrown while executing portlet action for: "
                                + portletRequestInfo,
                        e);

                // TODO this should be a constant right?
                actionRedirectUrl.setParameter("portletActionError", targetWindowId.toString());
            }
        }

        sendRedirect(actionRedirectUrl, response);
    }
1159335
private String getReportURL(String projectUrl,String path,String projectId) {
        StringBuilder sb = new StringBuilder(projectUrl);
        if(!projectUrl.endsWith("/")) {
            sb.append("/");
        }
        sb.append(path)
                .append(projectId);
        return sb.toString();
    }
369704
public static String doPost(String host, String path,
                                Map<String, String> headers,
                                Map<String, String> queries,
                                String body) throws Exception {
        return EntityUtils.toString(doPostResponse(host, path, headers, queries, body).getEntity(), "utf-8");
    }
861187
@Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String path = getRelativePath(req);

        // Check if webdav is set to read only
        if (m_readOnly) {

            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
            }

            return;
        }

        // Check if resource is locked
        if (isLocked(req)) {

            resp.setStatus(CmsWebdavStatus.SC_LOCKED);

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
            }

            return;
        }

        boolean exists = m_session.exists(path);
        boolean result = true;

        // Temp. content file used to support partial PUT
        File contentFile = null;

        CmsWebdavRange range = parseContentRange(req, resp);

        InputStream resourceInputStream = null;

        // Append data specified in ranges to existing content for this
        // resource - create a temp. file on the local filesystem to
        // perform this operation
        // Assume just one range is specified for now
        if (range != null) {
            contentFile = executePartialPut(req, range, path);
            resourceInputStream = new FileInputStream(contentFile);
        } else {
            resourceInputStream = req.getInputStream();
        }

        try {

            // FIXME: Add attributes(from Apache Tomcat)
            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_ITEM_0));
            }

            m_session.save(path, resourceInputStream, exists);
        } catch (Exception e) {

            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_REPOSITORY_ERROR_2, "PUT", path), e);
            }

            result = false;
            resp.setStatus(HttpServletResponse.SC_CONFLICT);
        }

        // Bugzilla 40326: at this point content file should be safe to delete
        // as it's no longer referenced.  Let's not rely on deleteOnExit because
        // it's a memory leak, as noted in this Bugzilla issue.
        if (contentFile != null) {
            try {
                contentFile.delete();
            } catch (Exception e) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(Messages.get().getBundle().key(Messages.LOG_DELETE_TEMP_FILE_0), e);
                }
            }
        }

        if (result) {

            if (LOG.isDebugEnabled()) {
                LOG.debug(Messages.get().getBundle().key(Messages.LOG_SAVE_SUCCESS_0));
            }

            if (exists) {
                resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            } else {
                resp.setStatus(HttpServletResponse.SC_CREATED);
            }
        }
    }
258275
public static Node getClosestExistingAncestor(final Session session, final String path)
            throws RepositoryException {

        String potentialPath = path.startsWith("/") ? path : "/" + path;
        while (!potentialPath.isEmpty()) {
            if (session.nodeExists(potentialPath)) {
                return session.getNode(potentialPath);
            }
            potentialPath = potentialPath.substring(0, potentialPath.lastIndexOf('/'));
        }
        return session.getRootNode();
    }
550320
@Override
    public HttpSession generateNewId(HttpServletRequest request, HttpServletResponse response, HttpSession existingSession) {
        SessionAffinityContext sac = getSessionAffinityContext(request);
        HttpSession session = (HttpSession) _coreHttpSessionManager.generateNewId(request, response, sac, ((SessionData) existingSession).getISession());
        return session;
    }
1192485
public void doBrowse(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException
    {
        if (!common.checkGet(request, response)) return;
        User user = common.getLoggedInUser(request);
        if (user == null) {
            common.pageSoftError(response, "Can't do /browse.  Nobody is logged in.");
            return;
        }

        DbxClientV2 dbxClient = requireDbxClient(request, response, user);
        if (dbxClient == null) return;

        String path = request.getParameter("path");
        if (path == null || path.length() == 0) {
            renderFolder(response, user, dbxClient, "");
        } else {
            String pathError = DbxPathV2.findError(path);
            if (pathError != null) {
                response.sendError(400, "Invalid path: " + jq(path) + ": " + pathError);
                return;
            }
            Metadata metadata;
            try {
                metadata = dbxClient.files()
                    .getMetadata(path);
            }
            catch (GetMetadataErrorException ex) {
                if (ex.errorValue.isPath()) {
                    LookupError le = ex.errorValue.getPathValue();
                    if (le.isNotFound()) {
                        response.sendError(400, "Path doesn't exist on Dropbox: " + jq(path));
                        return;
                    }
                }
                common.handleException(response, ex, "getMetadata(" + jq(path) + ")");
                return;
            }
            catch (DbxException ex) {
                common.handleDbxException(response, user, ex, "getMetadata(" + jq(path) + ")");
                return;
            }

            path = DbxPathV2.getParent(path) + "/" + metadata.getName();
            if (metadata instanceof FolderMetadata) {
                renderFolder(response, user, dbxClient, path);
            }
            else {
                renderFile(response, path, (FileMetadata) metadata);
            }
        }
    }
500823
private JcrSession openSession() throws ResourceException {
        try {
            Repository repo = mcf.getRepository();
            Session s = repo.login(cri.getCredentials(), cri.getWorkspace());
            return (JcrSession) s;
        } catch (RepositoryException e) {
            throw new ResourceException("Failed to create session: " + e.getMessage(), e);
        }
    }
1162028
protected void sendReport( final WebdavRequest req, final WebdavResponse resp, final Hashtable<String, WebdavStatus> errorList )
        throws IOException
    {

        resp.setStatus( WebdavStatus.SC_MULTI_STATUS );

        final String absoluteUri = req.getRequestURI();
        // String relativePath = getRelativePath(req);

        final HashMap<String, String> namespaces = new HashMap<String, String>();
        namespaces.put( "DAV:", "D" );

        final XMLWriter generatedXML = new XMLWriter( namespaces );
        generatedXML.writeXMLHeader();

        generatedXML.writeElement( "DAV::multistatus", XMLWriter.OPENING );

        final Enumeration<String> pathList = errorList.keys();
        while ( pathList.hasMoreElements() )
        {

            final String errorPath = pathList.nextElement();
            final int errorCode = errorList.get( errorPath )
                                           .code();

            generatedXML.writeElement( "DAV::response", XMLWriter.OPENING );

            generatedXML.writeElement( "DAV::href", XMLWriter.OPENING );
            String toAppend = null;
            if ( absoluteUri.endsWith( errorPath ) )
            {
                toAppend = absoluteUri;

            }
            else if ( absoluteUri.contains( errorPath ) )
            {

                final int endIndex = absoluteUri.indexOf( errorPath ) + errorPath.length();
                toAppend = absoluteUri.substring( 0, endIndex );
            }
            if ( !toAppend.startsWith( "/" ) && !toAppend.startsWith( "http:" ) )
            {
                toAppend = "/" + toAppend;
            }
            generatedXML.writeText( errorPath );
            generatedXML.writeElement( "DAV::href", XMLWriter.CLOSING );
            generatedXML.writeElement( "DAV::status", XMLWriter.OPENING );
            generatedXML.writeText( "HTTP/1.1 " + errorCode + " " + WebdavStatus.getStatusText( errorCode ) );
            generatedXML.writeElement( "DAV::status", XMLWriter.CLOSING );

            generatedXML.writeElement( "DAV::response", XMLWriter.CLOSING );

        }

        generatedXML.writeElement( "DAV::multistatus", XMLWriter.CLOSING );

        final Writer writer = resp.getWriter();
        writer.write( generatedXML.toString() );
        writer.close();

    }
671443
public ArmeriaRetrofitBuilder baseUrl(String baseUrl) {
        requireNonNull(baseUrl, "baseUrl");
        final URI uri = URI.create(baseUrl);
        checkArgument(SessionProtocol.find(uri.getScheme()).isPresent(),
                      "baseUrl must have an HTTP scheme: %s", baseUrl);
        final String path = uri.getPath();
        if (!path.isEmpty() && !SLASH.equals(path.substring(path.length() - 1))) {
            throw new IllegalArgumentException("baseUrl must end with /: " + baseUrl);
        }
        this.baseUrl = baseUrl;
        return this;
    }
210603
private static String getServerResponse(String protocol,
                                            String user,
                                            String pass,
                                            String path) throws IOException {
        String url = getBaseURL(protocol) + path;
        logger.info("Getting URL: {}", url);
        UsernamePasswordCredentials creds =
                new UsernamePasswordCredentials(user, pass);
        return s_webClient.getResponseAsString(url, true, creds);
    }
533535
public void setEntityBaseUrl(final URL base) {
        reader.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(final String publicId, final String systemId) throws IOException {
                return new InputSource(new URL(base, systemId).openStream());
            }
        });
    }
574893
public Response.ResponseBuilder getTimeMapBuilder(final LdpRequest req,
            final IOService serializer, final String baseUrl) {

        final List<MediaType> acceptableTypes = req.getHeaders().getAcceptableMediaTypes();
        final String identifier = getBaseUrl(baseUrl, req) + req.getPartition() + req.getPath();
        final List<Link> links = getMementoLinks(identifier, resource.getMementos()).collect(toList());

        final Response.ResponseBuilder builder = Response.ok().link(identifier, ORIGINAL + " " + TIMEGATE);
        builder.links(links.toArray(new Link[0])).link(Resource.getIRIString(), "type")
            .link(RDFSource.getIRIString(), "type").header(ALLOW, join(",", GET, HEAD, OPTIONS));

        final RDFSyntax syntax = getSyntax(acceptableTypes, of(APPLICATION_LINK_FORMAT)).orElse(null);
        if (nonNull(syntax)) {
            final IRI profile = ofNullable(getProfile(acceptableTypes, syntax)).orElse(expanded);

            final List<Triple> extraData = getExtraTriples(identifier);
            for (final Link l : links) {
                if (l.getRels().contains(MEMENTO)) {
                    extraData.add(rdf.createTriple(rdf.createIRI(identifier), Memento.memento,
                                    rdf.createIRI(l.getUri().toString())));
                }
            }

            final StreamingOutput stream = new StreamingOutput() {
                @Override
                public void write(final OutputStream out) throws IOException {
                    serializer.write(concat(links.stream().flatMap(linkToTriples), extraData.stream()), out, syntax,
                            profile);
                }
            };

            return builder.type(syntax.mediaType).entity(stream);
        }

        return builder.type(APPLICATION_LINK_FORMAT)
            .entity(links.stream().map(Link::toString).collect(joining(",\n")) + "\n");
    }