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:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @param req  Description of the Parameter
 * @param resp Description of the Parameter
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet-specified error occurs
 *///from www  . j  a v  a 2s.c o  m
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    if (readOnly) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    String path = getRelativePath(req);

    // Retrieve the Catalina context
    // Retrieve the resources
    DirContext resources = getResources();

    if (resources == null) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    boolean exists = true;
    try {
        resources.lookup(path);
    } catch (NamingException e) {
        exists = false;
    }

    if (exists) {
        boolean result = true;
        try {
            resources.unbind(path);
        } catch (NamingException e) {
            result = false;
        }
        if (result) {
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } else {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

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

/**
 * Restores a previous version for a file.
 *
 * @param req the HTTP request// w ww.  ja va 2  s  .com
 * @param resp the HTTP response
 * @param path the resource path
 * @param version the version number to restore
 * @throws IOException if an I/O error occurs
 */
private void restoreVersion(HttpServletRequest req, HttpServletResponse resp, String path, String version)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (resource instanceof Folder) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    try {
        final FileHeader file = (FileHeader) resource;
        final int oldVersion = Integer.parseInt(version);

        new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                getService().restoreVersion(user.getId(), file.getId(), oldVersion);
                return null;
            }
        });
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (NumberFormatException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.jahia.bin.Render.java

public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    if (isDisabled()) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }//from ww w  . j a v a2s . c  o  m
    String method = req.getMethod();
    if (req.getParameter(METHOD_TO_CALL) != null) {
        method = req.getParameter(METHOD_TO_CALL).toUpperCase();
    }
    if (!isMethodAllowed(method)) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return null;
    }
    long startTime = System.currentTimeMillis();
    String sessionId = null;
    try {
        final HttpSession session = req.getSession();
        if (logger.isInfoEnabled()) {
            sessionId = session.getId();
        }
        URLResolver urlResolver = urlResolverFactory.createURLResolver(req.getPathInfo(), req.getServerName(),
                workspace, req);

        req.setAttribute("urlResolver", urlResolver);

        session.setAttribute("workspace", urlResolver.getWorkspace());

        if (sessionExpiryTime != null && session.getMaxInactiveInterval() != sessionExpiryTime * 60) {
            session.setMaxInactiveInterval(sessionExpiryTime * 60);
        }

        RenderContext renderContext = createRenderContext(req, resp, jcrSessionFactory.getCurrentUser());
        renderContext.setWorkspace(urlResolver.getWorkspace());

        urlResolver.setRenderContext(renderContext);
        req.getSession().setAttribute(Constants.SESSION_LOCALE, urlResolver.getLocale());
        jcrSessionFactory.setCurrentLocale(urlResolver.getLocale());
        if (renderContext.isPreviewMode() && req.getParameter(ALIAS_USER) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            JahiaUserManagerService userManagerService = ServicesRegistry.getInstance()
                    .getJahiaUserManagerService();
            JCRUserNode userNode = userManagerService.lookupUser(req.getParameter(ALIAS_USER),
                    urlResolver.getSiteKey());
            if (userNode != null) {
                jcrSessionFactory.setCurrentAliasedUser(userNode.getJahiaUser());
            }
        }

        // check permission
        try {
            if (!hasAccess(urlResolver.getNode())) {
                if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                    throw new JahiaUnauthorizedException();
                } else {
                    throw new JahiaForbiddenAccessException();
                }
            }
        } catch (PathNotFoundException e) {

        }

        renderContext.setSiteInfo(urlResolver.getSiteInfo());

        if (renderContext.isPreviewMode() && req.getParameter(PREVIEW_DATE) != null
                && !JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
            Calendar previewDate = Calendar.getInstance();
            previewDate.setTime(new Date(new Long(req.getParameter(PREVIEW_DATE))));
            jcrSessionFactory.setCurrentPreviewDate(previewDate);
        }
        if (method.equals(METHOD_GET)) {
            Resource resource;
            resource = urlResolver.getResource();
            if (!StringUtils.isEmpty(urlResolver.getRedirectUrl())
                    && (StringUtils.isEmpty(resource.getTemplate())
                            || StringUtils.equals(resource.getTemplate(), "default"))) {
                Map<String, List<String>> parameters = new HashMap<String, List<String>>();
                parameters.put(NEW_NODE_OUTPUT_FORMAT, LIST_WITH_EMPTY_STRING);
                parameters.put(REDIRECT_HTTP_RESPONSE_CODE, REDIRECT_CODE_MOVED_PERMANENTLY);

                performRedirect(urlResolver.getRedirectUrl(),
                        StringUtils.isEmpty(urlResolver.getVanityUrl())
                                ? "/" + urlResolver.getLocale().toString() + urlResolver.getPath()
                                : urlResolver.getVanityUrl(),
                        req, resp, parameters, false);
            } else {
                renderContext.setMainResource(resource);
                if (renderContext.getSite() == null) {
                    // If Site has not been resolved by the servlet (so far only dashboard mode is doing that
                    JCRSiteNode site = resource.getNode().getResolveSite();
                    if (!Url.isLocalhost(req.getServerName()) && !renderContext.isEditMode()) {
                        JCRSessionWrapper session1 = resource.getNode().getSession();
                        if (urlResolver.getSiteKey() != null
                                && (site == null || !site.getSiteKey().equals(urlResolver.getSiteKey()))) {
                            site = (JCRSiteNode) session1.getNode("/sites/" + urlResolver.getSiteKey());
                        } else if (renderContext.isLiveMode() && urlResolver.getSiteKeyByServerName() != null
                                && (site == null
                                        || !site.getSiteKey().equals(urlResolver.getSiteKeyByServerName()))) {
                            site = (JCRSiteNode) session1
                                    .getNode("/sites/" + urlResolver.getSiteKeyByServerName());
                        }
                    }
                    String jsite = null;
                    HttpServletRequest request = renderContext.getRequest();
                    if (request != null) {
                        jsite = request.getParameter("jsite");
                    }
                    if (jsite == null && renderContext.getMainResource() != null) {
                        jsite = (String) renderContext.getMainResource().getModuleParams().get("jsite");
                    }
                    if (jsite != null) {
                        try {
                            site = (JCRSiteNode) resource.getNode().getSession().getNodeByIdentifier(jsite);
                        } catch (ItemNotFoundException e) {
                            if (JahiaUserManagerService.isGuest(jcrSessionFactory.getCurrentUser())) {
                                throw new JahiaUnauthorizedException();
                            } else {
                                throw new JahiaForbiddenAccessException();
                            }
                        }
                    }
                    if (resource.getNode().getPath().startsWith("/sites/") && (site == null || (!site.getPath()
                            .startsWith("/modules/")
                            && !site.isAllowsUnlistedLanguages()
                            && !(renderContext.isLiveMode()
                                    ? site.getActiveLiveLanguagesAsLocales().contains(urlResolver.getLocale())
                                    : site.getLanguagesAsLocales().contains(urlResolver.getLocale()))))) {
                        throw new PathNotFoundException("This language does not exist on this site");
                    }
                    renderContext.setSite(site);
                }
                //                    resource.pushWrapper("wrapper.fullpage");

                if (urlResolver.getPath().endsWith(".do")) {
                    Action action = templateService.getActions().get(resource.getResolvedTemplate());
                    Map<String, List<String>> parameters = toParameterMapOfListOfString(req);
                    if (action != null) {
                        doAction(req, resp, urlResolver, renderContext, resource, action, parameters);
                    } else {
                        logger.error("Action {} does not exist", resource.getResolvedTemplate());
                        throw new PathNotFoundException("Action does not exist");
                    }
                } else {
                    long lastModified = getLastModified(resource, renderContext);

                    if (lastModified == -1) {
                        // servlet doesn't support if-modified-since, no reason
                        // to go through further expensive logic
                        doGet(req, resp, renderContext, resource, startTime);
                    } else {
                        long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                        if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                            // If the servlet mod time is later, call doGet()
                            // Round down to the nearest second for a proper compare
                            // A ifModifiedSince of -1 will always be less
                            maybeSetLastModified(resp, lastModified);
                            doGet(req, resp, renderContext, resource, startTime);
                        } else {
                            resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                        }
                    }
                }
            }
        } else if (method.equals(METHOD_HEAD)) {
            doHead(req, resp);

        } else if (method.equals(METHOD_POST)) {
            doPost(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp, renderContext, urlResolver);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req, resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req, resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    } catch (Exception e) {
        List<ErrorHandler> handlers = templateService.getErrorHandler();
        for (ErrorHandler handler : handlers) {
            if (handler.handle(e, req, resp)) {
                return null;
            }
        }
        DefaultErrorHandler.getInstance().handle(e, req, resp);
    } finally {
        if (logger.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder(100);
            sb.append("Rendered [").append(req.getRequestURI());
            if (jcrSessionFactory.getCurrentUser() != null) {
                sb.append("] user=[").append(jcrSessionFactory.getCurrentUser().getUsername());
            }
            sb.append("] ip=[").append(req.getRemoteAddr()).append("] sessionID=[").append(sessionId)
                    .append("] in [").append(System.currentTimeMillis() - startTime).append("ms]");
            logger.info(sb.toString());
        }
    }
    return null;
}

From source file:org.nuxeo.ecm.automation.server.test.EmbeddedAutomationClientTest.java

/**
 * @since 7.1/*from  w ww.  jav a  2  s  . c  om*/
 */
@Test
public void shouldReturnCustomHttpStatusWhenFailure() throws Exception {
    try {
        session.newRequest(HttpStatusOperationTest.ID).set("isFailing", true).execute();
        fail();
    } catch (RemoteException e) {
        assertNotNull(e);
        RemoteThrowable cause = (RemoteThrowable) e.getRemoteCause();
        while (cause.getCause() != null && cause.getCause() != cause) {
            cause = (RemoteThrowable) cause.getCause();
        }
        assertEquals("Exception Message", cause.getMessage());
        assertEquals(ExceptionTest.class.getCanonicalName(),
                cause.getOtherNodes().get("className").getTextValue());
        assertEquals(HttpServletResponse.SC_METHOD_NOT_ALLOWED, e.getStatus());
    } catch (Exception e) {
        fail();
    }
}

From source file:edu.slu.action.ObjectAction.java

/**
 * Since programming languages with HTTP packages don't all support PATCH, we have to detect the workaround.
 * If the user supplies the header//from w  w  w . jav a  2s  .  c o  m
 * @param http_request the request that was made so we can check its headers.
 * @return 
 */
private String checkPatchOverrideSupport(HttpServletRequest http_request) {
    String overrideStatus = "no";
    String overrideHeader = http_request.getHeader("X-HTTP-Method-Override");
    String methodUsed = http_request.getMethod();
    if (null != overrideHeader) {
        if (overrideHeader.equals("PATCH") && methodUsed.equals("POST")) {
            overrideStatus = "yes";
        } else {
            overrideStatus = "improper";
            writeErrorResponse(
                    "The use of the override header for 'PATCH' requests is allowed.  The method must be 'POST' and the header value must be 'PATCH'",
                    HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }
    }
    return overrideStatus;
}

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

/**
 * A method for handling multipart POST requests for uploading
 * files from browser-based JavaScript clients.
 *
 * @param request the HTTP request/*from   w  w  w . j a  va2s.co  m*/
 * @param response the HTTP response
 * @param path the resource path
 * @throws IOException in case an error occurs writing to the
 *       response stream
 */
private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Multipart POST for resource: " + path);

    User owner = getOwner(request);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader) {
            file = (FileHeader) resource;
            if (file.isDeleted()) {
                response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }

    Object parent;
    String parentPath = null;
    try {
        parentPath = getParentPath(path);
        parent = getService().getResourceAtPath(owner.getId(), parentPath, true);
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath);
        return;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (!(parent instanceof Folder)) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }
    final Folder folderLocal = (Folder) parent;
    final String fileName = getLastElement(path);

    if (!isValidResourceName(fileName)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    FileItemIterator iter;
    File uploadedFile = null;
    try {
        // Create a new file upload handler.
        ServletFileUpload upload = new ServletFileUpload();
        StatusProgressListener progressListener = new StatusProgressListener(getService());
        upload.setProgressListener(progressListener);
        iter = upload.getItemIterator(request);
        String dateParam = null;
        String auth = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                final String value = Streams.asString(stream);
                if (name.equals(DATE_PARAMETER))
                    dateParam = value;
                else if (name.equals(AUTHORIZATION_PARAMETER))
                    auth = value;

                if (logger.isDebugEnabled())
                    logger.debug(name + ":" + value);
            } else {
                // Fetch the timestamp used to guard against replay attacks.
                if (dateParam == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter");
                    return;
                }

                long timestamp;
                try {
                    timestamp = DateUtil.parseDate(dateParam).getTime();
                } catch (DateParseException e) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                    return;
                }

                // Fetch the Authorization parameter and find the user specified in it.
                if (auth == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter");
                    return;
                }
                String[] authParts = auth.split(" ");
                if (authParts.length != 2) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                String username = authParts[0];
                String signature = authParts[1];
                User user = null;
                try {
                    user = getService().findUser(username);
                } catch (RpcException e) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                if (user == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                request.setAttribute(USER_ATTRIBUTE, user);

                // Remove the servlet path from the request URI.
                String p = request.getRequestURI();
                String servletPath = request.getContextPath() + request.getServletPath();
                p = p.substring(servletPath.length());
                // Validate the signature in the Authorization parameter.
                String data = request.getMethod() + dateParam + p;
                if (!isSignatureValid(signature, user, data)) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                progressListener.setUserId(user.getId());
                progressListener.setFilename(fileName);
                final String contentType = item.getContentType();

                try {
                    uploadedFile = getService().uploadFile(stream, user.getId());
                } catch (IOException ex) {
                    throw new GSSIOException(ex, false);
                }
                FileHeader fileLocal = null;
                final File upf = uploadedFile;
                final FileHeader f = file;
                final User u = user;
                if (file == null)
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().createFile(u.getId(), folderLocal.getId(), fileName,
                                    contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                else
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().updateFileContents(u.getId(), f.getId(), contentType,
                                    upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize());
                getService().removeFileUploadProgress(user.getId(), fileName);
            }
        }
        // We can't return 204 here since GWT's onSubmitComplete won't fire.
        response.setContentType("text/html");
        response.getWriter().print("<pre></pre>");
    } catch (FileUploadException e) {
        String error = "Error while uploading file";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (GSSIOException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Error while uploading file";
        if (e.logAsError())
            logger.error(error, e);
        else
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (DuplicateNameException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "The specified file name already exists in this folder";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_CONFLICT, error);

    } catch (InsufficientPermissionsException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "You don't have the necessary permissions";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error);

    } catch (QuotaExceededException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Not enough free space available";
        if (logger.isDebugEnabled())
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error);

    } catch (ObjectNotFoundException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "A specified object was not found";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, error);
    } catch (RpcException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (Exception e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An internal server error occurred";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    }
}

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

/**
 * Move the resource in the specified path to the specified destination.
 *
 * @param req the HTTP request/*from w  w  w  .  j a v  a2  s. co  m*/
 * @param resp the HTTP response
 * @param path the path of the resource
 * @param moveTo the destination of the move procedure
 * @throws IOException if an input/output error occurs
 */
private void moveResource(HttpServletRequest req, HttpServletResponse resp, String path, String moveTo)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    String destination = null;
    User destOwner = null;
    boolean exists = true;
    try {
        destination = getDestinationPath(req, encodePath(moveTo));
        destination = URLDecoder.decode(destination, "UTF-8");
        destOwner = getDestinationOwner(req);
        getService().getResourceAtPath(destOwner.getId(), destination, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
        return;
    }
    if (exists) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
        return;
    }

    try {
        final User dOwner = destOwner;
        final String dest = destination;
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().moveFolderToPath(user.getId(), dOwner.getId(), folderLocal.getId(), dest);
                    return null;
                }
            });
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().moveFileToPath(user.getId(), dOwner.getId(), fileLocal.getId(), dest);
                    return null;
                }
            });

        }
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    }
}

From source file:org.energy_home.jemma.internal.shapi.HapProxy.java

protected void doDelete(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    String requestUri = servletRequest.getRequestURI();
    initResponse(servletResponse);//from w w w.j  av  a  2 s  .c o  m
    requestUri = replaceFilters(requestUri, false);
    if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) {
        try {
            if (requestUri.startsWith(subscriptionItemsAddressedId)) {
                if (requestUri.endsWith(M2MContainerAddress.ALL_ID_FILTER))
                    servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                else {
                    String subscriptionId = requestUri.substring(subscriptionItemsAddressedId.length() + 1,
                            requestUri.length());
                    SubscriptionInfo subscriptionInfo = null;
                    synchronized (subscriptionInfos) {
                        for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                            subscriptionInfo = (SubscriptionInfo) iterator.next();
                            if (subscriptionInfo.subscription.getId().equals(subscriptionId)) {
                                iterator.remove();
                                break;
                            }
                        }
                    }
                }
            } else {
                AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri);
                if (!isValidLocalHagId(containerAddress.getHagId()))
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                String appliancePid = containerAddress.getAppliancePid();
                if (containerAddress.getAppliancePid() != null && containerAddress.getEndPointId() == null
                        && containerAddress.getContainerName() == null) {
                    ContentInstance ci = hapService.getM2MHapService()
                            .getLocalContentInstance(containerAddress);
                    boolean result = false;
                    // Only existing resources are deleted
                    if (ci != null) {
                        result = appliancesProxy.deleteAppliance(appliancePid);
                        if (!result) {
                            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                            return;
                        }
                    } else {
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                        return;
                    }

                } else {
                    servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                }
                ContentInstance ci = new ContentInstance();
                ci.setId(System.currentTimeMillis());
                writeXmlObject(servletResponse, ci);
            }
        } catch (Exception e) {
            log.error("service: error while parsing local request", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

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

/**
 * Copy the resource in the specified path to the specified destination.
 *
 * @param req the HTTP request//  w w  w.j  a  va  2s.  c o m
 * @param resp the HTTP response
 * @param path the path of the resource
 * @param copyTo the destination of the copy procedure
 * @throws IOException if an input/output error occurs
 */
private void copyResource(HttpServletRequest req, HttpServletResponse resp, String path, String copyTo)
        throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    String destination = null;
    User destOwner = null;
    boolean exists = true;
    try {
        String destinationEncoded = getDestinationPath(req, encodePath(copyTo));
        destination = URLDecoder.decode(destinationEncoded, "UTF-8");
        destOwner = getDestinationOwner(req);
        getService().getResourceAtPath(destOwner.getId(), destinationEncoded, true);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
        return;
    }
    if (exists) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, destination + " already exists");
        return;
    }

    try {
        final User dOwner = destOwner;
        final String dest = destination;
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().copyFolderStructureToPath(user.getId(), dOwner.getId(), folderLocal.getId(),
                            dest);
                    return null;
                }
            });
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            new TransactionHelper<Void>().tryExecute(new Callable<Void>() {
                @Override
                public Void call() throws Exception {
                    getService().copyFileToPath(user.getId(), dOwner.getId(), fileLocal.getId(), dest);
                    return null;
                }
            });
        }
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, destination);
    }
}

From source file:org.energy_home.jemma.internal.shapi.M2MLocalService.java

protected void doDelete(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {
    String requestUri = servletRequest.getRequestURI();
    initResponse(servletResponse);//from   ww  w.j a  v a  2s.  co m
    requestUri = replaceFilters(requestUri, false);
    if (requestUri.startsWith(M2MConstants.URL_HAG_SCL_BASE)) {
        try {
            if (requestUri.startsWith(subscriptionItemsAddressedId)) {
                if (requestUri.endsWith(M2MContainerAddress.ALL_ID_FILTER))
                    servletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                else {
                    String subscriptionId = requestUri.substring(subscriptionItemsAddressedId.length() + 1,
                            requestUri.length());
                    SubscriptionInfo subscriptionInfo = null;
                    synchronized (subscriptionInfos) {
                        for (Iterator iterator = subscriptionInfos.iterator(); iterator.hasNext();) {
                            subscriptionInfo = (SubscriptionInfo) iterator.next();
                            if (subscriptionInfo.subscription.getId().equals(subscriptionId)) {
                                iterator.remove();
                                break;
                            }
                        }
                    }
                }
            } else {
                AHContainerAddress containerAddress = new AHM2MContainerAddress(requestUri);
                if (!isValidLocalHagId(containerAddress.getHagId()))
                    servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                String appliancePid = containerAddress.getAppliancePid();
                if (containerAddress.getAppliancePid() != null && containerAddress.getEndPointId() == null
                        && containerAddress.getContainerName() == null) {
                    ContentInstance ci = hapService.getLocalContentInstance(containerAddress);
                    boolean result = false;
                    // Only existing resources are deleted
                    if (ci != null) {
                        result = appliancesProxy.deleteAppliance(appliancePid);
                        if (!result) {
                            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
                            return;
                        }
                    } else {
                        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
                        return;
                    }

                } else {
                    servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
                }
                ContentInstance ci = new ContentInstance();
                ci.setId(System.currentTimeMillis());
                writeXmlObject(servletResponse, ci);
            }
        } catch (Exception e) {
            LOG.error("service: error while parsing local request", e);
            servletResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
    } else {
        servletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}