Example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

List of usage examples for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Prototype

int SC_METHOD_NOT_ALLOWED

To view the source code for javax.servlet.http HttpServletResponse SC_METHOD_NOT_ALLOWED.

Click Source Link

Document

Status code (405) indicating that the method specified in the Request-Line is not allowed for the resource identified by the Request-URI.

Usage

From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    boolean running_state = CMS.isInRunningState();

    if (!running_state)
        throw new IOException("CMS server is not ready to serve.");

    HttpServletRequest req = request;//from   w  w w  . j a  v a2 s  .  c o  m
    HttpServletResponse resp = response;

    CMSRequest cmsRequest = newCMSRequest();

    // set argblock
    cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request)));

    // set http request
    cmsRequest.setHttpReq(request);

    // set http response
    cmsRequest.setHttpResp(response);

    // set servlet config.
    cmsRequest.setServletConfig(mConfig);

    // set servlet context.
    cmsRequest.setServletContext(mConfig.getServletContext());

    char[] content = null;
    String encodedreq = null;
    String method = null;
    int len = -1;
    IPKIMessage msg = null;
    IPKIMessage replymsg = null;

    // NOTE must read all bufer before redoing handshake for
    // ssl client auth for client auth to work.

    // get request method
    method = req.getMethod();

    // get content length
    len = request.getContentLength();

    // get content, a base 64 encoded serialized request.
    if (len > 0) {
        InputStream in = request.getInputStream();
        InputStreamReader inreader = new InputStreamReader(in, "UTF8");
        BufferedReader reader = new BufferedReader(inreader, len);

        content = new char[len];
        int done = reader.read(content, 0, len);
        int total = done;

        while (done >= 0 && total < len) {
            done = reader.read(content, total, len - total);
            total += done;
        }
        reader.close();
        encodedreq = new String(content);
    }

    // force client auth handshake, validate RA and get RA's Id.
    // NOTE must do this after all contents are read for ssl
    // redohandshake to work

    X509Certificate peerCert;

    try {
        peerCert = getPeerCert(req);
    } catch (EBaseException e) {
        mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT"));
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    if (peerCert == null) {
        // XXX log something here.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // authenticate RA

    String RA_Id = null;
    String raUserId = null;
    IAuthToken token = null;

    try {
        token = authenticate(request);
        raUserId = token.getInString("userid");
        RA_Id = peerCert.getSubjectDN().toString();
    } catch (EInvalidCredentials e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } catch (EBaseException e) {
        // already logged.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN());

    // authorize
    AuthzToken authzToken = null;

    try {
        authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit");
    } catch (Exception e) {
        // do nothing for now
    }

    if (authzToken == null) {
        cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED);
        return;
    }

    // after cert validated, check http request.
    if (!method.equalsIgnoreCase("POST")) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }
    if (len <= 0) {
        resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED);
        return;
    }

    // now process request.

    CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id);
    try {
        // decode request.
        msg = (IPKIMessage) mReqEncoder.decode(encodedreq);
        // process request
        replymsg = processRequest(RA_Id, raUserId, msg, token);
    } catch (IOException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (EBaseException e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
        mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString()));
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: service " + e.toString());
        CMS.debug(e);
    }

    CMS.debug("ConnectorServlet: done processRequest");

    // encode reply
    try {
        String encodedrep = mReqEncoder.encode(replymsg);

        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("text/html");
        resp.setContentLength(encodedrep.length());

        // send reply
        OutputStream out = response.getOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8");

        writer.write(encodedrep);
        writer.flush();
        writer.close();
        out.flush();
    } catch (Exception e) {
        CMS.debug("ConnectorServlet: error writing e=" + e.toString());
    }
    CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id);
}

From source file:org.gss_project.gss.server.rest.RequestHandler.java

@Override
protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    boolean authDeferred = getAuthDeferred(req);
    // Strip the username part
    String path;//  ww  w. jav  a2  s.  c o m
    try {
        path = getUserPath(req);
    } catch (ObjectNotFoundException e) {
        if (authDeferred) {
            // We do not want to leak information if the request
            // was not authenticated.
            resp.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        return;
    }
    if (authDeferred && !path.startsWith(PATH_FILES)) {
        // Only files may be open to the public.
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (path.startsWith(PATH_GROUPS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_GROUPS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_OTHERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_OTHERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SEARCH)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SEARCH));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TOKEN)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TOKEN));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_USERS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_USERS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_SHARED)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_SHARED));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TAGS)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TAGS));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_TRASH)) {
        resp.addHeader("Allow", methodsAllowed.get(PATH_TRASH));
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } else if (path.startsWith(PATH_FILES))
        // Serve the requested resource, without the data content
        new FilesHandler(getServletContext()).serveResource(req, resp, false);
    else
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, req.getRequestURI());
}

From source file:org.appcelerator.transport.UploadTransportServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getMethod().equalsIgnoreCase("POST")) {
        // paranoia check -we don't accept urlencoded transfers which are very bad performance wise
        if (false == ServletFileUpload.isMultipartContent(request)) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "must be 'multipart/form-data'");
            return;
        }//from   w w w.j av  a 2s.c  o m

        String type = null;
        String callback = null;
        long size = 0L;
        // String instanceid = null;
        IMessageDataObject data = MessageUtils.createMessageDataObject();

        try {
            ServletFileUpload upload = new ServletFileUpload(fileFactory);
            List items = upload.parseRequest(request);
            for (Iterator i = items.iterator(); i.hasNext();) {
                FileItem item = (FileItem) i.next();
                if (item.isFormField()) {
                    if (item.getFieldName().equals("callback")) {
                        callback = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("type")) {
                        type = item.getString();
                        continue;
                    } else if (item.getFieldName().equals("instanceid")) {
                        //instanceid = item.getString();
                        continue;
                    }
                    // place it in the data payload
                    data.put(item.getFieldName(), item.getString());
                } else {
                    File f = null;
                    if (tempDirectory != null) {
                        f = File.createTempFile("sup", ".tmp", tempDirectory);
                    } else {
                        f = File.createTempFile("sup", ".tmp");
                    }

                    f.deleteOnExit();

                    // write out the temporary file
                    item.write(f);

                    size = item.getSize();

                    IMessageDataObject filedata = MessageUtils.createMessageDataObject();

                    filedata.put("file", f.getAbsolutePath());
                    filedata.put("size", size);
                    filedata.put("contentType", item.getContentType());
                    filedata.put("fieldName", item.getFieldName());
                    filedata.put("fileName", item.getName());

                    data.put("filedata", filedata);
                }
            }

            // required parameter type
            if (type == null || type.equals("")) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "missing 'type' parameter");
                return;
            }
        } catch (Throwable fe) {
            fe.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fe.getMessage());
            return;
        }

        String scope = request.getParameter("scope");
        String version = request.getParameter("version");

        if (scope == null) {
            scope = "appcelerator";
        }
        if (version == null) {
            version = "1.0";
        }

        // create a message
        Message msg = new Message();
        msg.setUser(request.getUserPrincipal());
        msg.setSession(request.getSession());
        msg.setServletRequest(request);
        msg.setType(type);
        msg.setData(data);
        msg.setAddress(InetAddress.getByName(request.getRemoteAddr()));
        msg.setScope(scope);
        msg.setVersion(version);

        // send the data
        ArrayList<Message> responses = new ArrayList<Message>();
        try {
            ServiceRegistry.dispatch(msg, responses);
        } catch (Exception ex) {
            LOG.error("error dispatching upload message: " + msg, ex);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
        response.setDateHeader("Expires", System.currentTimeMillis() - TimeUtil.ONE_YEAR);
        response.setContentType("text/html;charset=UTF-8");

        // optionally, invoke a callback function/message on upload in the client
        if (callback != null || !responses.isEmpty()) {
            StringBuilder code = new StringBuilder();
            code.append("<html><head><script>");

            if (callback != null) {
                if (callback.startsWith("l:") || callback.startsWith("local:") || callback.startsWith("r:")
                        || callback.startsWith("remote:")) {
                    code.append(makeMessage(callback, "{size:" + size + "}", scope, version));
                } else {
                    // a javascript function to call
                    code.append("window.parent.").append(callback).append("();");
                }
            }

            for (Message m : responses) {
                code.append(makeMessage(m.getType(), m.getData().toDataString(), m.getScope(), m.getVersion()));
            }

            code.append("</script></head><body></body></html>");

            // send the response
            response.setStatus(HttpServletResponse.SC_OK);
            response.getWriter().print(code.toString());
        } else {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        }
    } else {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "method was: " + request.getMethod());
    }
}

From source file:v7db.files.buckets.BucketsServletTest.java

public void testFormPostPOST() throws IOException, SAXException {

    ServletUnitClient sc = sr.newClient();
    {/*from   ww w  .  j  a  va2 s  . c  o  m*/
        PostMethodWebRequest request = new PostMethodWebRequest("http://test/myServlet/1");

        try {
            sc.getResponse(request);
            fail("bucket not found => 404");
        } catch (HttpNotFoundException e) {
            assertEquals("Bucket '1' not found", e.getResponseMessage());
        }

    }

    prepareBucket("1", "FormPost", null, null);
    {
        PostMethodWebRequest request = new PostMethodWebRequest("http://test/myServlet/1");

        try {
            sc.getResponse(request);
            fail("uploads not allowed => 405");
        } catch (HttpException e) {
            assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getResponseCode());
        }
    }
    //
    // TODO: an actual POST, see
    // http://stackoverflow.com/questions/10891247/file-upload-post-request-with-servletunit

}

From source file:com.basetechnology.s0.agentserver.appserver.AgentAppServer.java

public void startJetty() throws Exception {
    if (server != null) {
        String jettyState = server.getState();
        if (jettyState.equalsIgnoreCase("STARTED"))
            return;
    }/*from w  w w .j  a  v a  2  s. co m*/

    Handler handler = new AbstractHandler() {
        public void handle(String target, Request request, HttpServletRequest servletRequest,
                HttpServletResponse response) throws IOException, ServletException {
            // Gather all the request info in one place
            HttpInfo httpInfo = new HttpInfo(target, request, servletRequest, response, null, null, "json",
                    agentServer);

            // Handle major exceptions in a common manner at the outer level
            try {
                // Get path from URL
                String path = request.getPathInfo();

                // Determine output format
                String format = "json";
                if (path.endsWith(".json")) {
                    format = "json";
                    path = path.substring(0, path.length() - 5);
                } else if (path.endsWith(".csv")) {
                    format = "csv";
                    path = path.substring(0, path.length() - 4);
                } else if (path.endsWith(".tab")) {
                    format = "tab";
                    path = path.substring(0, path.length() - 4);
                } else if (path.endsWith(".xml")) {
                    format = "xml";
                    path = path.substring(0, path.length() - 4);
                } else if (path.endsWith(".rss")) {
                    format = "rss";
                    path = path.substring(0, path.length() - 4);
                } else if (path.endsWith(".html")) {
                    format = "html";
                    path = path.substring(0, path.length() - 5);
                } else if (path.endsWith(".txt")) {
                    format = "text";
                    path = path.substring(0, path.length() - 4);
                } else if (path.endsWith(".text")) {
                    format = "text";
                    path = path.substring(0, path.length() - 5);
                } else {
                    String formatParameter = request.getParameter("format");
                    if (formatParameter != null) {
                        if (formatParameter.equalsIgnoreCase("json"))
                            format = "json";
                        else if (formatParameter.equalsIgnoreCase("xml"))
                            format = "xml";
                        else if (formatParameter.equalsIgnoreCase("rss"))
                            format = "rss";
                        else if (formatParameter.equalsIgnoreCase("html"))
                            format = "html";
                        else if (formatParameter.equalsIgnoreCase("txt")
                                || formatParameter.equalsIgnoreCase("text"))
                            format = "text";
                        else if (formatParameter.equalsIgnoreCase("csv"))
                            format = "csv";
                        else if (formatParameter.equalsIgnoreCase("tab"))
                            format = "tab";
                        else
                            throw new AgentAppServerBadRequestException(
                                    "Unsupported format type query parameter (only json, xml, html, rss, text, txt, csv, and tab supported): "
                                            + formatParameter);
                    }
                }
                httpInfo.format = format;

                // Make sure path is an API path that we handle
                if (!path.startsWith(apiPathPrefix))
                    throw new AgentAppServerBadRequestException(
                            "Unsupported API path prefix (needs to be '" + apiPathPrefix + "')");

                // Strip the API version from the path
                path = path.substring(apiPathPrefix.length());
                httpInfo.path = path;

                // Get common info
                String method = request.getMethod();
                String[] pathParts = path.split("/");
                httpInfo.pathParts = pathParts;
                int numPathParts = pathParts.length;
                log.info("Request method: " + method + " path: " + path + " numPathParts: " + numPathParts);

                // Determine which HTTP method is being invoked
                boolean handled = false;
                if (method.equalsIgnoreCase("GET")) {
                    handled = new HandleGet(httpInfo).handleGet();
                } else if (method.equalsIgnoreCase("POST")) {
                    handled = new HandlePost(httpInfo).handlePost();
                } else if (method.equalsIgnoreCase("PUT")) {
                    handled = new HandlePut(httpInfo).handlePut();
                } else if (method.equalsIgnoreCase("DELETE")) {
                    handled = new HandleDelete(httpInfo).handleDelete();
                } else {
                    throw new AgentAppServerException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                            "The " + method + " is not supported by the agent server");
                }

                // I'm not really sure when/why this might be false
                // But maybe because this handler expects to process all paths and give an error page
                // if the path is not supported by the agent server
                ((Request) request).setHandled(handled);
            } catch (AgentAppServerBadRequestException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (AgentAppServerException e) {
                handleException(httpInfo, e.statusCode, e);
            } catch (AgentServerException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (ParserException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (TokenizerException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (JSONException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (InterruptedException e) {
                handleException(httpInfo, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            } catch (WebAccessException e) {
                handleException(httpInfo, HttpServletResponse.SC_BAD_REQUEST, e);
            } catch (ParseException e) {
                handleException(httpInfo, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            } catch (Exception e) {
                handleException(httpInfo, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            }
        }

    };

    server = new Server(appServerPort);
    server.setHandler(handler);

    String jettyState = server.getState();
    server.start();
    jettyState = server.getState();
}

From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java

@Override
public DavResource createResource(final DavResourceLocator locator, final DavServletRequest request,
        final DavServletResponse response) throws DavException {
    ArchivaDavResourceLocator archivaLocator = checkLocatorIsInstanceOfRepositoryLocator(locator);

    RepositoryGroupConfiguration repoGroupConfig = archivaConfiguration.getConfiguration()
            .getRepositoryGroupsAsMap().get(archivaLocator.getRepositoryId());

    String activePrincipal = getActivePrincipal(request);

    List<String> resourcesInAbsolutePath = new ArrayList<>();

    boolean readMethod = WebdavMethodUtil.isReadMethod(request.getMethod());
    DavResource resource;/*from  www .ja va 2s .co m*/
    if (repoGroupConfig != null) {
        if (!readMethod) {
            throw new DavException(HttpServletResponse.SC_METHOD_NOT_ALLOWED,
                    "Write method not allowed for repository groups.");
        }

        log.debug("Repository group '{}' accessed by '{}", repoGroupConfig.getId(), activePrincipal);

        // handle browse requests for virtual repos
        if (getLogicalResource(archivaLocator, null, true).endsWith("/")) {
            try {
                DavResource davResource = getResourceFromGroup(request, repoGroupConfig.getRepositories(),
                        archivaLocator, repoGroupConfig);

                setHeaders(response, locator, davResource, true);

                return davResource;

            } catch (RepositoryAdminException e) {
                throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
            }
        } else {
            // make a copy to avoid potential concurrent modifications (eg. by configuration)
            // TODO: ultimately, locking might be more efficient than copying in this fashion since updates are
            //  infrequent
            List<String> repositories = new ArrayList<>(repoGroupConfig.getRepositories());
            resource = processRepositoryGroup(request, archivaLocator, repositories, activePrincipal,
                    resourcesInAbsolutePath, repoGroupConfig);
        }
    } else {

        try {
            RemoteRepository remoteRepository = remoteRepositoryAdmin
                    .getRemoteRepository(archivaLocator.getRepositoryId());

            if (remoteRepository != null) {
                String logicalResource = getLogicalResource(archivaLocator, null, false);
                IndexingContext indexingContext = remoteRepositoryAdmin.createIndexContext(remoteRepository);
                File resourceFile = StringUtils.equals(logicalResource, "/")
                        ? new File(indexingContext.getIndexDirectoryFile().getParent())
                        : new File(indexingContext.getIndexDirectoryFile().getParent(), logicalResource);
                resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), //
                        locator.getResourcePath(), //
                        null, //
                        request.getRemoteAddr(), //
                        activePrincipal, //
                        request.getDavSession(), //
                        archivaLocator, //
                        this, //
                        mimeTypes, //
                        auditListeners, //
                        scheduler, //
                        fileLockManager);
                setHeaders(response, locator, resource, false);
                return resource;
            }
        } catch (RepositoryAdminException e) {
            log.debug("RepositoryException remote repository with d'{}' not found, msg: {}",
                    archivaLocator.getRepositoryId(), e.getMessage());
        }

        ManagedRepositoryContent managedRepositoryContent = null;

        try {
            managedRepositoryContent = repositoryFactory
                    .getManagedRepositoryContent(archivaLocator.getRepositoryId());
        } catch (RepositoryNotFoundException e) {
            throw new DavException(HttpServletResponse.SC_NOT_FOUND,
                    "Invalid repository: " + archivaLocator.getRepositoryId());
        } catch (RepositoryException e) {
            throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }

        log.debug("Managed repository '{}' accessed by '{}'", managedRepositoryContent.getId(),
                activePrincipal);

        try {
            resource = processRepository(request, archivaLocator, activePrincipal, managedRepositoryContent,
                    managedRepositoryAdmin.getManagedRepository(archivaLocator.getRepositoryId()));

            String logicalResource = getLogicalResource(archivaLocator, null, false);
            resourcesInAbsolutePath
                    .add(new File(managedRepositoryContent.getRepoRoot(), logicalResource).getAbsolutePath());

        } catch (RepositoryAdminException e) {
            throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        }
    }

    String requestedResource = request.getRequestURI();

    // MRM-872 : merge all available metadata
    // merge metadata only when requested via the repo group
    if ((repositoryRequest.isMetadata(requestedResource)
            || repositoryRequest.isMetadataSupportFile(requestedResource)) && repoGroupConfig != null) {
        // this should only be at the project level not version level!
        if (isProjectReference(requestedResource)) {

            ArchivaDavResource res = (ArchivaDavResource) resource;
            String filePath = StringUtils
                    .substringBeforeLast(res.getLocalResource().getAbsolutePath().replace('\\', '/'), "/");
            filePath = filePath + "/maven-metadata-" + repoGroupConfig.getId() + ".xml";

            // for MRM-872 handle checksums of the merged metadata files
            if (repositoryRequest.isSupportFile(requestedResource)) {
                File metadataChecksum = new File(
                        filePath + "." + StringUtils.substringAfterLast(requestedResource, "."));

                if (metadataChecksum.exists()) {
                    LogicalResource logicalResource = new LogicalResource(
                            getLogicalResource(archivaLocator, null, false));

                    resource = new ArchivaDavResource(metadataChecksum.getAbsolutePath(),
                            logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal,
                            request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler,
                            fileLockManager);
                }
            } else {
                if (resourcesInAbsolutePath != null && resourcesInAbsolutePath.size() > 1) {
                    // merge the metadata of all repos under group
                    ArchivaRepositoryMetadata mergedMetadata = new ArchivaRepositoryMetadata();
                    for (String resourceAbsPath : resourcesInAbsolutePath) {
                        try {
                            File metadataFile = new File(resourceAbsPath);
                            ArchivaRepositoryMetadata repoMetadata = MavenMetadataReader.read(metadataFile);
                            mergedMetadata = RepositoryMetadataMerge.merge(mergedMetadata, repoMetadata);
                        } catch (XMLException e) {
                            throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Error occurred while reading metadata file.");
                        } catch (RepositoryMetadataException r) {
                            throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                    "Error occurred while merging metadata file.");
                        }
                    }

                    try {
                        File resourceFile = writeMergedMetadataToFile(mergedMetadata, filePath);

                        LogicalResource logicalResource = new LogicalResource(
                                getLogicalResource(archivaLocator, null, false));

                        resource = new ArchivaDavResource(resourceFile.getAbsolutePath(),
                                logicalResource.getPath(), null, request.getRemoteAddr(), activePrincipal,
                                request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners,
                                scheduler, fileLockManager);
                    } catch (RepositoryMetadataException r) {
                        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Error occurred while writing metadata file.");
                    } catch (IOException ie) {
                        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Error occurred while generating checksum files.");
                    } catch (DigesterException de) {
                        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Error occurred while generating checksum files." + de.getMessage());
                    }
                }
            }
        }
    }

    setHeaders(response, locator, resource, false);

    // compatibility with MRM-440 to ensure browsing the repository works ok
    if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
        throw new BrowserRedirectException(resource.getHref());
    }
    resource.addLockManager(lockManager);
    return resource;
}

From source file:org.gss_project.gss.server.rest.GroupsHandler.java

/**
 * Handle POST requests in the groups namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//*w  w w  .  jav a 2 s . c o m*/
void postGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Identify the requested resource path
    String path = getInnerPath(req, PATH_GROUPS);
    if (path.equals(""))
        path = "/";

    try {
        User user = getUser(req);
        final User owner = getOwner(req);
        if (!owner.equals(user))
            throw new InsufficientPermissionsException("User " + user.getUsername()
                    + " does not have permission to modify the groups owned by " + owner.getUsername());
        if (path.equals("/")) {
            // Request to add group
            final String group = req.getParameter(GROUP_PARAMETER);
            if (!isValidResourceName(group)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            if (logger.isDebugEnabled())
                logger.debug("Adding group " + group);
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().createGroup(owner.getId(), group);
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        } else {
            // Request to add group member
            String username = req.getParameter(USERNAME_PARAMETER);
            if (!isValidResourceName(username)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            // Chop any trailing slash
            path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
            // Chop any leading slash
            path = path.startsWith("/") ? path.substring(1) : path;
            if (logger.isDebugEnabled())
                logger.debug("Adding member " + username + " to group " + path);
            final Group group = getService().getGroup(owner.getId(), URLDecoder.decode(path, "UTF-8"));
            final User member = getService().findUser(username);
            if (member == null) {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "User " + username + " not found");
                return;
            }
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().addUserToGroup(owner.getId(), group.getId(), member.getId());
                    return null;
                }
            });
            resp.setStatus(HttpServletResponse.SC_CREATED);
        }
        // Workaround for IE's broken caching behavior.
        resp.setHeader("Expires", "-1");
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (RpcException e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
    } catch (Exception e) {
        logger.error("", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();//from   ww  w. j a v  a  2 s . c om
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.imaginary.home.cloud.api.RestApi.java

@Override
public void doHead(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp)
        throws IOException, ServletException {
    String requestId = request(req);

    try {/*  ww  w.  j  a  v  a2s . c om*/
        Map<String, Object> headers = parseHeaders(req);
        String[] path = getPath(req);

        if (path.length < 1) {
            // TODO: documentation
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No HEAD is allowed against /");
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

            String userId = authenticate("HEAD", req, headers);

            call.head(requestId, userId, path, req, resp, headers, parameters);
        } else {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE,
                    "No " + path[0] + " resource exists in this API");
        }
    } catch (RestException e) {
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", e.getStatus());
        error.put("message", e.getMessage());
        error.put("description", e.getDescription());
        resp.setStatus(e.getStatus());
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    } catch (Throwable t) {
        t.printStackTrace();
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        error.put("message", RestException.INTERNAL_ERROR);
        error.put("description", t.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    }
}

From source file:org.gss_project.gss.server.rest.GroupsHandler.java

/**
 * Handle DELETE requests in the groups namespace.
 *
  * @param req The servlet request we are processing
  * @param resp The servlet response we are processing
  * @throws IOException if an input/output error occurs
 *//*from   ww w.  jav a2  s .  co  m*/
void deleteGroup(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String path = getInnerPath(req, PATH_GROUPS);
    if (path.equals(""))
        path = "/";

    if (path.equals("/"))
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, METHOD_GET + ", " + METHOD_POST);
    else {
        // Chop any trailing slash
        path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
        // Chop any leading slash
        path = path.startsWith("/") ? path.substring(1) : path;
        int slash = path.indexOf('/');
        try {
            User user = getUser(req);
            final User owner = getOwner(req);
            if (!owner.equals(user))
                throw new InsufficientPermissionsException("User " + user.getUsername()
                        + " does not have permission to modify the groups owned by " + owner.getUsername());
            if (slash != -1) {
                // Request to delete group member
                if (logger.isDebugEnabled())
                    logger.debug("Removing member " + path.substring(slash + 1) + " from group "
                            + path.substring(0, slash));
                final Group group = getService().getGroup(owner.getId(),
                        URLDecoder.decode(path.substring(0, slash), "UTF-8"));
                for (final User u : group.getMembers())
                    if (u.getUsername().equals(path.substring(slash + 1)))
                        new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                            @Override
                            public Void call() throws Exception {
                                getService().removeMemberFromGroup(owner.getId(), group.getId(), u.getId());
                                return null;
                            }
                        });
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Removing group " + path);
                final Group group = getService().getGroup(owner.getId(), URLDecoder.decode(path, "UTF-8"));
                new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                    @Override
                    public Void call() throws Exception {
                        getService().deleteGroup(owner.getId(), group.getId());
                        return null;
                    }
                });
            }
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
            // Workaround for IE's broken caching behavior.
            resp.setHeader("Expires", "-1");
        } catch (RpcException e) {
            logger.error("", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getMessage());
        } catch (Exception e) {
            logger.error("", e);
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
}