Example usage for javax.servlet.http HttpServletResponse SC_CONFLICT

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

Introduction

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

Prototype

int SC_CONFLICT

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

Click Source Link

Document

Status code (409) indicating that the request could not be completed due to a conflict with the current state of the resource.

Usage

From source file:org.apache.catalina.servlets.DefaultServlet.java

/**
 * Process a POST request for the specified resource.
 *
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet-specified error occurs
 *//*  ww  w.j av a  2s .c o m*/
protected void doPut(ActionContext context) throws ServletException, IOException {

    //showRequestInfo(context.getRequest());

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

    String path = getRelativePath(context.getRequest());

    //Fix for MACOSX finder. Do not allow requests for files starting with a period
    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        return;
    }

    // Retrieve the resources
    Connection db = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    Object object = null;

    boolean exists = true;
    boolean result = true;

    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);

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

        thisSystem = this.getSystemStatus(context);

        try {
            object = resources.lookup(thisSystem, db, path);
        } catch (NamingException e) {
            exists = false;
        }

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

        // Input stream for temp. content file used to support partial PUT
        FileInputStream contentFileInStream = null;

        //ResourceInfo resourceInfo = new ResourceInfo(thisSystem, path, resources);
        Range range = parseContentRange(context.getRequest(), context.getResponse());

        //InputStream resourceInputStream = null;
        ServletInputStream 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(context.getRequest(), range, path);
            //resourceInputStream = new FileInputStream(contentFile);
        } else {
            resourceInputStream = context.getRequest().getInputStream();
            //System.out.println("RESOURCE INPUT STREAM: " + resourceInputStream);
            System.out.println("CONTENT LENGTH: " + context.getRequest().getContentLength());
            //System.out.println("DATA: " + resourceInputStream.available());
        }

        try {
            Object thisObject = null;
            if (exists) {
                //resources.rebind(path, newResource);
                Resource oldResource = (Resource) object;
                oldResource.setContent(resourceInputStream);
                thisObject = resources.copyResource(thisSystem, db, path, oldResource);
            } else {
                Resource newResource = new Resource(resourceInputStream);
                thisObject = resources.copyResource(thisSystem, db, path, newResource);
            }
            if (thisObject != null) {
                processInsertHook(context, thisObject);
            }
        } catch (NamingException e) {
            //e.printStackTrace(System.out);
            result = false;
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
    } finally {
        this.freeConnection(db, context);
    }

    if (result) {
        if (exists) {
            context.getResponse().setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            context.getResponse().setStatus(HttpServletResponse.SC_CREATED);
        }
    } else {
        context.getResponse().sendError(HttpServletResponse.SC_CONFLICT);
    }
}

From source file:org.clothocad.phagebook.controllers.PersonController.java

@RequestMapping(value = "/createPerson", method = RequestMethod.POST)
protected void createPerson(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws ServletException, IOException {

    ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
    Clotho clothoObject = new Clotho(conn);

    String firstName = params.get("firstName");
    String lastName = params.get("lastName");
    String password = params.get("password");
    String emailId = params.get("emailId");

    Object pInstitutionId = params.get("institution");
    String institutionId = pInstitutionId != null ? (String) pInstitutionId : "";

    System.out.println("Passed in instit ID" + institutionId);
    Object pLabId = params.get("lab");
    String labId = pLabId != null ? (String) pLabId : "";
    Person createdPerson = new Person();
    createdPerson.setFirstName(firstName);
    createdPerson.setLastName(lastName);
    createdPerson.setEmailId(emailId);//from w  w  w . jav a2s . com
    createdPerson.setPassword(password);

    if (!institutionId.equals("")) {
        List<String> institutions = createdPerson.getInstitutions();
        institutions.add(institutionId);
        createdPerson.setInstitutions(institutions);
        createdPerson.setInstitution(institutionId);
        System.out.println("I GOT TO HERE WITH ID " + institutionId);
    }

    if (!labId.equals("")) {
        List<String> labs = createdPerson.getLabs();
        labs.add(labId);

        createdPerson.setLabs(labs);
    }

    EmailSaltHasher salty = EmailSaltHasher.getEmailSaltHasher();
    String salt = EmailSaltHasher.csRandomAlphaNumericString();
    createdPerson.setSalt(salt);

    byte[] SaltedHashedEmail = salty.hash(emailId.toCharArray(), salt.getBytes("UTF-8"));

    createdPerson.setSaltedEmailHash(SaltedHashedEmail);
    boolean isUnique = false;
    Map clothoQuery = new HashMap();
    clothoQuery.put("emailId", createdPerson.getEmailId());
    List<Person> people = ClothoAdapter.queryPerson(clothoQuery, clothoObject, ClothoAdapter.QueryMode.EXACT);

    if (people.isEmpty()) {
        isUnique = true;
    }

    if (isUnique) {
        clothoObject.logout();
        System.out.println(createdPerson.getInstitutions() + " THE INSTITUTIONS");
        ClothoAdapter.createPerson(createdPerson, clothoObject);

        EmailHandler emailer = EmailHandler.getEmailHandler();

        String link = Args.phagebookBaseURL + "/html/validateEmail.html?emailId=" + createdPerson.getEmailId()
                + "&salt=" + createdPerson.getSalt();
        System.out.println(link);

        emailer.sendEmailVerification(createdPerson, link);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/JSON");
        PrintWriter out = response.getWriter();

        JSONObject obj = new JSONObject();
        obj.put("clothoId", createdPerson.getId());
        obj.put("emailId", createdPerson.getEmailId());
        out.print(obj);
        out.flush();
        out.close();

    } else {
        System.out.println("User is not unique in Clotho");
        response.setStatus(HttpServletResponse.SC_CONFLICT);
        response.setContentType("application/JSON");
        PrintWriter out = response.getWriter();
        JSONObject obj = new JSONObject();
        obj.put("message", "Person Already Exists");
        out.print(obj);
        out.flush();
        out.close();
    }
    conn.closeConnection();

}

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

/**
 * Restores a previous version for a file.
 *
 * @param req the HTTP request//from w  w  w.j av a  2  s .  c o  m
 * @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:com.jpeterson.littles3.StorageEngine.java

/**
 * Write/*  www . ja v  a  2s .co m*/
 * 
 * @param req
 *            the HttpServletRequest object that contains the request the
 *            client made of the servlet
 * @param resp
 *            the HttpServletResponse object that contains the response the
 *            servlet returns to the client
 * @throws IOException
 *             if an input or output error occurs while the servlet is
 *             handling the PUT request
 * @throws ServletException
 *             if the request for the PUT cannot be handled
 */
@SuppressWarnings("unchecked")
public void methodPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStream out = null;

    try {
        S3ObjectRequest or;

        try {
            or = S3ObjectRequest.create(req, resolvedHost(),
                    (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
        } catch (InvalidAccessKeyIdException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
            return;
        } catch (InvalidSecurityException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        } catch (RequestTimeTooSkewedException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
            return;
        } catch (SignatureDoesNotMatchException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
            return;
        } catch (AuthenticatorException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
            return;
        }
        logger.debug("S3ObjectRequest: " + or);

        CanonicalUser requestor = or.getRequestor();

        if (or.getKey() != null) {
            String value;
            long contentLength;
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            DigestOutputStream digestOutputStream = null;
            S3Object oldS3Object = null;
            S3Object s3Object;
            StorageService storageService;
            Bucket bucket;
            String bucketName = or.getBucket();
            String key = or.getKey();

            if (!isValidKey(key)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "KeyTooLong");
                return;
            }

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;
                s3Object = storageService.load(bucketName, key);

                if (s3Object == null) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
                    return;
                }

                acp = s3Object.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                s3Object.setAcp(acp);

                storageService.store(s3Object);
            } else {
                // make sure requestor can "WRITE" to the bucket
                try {
                    bucket = storageService.loadBucket(bucketName);
                    bucket.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                try {
                    oldS3Object = storageService.load(bucket.getName(), key);
                } catch (DataRetrievalFailureException e) {
                    // ignore
                }

                // create a new S3Object for this request to store an object
                try {
                    s3Object = storageService.createS3Object(bucket, key, requestor);
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                out = s3Object.getOutputStream();
                digestOutputStream = new DigestOutputStream(out, messageDigest);

                // Used instead of req.getContentLength(); because Amazon
                // limit is 5 gig, which is bigger than an int
                value = req.getHeader("Content-Length");
                if (value == null) {
                    resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED, "MissingContentLength");
                    return;
                }
                contentLength = Long.valueOf(value).longValue();

                if (contentLength > 5368709120L) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "EntityTooLarge");
                    return;
                }

                long written = 0;
                int count;
                byte[] b = new byte[4096];
                ServletInputStream in = req.getInputStream();

                while (((count = in.read(b, 0, b.length)) > 0) && (written < contentLength)) {
                    digestOutputStream.write(b, 0, count);
                    written += count;
                }
                digestOutputStream.flush();

                if (written != contentLength) {
                    // transmission truncated
                    if (out != null) {
                        out.close();
                        out = null;
                    }
                    if (digestOutputStream != null) {
                        digestOutputStream.close();
                        digestOutputStream = null;
                    }
                    // clean up
                    storageService.remove(s3Object);
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "IncompleteBody");
                    return;
                }

                s3Object.setContentDisposition(req.getHeader("Content-Disposition"));
                s3Object.setContentLength(contentLength);
                s3Object.setContentMD5(req.getHeader("Content-MD5"));
                value = req.getContentType();
                logger.debug("Put - Content-Type: " + value);
                if (value == null) {
                    value = S3Object.DEFAULT_CONTENT_TYPE;
                }
                s3Object.setContentType(value);
                logger.debug("Put - get content-type: " + s3Object.getContentType());
                s3Object.setLastModified(System.currentTimeMillis());

                // metadata
                int prefixLength = HEADER_PREFIX_USER_META.length();
                String name;
                for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
                    String headerName = (String) headerNames.nextElement();
                    if (headerName.startsWith(HEADER_PREFIX_USER_META)) {
                        name = headerName.substring(prefixLength).toLowerCase();
                        for (Enumeration headers = req.getHeaders(headerName); headers.hasMoreElements();) {
                            value = (String) headers.nextElement();
                            s3Object.addMetadata(name, value);
                        }
                    }
                }

                // calculate ETag, hex encoding of MD5
                value = new String(Hex.encodeHex(digestOutputStream.getMessageDigest().digest()));
                resp.setHeader("ETag", value);
                s3Object.setETag(value);

                grantCannedAccessPolicies(req, s3Object.getAcp(), requestor);

                // NOTE: This could be reengineered to have a two-phase
                // commit.
                if (oldS3Object != null) {
                    storageService.remove(oldS3Object);
                }
                storageService.store(s3Object);
            }
        } else if (or.getBucket() != null) {
            StorageService storageService;
            Bucket bucket;

            storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

            if (req.getParameter(PARAMETER_ACL) != null) {
                // write access control policy
                Acp acp;
                CanonicalUser owner;

                logger.debug("User is providing new ACP for bucket " + or.getBucket());

                try {
                    bucket = storageService.loadBucket(or.getBucket());
                } catch (DataAccessException e) {
                    resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
                    return;
                }

                acp = bucket.getAcp();
                try {
                    acp.canWrite(requestor);
                } catch (AccessControlException e) {
                    resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
                    return;
                }

                // save owner
                owner = acp.getOwner();

                try {
                    acp = Acp.decode(req.getInputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "MalformedACLError");
                    return;
                }

                // maintain owner
                acp.setOwner(owner);

                bucket.setAcp(acp);

                logger.debug("Saving bucket ACP");
                logger.debug("ACP: " + Acp.encode(bucket.getAcp()));

                storageService.storeBucket(bucket);
            } else {
                // validate bucket
                String bucketName = or.getBucket();

                if (!isValidBucketName(bucketName)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidBucketName");
                    return;
                }

                try {
                    bucket = storageService.createBucket(bucketName, requestor);
                } catch (BucketAlreadyExistsException e) {
                    resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketAlreadyExists");
                    return;
                }

                grantCannedAccessPolicies(req, bucket.getAcp(), requestor);

                storageService.storeBucket(bucket);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        logger.error("Unable to use MD5", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "InternalError");
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (out != null) {
            out.close();
            out = null;
        }
    }
}

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/*  ww w .  ja  v  a  2 s.  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:com.jpeterson.littles3.StorageEngine.java

/**
 * Delete/* w ww.  j a v  a  2  s  . c o  m*/
 * 
 * @param req
 *            the HttpServletRequest object that contains the request the
 *            client made of the servlet
 * @param resp
 *            the HttpServletResponse object that contains the response the
 *            servlet returns to the client
 * @param IOException
 *            if an input or output error occurs while the servlet is
 *            handling the DELETE request
 * @param ServletException
 *            if the request for the DELETE cannot be handled
 */
public void methodDelete(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    S3ObjectRequest or;

    try {
        or = S3ObjectRequest.create(req, resolvedHost(),
                (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR));
    } catch (InvalidAccessKeyIdException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId");
        return;
    } catch (InvalidSecurityException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
        return;
    } catch (RequestTimeTooSkewedException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed");
        return;
    } catch (SignatureDoesNotMatchException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch");
        return;
    } catch (AuthenticatorException e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity");
        return;
    }
    logger.debug("S3ObjectRequest: " + or);

    CanonicalUser requestor = or.getRequestor();

    if (or.getKey() != null) {
        Bucket bucket;
        S3Object s3Object;
        StorageService storageService;

        storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

        // make sure requester can "WRITE" to the bucket
        try {
            bucket = storageService.loadBucket(or.getBucket());
            bucket.canWrite(requestor);
        } catch (AccessControlException e) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
            return;
        } catch (DataAccessException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
            return;
        }

        try {
            s3Object = storageService.load(bucket.getName(), or.getKey());
        } catch (DataRetrievalFailureException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey");
            return;
        }
        storageService.remove(s3Object);

        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return;
    } else if (or.getBucket() != null) {
        StorageService storageService;
        Bucket bucket;

        // validate bucket
        String bucketName = or.getBucket();

        storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE);

        try {
            bucket = storageService.loadBucket(bucketName);
        } catch (DataAccessException e) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket");
            return;
        }

        if (!requestor.equals(bucket.getAcp().getOwner())) {
            resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied");
            return;
        }

        try {
            storageService.deleteBucket(bucket);
        } catch (BucketNotEmptyException e) {
            resp.sendError(HttpServletResponse.SC_CONFLICT, "BucketNotEmpty");
            return;
        }

        resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return;
    }

    resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED);
}

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//  ww  w.j av a  2  s  .  c o  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.gss_project.gss.server.rest.FilesHandler.java

/**
 * Copy the resource in the specified path to the specified destination.
 *
 * @param req the HTTP request// ww  w .j  ava 2 s  .  co  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.gss_project.gss.server.rest.FilesHandler.java

/**
 * Update the resource in the specified path.
 *
 * @param req the HTTP request//from  w  ww.j a  v  a2  s .  co m
 * @param resp the HTTP response
 * @param path the path of the resource
 * @throws IOException if an input/output error occurs
 */
private void updateResource(HttpServletRequest req, HttpServletResponse resp, String path) throws IOException {
    final User user = getUser(req);
    User owner = getOwner(req);
    Object resource = null;

    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    StringBuffer input = new StringBuffer();
    JSONObject json = null;
    if (req.getContentType() != null && req.getContentType().startsWith("application/x-www-form-urlencoded"))
        input.append(req.getParameter(RESOURCE_UPDATE_PARAMETER));
    else {
        // Assume application/json
        BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream(), "UTF-8"));
        String line = null;
        while ((line = reader.readLine()) != null)
            input.append(line);
        reader.close();
    }
    try {
        json = new JSONObject(input.toString());
        if (logger.isDebugEnabled())
            logger.debug("JSON update: " + json);
        if (resource instanceof Folder) {
            final Folder folderLocal = (Folder) resource;
            String name = json.optString("name");
            if (!isValidResourceName(name)) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            JSONArray permissions = json.optJSONArray("permissions");
            Set<Permission> perms = null;
            if (permissions != null)
                perms = parsePermissions(user, permissions);
            Boolean readForAll = null;
            if (json.opt("readForAll") != null)
                readForAll = json.optBoolean("readForAll");
            if (!name.isEmpty() || permissions != null || readForAll != null) {
                final String fName = name.isEmpty() ? null : name;
                final Boolean freadForAll = readForAll;
                final Set<Permission> fPerms = perms;
                Folder folderUpdated = new TransactionHelper<Folder>().tryExecute(new Callable<Folder>() {
                    @Override
                    public Folder call() throws Exception {
                        return getService().updateFolder(user.getId(), folderLocal.getId(), fName, freadForAll,
                                fPerms);
                    }

                });
                resp.getWriter().println(getNewUrl(req, folderUpdated));
            }
        } else {
            final FileHeader fileLocal = (FileHeader) resource;
            String name = null;
            if (json.opt("name") != null)
                name = json.optString("name");
            if (name != null)
                if (!isValidResourceName(name)) {
                    resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
            Long modificationDate = null;
            if (json.optLong("modificationDate") != 0)
                modificationDate = json.optLong("modificationDate");
            Boolean versioned = null;
            if (json.opt("versioned") != null)
                versioned = json.getBoolean("versioned");
            JSONArray tagset = json.optJSONArray("tags");
            String tags = null;
            StringBuffer t = new StringBuffer();
            if (tagset != null) {
                for (int i = 0; i < tagset.length(); i++)
                    t.append(tagset.getString(i) + ',');
                tags = t.toString();
            }
            JSONArray permissions = json.optJSONArray("permissions");
            Set<Permission> perms = null;
            if (permissions != null)
                perms = parsePermissions(user, permissions);
            Boolean readForAll = null;
            if (json.opt("readForAll") != null)
                readForAll = json.optBoolean("readForAll");
            if (name != null || tags != null || modificationDate != null || versioned != null || perms != null
                    || readForAll != null) {
                final String fName = name;
                final String fTags = tags;
                final Date mDate = modificationDate != null ? new Date(modificationDate) : null;
                final Boolean fVersioned = versioned;
                final Boolean fReadForAll = readForAll;
                final Set<Permission> fPerms = perms;
                new TransactionHelper<Object>().tryExecute(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        getService().updateFile(user.getId(), fileLocal.getId(), fName, fTags, mDate,
                                fVersioned, fReadForAll, fPerms);
                        return null;
                    }

                });
            }
        }
    } catch (JSONException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT, e.getMessage());
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
}

From source file:org.opencms.webdav.CmsWebdavServlet.java

/**
 * Process a POST request for the specified resource.<p>
 *
 * @param req the servlet request we are processing
 * @param resp the servlet response we are creating
 *
 * @throws IOException if an input/output error occurs
 *//*from   w ww  .j  av a  2  s  .  c  o m*/
@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);
        }
    }
}