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.gss_project.gss.server.rest.FilesHandler.java

/**
 * Creates a new folder with the specified name under the folder in the provided path.
 *
 * @param req the HTTP request/*from w w w  .  ja  v  a2s . c  o  m*/
 * @param resp the HTTP response
 * @param path the parent folder path
 * @param folderName the name of the new folder
 * @throws IOException if an input/output error occurs
 */
private void createFolder(HttpServletRequest req, HttpServletResponse resp, String path,
        final String folderName) throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Creating folder " + folderName + " in '" + path);

    final User user = getUser(req);
    User owner = getOwner(req);
    boolean exists = true;
    try {
        getService().getResourceAtPath(owner.getId(), path + folderName, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
        return;
    }

    if (exists) {
        resp.addHeader("Allow", METHOD_GET + ", " + METHOD_DELETE + ", " + METHOD_HEAD);
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    Object parent;
    try {
        parent = getService().getResourceAtPath(owner.getId(), path, true);
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
        return;
    }
    try {
        if (parent instanceof Folder) {
            final Folder folderLocal = (Folder) parent;
            Folder newFolder = new TransactionHelper<Folder>().tryExecute(new Callable<Folder>() {
                @Override
                public Folder call() throws Exception {
                    return getService().createFolder(user.getId(), folderLocal.getId(), folderName);
                }

            });
            String newResource = getApiRoot() + newFolder.getURI();
            resp.setHeader("Location", newResource);
            resp.setContentType("text/plain");
            PrintWriter out = resp.getWriter();
            out.println(newResource);
        } else {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    } catch (ObjectNotFoundException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path + folderName);
        return;
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    resp.setStatus(HttpServletResponse.SC_CREATED);
}

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

/**
 * @param req/*from  ww w . j av a  2 s. c  om*/
 * @param resp
 * @throws IOException
 * @throws FileNotFoundException
 */
void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException {
    String path = getInnerPath(req, PATH_FILES);
    try {
        path = URLDecoder.decode(path, "UTF-8");
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    }
    if (logger.isDebugEnabled())
        logger.debug("Updating resource: " + path);

    final User user = getUser(req);
    User owner = getOwner(req);
    boolean exists = true;
    Object resource = null;
    FileHeader fileLocal = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader)
            fileLocal = (FileHeader) resource;
        else {
            resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }
    boolean result = true;

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

    Range range = parseContentRange(req, resp);

    InputStream resourceInputStream = null;

    // Append data specified in ranges to existing content for this
    // resource - create a temporary file on the local filesystem to
    // perform this operation.
    // Assume just one range is specified for now
    if (range != null) {
        try {
            contentFile = executePartialPut(req, range, path);
        } catch (RpcException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
            return;
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        resourceInputStream = new FileInputStream(contentFile);
    } else
        resourceInputStream = req.getInputStream();

    try {
        Folder folderLocal = null;
        Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true);
        if (!(parent instanceof Folder)) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }
        folderLocal = (Folder) parent;
        final String name = getLastElement(path);
        final String mimeType = context.getMimeType(name);
        File uploadedFile = null;
        try {
            uploadedFile = getService().uploadFile(resourceInputStream, user.getId());
        } catch (IOException ex) {
            throw new GSSIOException(ex, false);
        }
        FileHeader fileTemp = null;
        final File uploadedf = uploadedFile;
        final Folder parentf = folderLocal;
        final FileHeader f = fileLocal;
        if (exists)
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().updateFileContents(user.getId(), f.getId(), mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }
            });
        else
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().createFile(user.getId(), parentf.getId(), name, mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }

            });
        updateAccounting(owner, new Date(), fileTemp.getCurrentBody().getFileSize());
        getService().removeFileUploadProgress(user.getId(), fileTemp.getName());
    } catch (ObjectNotFoundException e) {
        result = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
        return;
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

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

From source file:org.sakaiproject.dav.DavServlet.java

/**
 * Process a PUT request for the specified resource.
 * /* w  w  w.j  ava 2  s  . c  o  m*/
 * @param request
 *        The servlet request we are processing
 * @param response
 *        The servlet response we are creating
 * @exception IOException
 *            if an input/output error occurs
 * @exception ServletException
 *            if a servlet-specified error occurs
 */
@SuppressWarnings("unchecked")
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    // Do not allow files which match patterns specified in properties
    if (!isFileNameAllowed(req)) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    if (isLocked(req)) {
        resp.sendError(SakaidavStatus.SC_LOCKED);
        return;
    }

    String path = getRelativePathSAKAI(req);

    if (prohibited(path) || (path.toUpperCase().startsWith("/WEB-INF"))
            || (path.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    // Looking for a Content-Range header
    if (req.getHeader("Content-Range") != null) {
        // No content range header is supported
        resp.sendError(SakaidavStatus.SC_NOT_IMPLEMENTED);
    }

    String name = justName(path);

    // Database max for id field is 255. If we allow longer, odd things happen
    if (path.length() > 254) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    if ((name.toUpperCase().startsWith("/WEB-INF")) || (name.toUpperCase().startsWith("/META-INF"))) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    }

    // Don't delete the resource and add it again

    // Update the resource

    String contentType = "";
    InputStream inputStream = req.getInputStream();
    contentType = req.getContentType();

    // For MS office, ignore the supplied content type if we can figure out one from file type
    // they send text/xml for doc and docx files
    if (contentType != null) {
        UsageSession session = UsageSessionService.getSession();
        String agent = null;
        if (session != null)
            agent = session.getUserAgent();
        if (agent != null && agent.startsWith("Microsoft Office Core Storage Infrastructure")) {
            String fileContentType = getServletContext().getMimeType(path);
            if (fileContentType != null) {
                contentType = fileContentType;
            }
        }
    }

    if (M_log.isDebugEnabled())
        M_log.debug("  req.contentType() =" + contentType);

    if (contentType == null) {
        contentType = getServletContext().getMimeType(path);
        if (M_log.isDebugEnabled())
            M_log.debug("Lookup contentType =" + contentType);
    }
    if (contentType == null) {
        if (M_log.isDebugEnabled())
            M_log.debug("Unable to determine contentType");
        contentType = ""; // Still cannot figure it out
    }

    try {

        ContentResourceEdit edit;

        boolean newfile = false;
        String resourcePath = adjustId(path);

        // Since editResource doesn't throw IdUnusedException correctly, try first with getResource
        try {
            contentHostingService.getResource(resourcePath);
        } catch (IdUnusedException e) {
            newfile = true;
        }

        if (newfile) {
            edit = contentHostingService.addResource(resourcePath);
            final ResourcePropertiesEdit p = edit.getPropertiesEdit();
            p.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);

            User user = UserDirectoryService.getCurrentUser();
            final TimeBreakdown timeBreakdown = TimeService.newTime().breakdownLocal();
            p.addProperty(ResourceProperties.PROP_COPYRIGHT, "copyright (c)" + " " + timeBreakdown.getYear()
                    + ", " + user.getDisplayName() + ". All Rights Reserved. ");
        } else {
            edit = contentHostingService.editResource(resourcePath);
            contentType = edit.getContentType();
        }

        edit.setContentType(contentType);
        edit.setContent(inputStream);

        // commit the change
        contentHostingService.commitResource(edit, NotificationService.NOTI_NONE);

    } catch (IdUsedException e) {
        // Should not happen because we deleted above (unless two requests at same time)
        M_log.warn("SAKAIDavServlet.doPut() IdUsedException:" + e.getMessage());

        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (IdInvalidException e) {
        M_log.warn("SAKAIDavServlet.doPut() IdInvalidException:" + e.getMessage());
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (PermissionException e) {
        // Normal
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (OverQuotaException e) {
        // Normal %%% what's the proper response for over-quota?
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (InconsistentException e) {
        M_log.warn("SAKAIDavServlet.doPut() InconsistentException:" + e.getMessage());
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (ServerOverloadException e) {
        M_log.warn("SAKAIDavServlet.doPut() ServerOverloadException:" + e.getMessage());
        resp.setStatus(SakaidavStatus.SC_SERVICE_UNAVAILABLE);
        return;
    } catch (InUseException e) {
        resp.sendError(SakaidavStatus.SC_FORBIDDEN);
        return;
    } catch (TypeException e) {
        M_log.warn("SAKAIDavServlet.doPut() TypeException:" + e.getMessage());
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (IdUnusedException inconsistent) {
        M_log.error(
                "SAKAIDavServlet.doPut() Inconsistently got IdUnusedException after checking resource exists: "
                        + inconsistent.getMessage());
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    resp.setStatus(HttpServletResponse.SC_CREATED);

    // Removing any lock-null resource which would be present
    lockNullResources.remove(path);

}

From source file:org.opencastproject.adminui.endpoint.AbstractEventEndpoint.java

@POST
@Path("new/conflicts")
@RestQuery(name = "checkNewConflicts", description = "Checks if the current scheduler parameters are in a conflict with another event", returnDescription = "Returns NO CONTENT if no event are in conflict within specified period or list of conflicting recordings in JSON", restParameters = {
        @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_NO_CONTENT, description = "No conflicting events found"),
                @RestResponse(responseCode = HttpServletResponse.SC_CONFLICT, description = "There is a conflict"),
                @RestResponse(responseCode = HttpServletResponse.SC_BAD_REQUEST, description = "Missing or invalid parameters") })
public Response getNewConflicts(@FormParam("metadata") String metadata) throws NotFoundException {
    if (StringUtils.isBlank(metadata)) {
        logger.warn("Metadata is not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }/*  w w w  . ja v a 2  s  .co  m*/

    JSONObject metadataJson;
    try {
        metadataJson = (JSONObject) parser.parse(metadata);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }

    String device;
    String startDate;
    String endDate;
    try {
        device = (String) metadataJson.get("device");
        startDate = (String) metadataJson.get("start");
        endDate = (String) metadataJson.get("end");
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }

    if (StringUtils.isBlank(device) || StringUtils.isBlank(startDate) || StringUtils.isBlank(endDate)) {
        logger.warn("Either device, start date or end date were not specified");
        return Response.status(Status.BAD_REQUEST).build();
    }

    Date start;
    try {
        start = new Date(DateTimeSupport.fromUTC(startDate));
    } catch (Exception e) {
        logger.warn("Unable to parse start date {}", startDate);
        return RestUtil.R.badRequest("Unable to parse start date");
    }

    Date end;
    try {
        end = new Date(DateTimeSupport.fromUTC(endDate));
    } catch (Exception e) {
        logger.warn("Unable to parse end date {}", endDate);
        return RestUtil.R.badRequest("Unable to parse end date");
    }

    String rrule = (String) metadataJson.get("rrule");

    String timezone = null;
    String durationString = null;
    if (StringUtils.isNotEmpty(rrule)) {
        try {
            RRule rule = new RRule(rrule);
            rule.validate();
        } catch (Exception e) {
            logger.warn("Unable to parse rrule {}: {}", rrule, e.getMessage());
            return Response.status(Status.BAD_REQUEST).build();
        }

        durationString = (String) metadataJson.get("duration");
        if (StringUtils.isBlank(durationString)) {
            logger.warn("If checking recurrence, must include duration.");
            return Response.status(Status.BAD_REQUEST).build();
        }

        Agent agent = getCaptureAgentStateService().getAgent(device);
        timezone = agent.getConfiguration().getProperty("capture.device.timezone");
        if (StringUtils.isBlank(timezone)) {
            timezone = TimeZone.getDefault().getID();
            logger.warn(
                    "No 'capture.device.timezone' set on agent {}. The default server timezone {} will be used.",
                    device, timezone);
        }
    }

    try {
        DublinCoreCatalogList events = null;
        if (StringUtils.isNotEmpty(rrule)) {
            events = getSchedulerService().findConflictingEvents(device, rrule, start, end,
                    Long.parseLong(durationString), timezone);
        } else {
            events = getSchedulerService().findConflictingEvents(device, start, end);
        }
        if (!events.getCatalogList().isEmpty()) {
            List<JValue> eventsJSON = new ArrayList<JValue>();
            for (DublinCoreCatalog event : events.getCatalogList()) {
                eventsJSON.add(j(f("time", v(event.getFirst(DublinCoreCatalog.PROPERTY_TEMPORAL))),
                        f("title", v(event.getFirst(DublinCoreCatalog.PROPERTY_TITLE)))));
            }

            return conflictJson(a(eventsJSON));
        } else {
            return Response.noContent().build();
        }
    } catch (Exception e) {
        logger.error("Unable to find conflicting events for {}, {}, {}: {}",
                new String[] { device, startDate, endDate, ExceptionUtils.getStackTrace(e) });
        return RestUtil.R.serverError();
    }
}