List of usage examples for javax.servlet.http HttpServletResponse SC_CONFLICT
int SC_CONFLICT
To view the source code for javax.servlet.http HttpServletResponse SC_CONFLICT.
Click Source Link
From source file:org.opendatakit.aggregate.externalservice.GoogleMapsEngine.java
private String executeGMEStmt(String method, String statement, CallingContext cc) throws ServiceException, IOException, ODKExternalServiceException, GeneralSecurityException { if (statement == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new ODKExternalServiceException(NO_BODY_ERROR); } else if (statement != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) { throw new ODKExternalServiceException(BODY_SUPPLIED_ERROR); }//from w ww . ja v a 2s.c o m HttpContent entity = null; if (statement != null) { // the alternative -- using ContentType.create(,) throws an exception??? // entity = new StringEntity(statement, "application/json", UTF_8); // NOTE: by using HtmlConsts versus "application/json" we now include the // UTF-8 in the type // could cause problems so place to look for error entity = new ByteArrayContent(HtmlConsts.RESP_TYPE_JSON, statement.getBytes(HtmlConsts.UTF8_ENCODE)); } HttpRequest request = requestFactory.buildRequest(method, generateGmeUrl(), entity); request.setThrowExceptionOnExecuteError(false); HttpResponse resp = request.execute(); String response = WebUtils.readGoogleResponse(resp); int statusCode = resp.getStatusCode(); switch (statusCode) { case HttpServletResponse.SC_CONFLICT: logger.warn("GME CONFLICT DETECTED" + response + statement); case HttpServletResponse.SC_OK: case HttpServletResponse.SC_NO_CONTENT: return response; case HttpServletResponse.SC_FORBIDDEN: case HttpServletResponse.SC_UNAUTHORIZED: throw new ODKExternalServiceCredentialsException(response + statement); default: throw new ODKExternalServiceException(response + statement); } }
From source file:org.dasein.cloud.rackspace.network.CloudLoadBalancers.java
@Override public void remove(String loadBalancerId) throws CloudException, InternalException { Logger logger = RackspaceCloud.getLogger(CloudLoadBalancers.class, "std"); if (logger.isTraceEnabled()) { logger.trace("enter - " + CloudLoadBalancers.class.getName() + ".remove(" + loadBalancerId + ")"); }/*from ww w. j a va 2s. c o m*/ try { RackspaceMethod method = new RackspaceMethod(provider); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteLoadBalancers("/loadbalancers", loadBalancerId); return; } catch (RackspaceException e) { if (e.getHttpCode() != HttpServletResponse.SC_CONFLICT || e.getHttpCode() == 422) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch (InterruptedException e) { } } while (System.currentTimeMillis() < timeout); } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + CloudLoadBalancers.class.getName() + ".remove()"); } } }
From source file:org.dasein.cloud.rackspace.compute.CloudServers.java
@Override public void terminate(@Nonnull String vmId) throws InternalException, CloudException { Logger std = RackspaceCloud.getLogger(CloudServers.class, "std"); if (std.isTraceEnabled()) { std.trace("enter - " + CloudServers.class.getName() + ".terminate(" + vmId + ")"); }//from ww w. jav a 2 s .c o m try { RackspaceMethod method = new RackspaceMethod(provider); long timeout = System.currentTimeMillis() + CalendarWrapper.HOUR; do { try { method.deleteServers("/servers", vmId); return; } catch (RackspaceException e) { if (e.getHttpCode() != HttpServletResponse.SC_CONFLICT) { throw e; } } try { Thread.sleep(CalendarWrapper.MINUTE); } catch (InterruptedException e) { /* ignore */ } } while (System.currentTimeMillis() < timeout); } finally { if (std.isTraceEnabled()) { std.trace("exit - " + CloudServers.class.getName() + ".terminate()"); } } }
From source file:edu.slu.action.ObjectAction.java
/** * Internal helper method to update the history.previous property of a root object. This will occur because a new root object can be created * by put_update.action on an external object. It must mark itself as root and contain the original ID for the object in history.previous. * This method only receives reliable objects from mongo. * //from w w w . j a v a2 s. c o m * @param newRootObj the RERUM object whose history.previous needs to be updated * @param externalObjID the @id of the external object to go into history.previous * @return JSONObject of the provided object with the history.previous alteration */ private JSONObject alterHistoryPrevious(JSONObject newRootObj, String externalObjID) { DBObject myAnnoWithHistoryUpdate; DBObject myAnno = (BasicDBObject) JSON.parse(newRootObj.toString()); try { newRootObj.getJSONObject("__rerum").getJSONObject("history").element("previous", externalObjID); //write back to the anno from mongo myAnnoWithHistoryUpdate = (DBObject) JSON.parse(newRootObj.toString()); //make the JSONObject a DB object mongoDBService.update(Constant.COLLECTION_ANNOTATION, myAnno, myAnnoWithHistoryUpdate); //update in mongo } catch (Exception e) { writeErrorResponse( "This object does not contain the proper history property. It may not be from RERUM, the update failed.", HttpServletResponse.SC_CONFLICT); } return newRootObj; }
From source file:org.dspace.app.dav.DAVResource.java
/** * Propfind crawler.//w w w . ja va 2s . c om * * @param multistatus the multistatus * @param pfType the pf type * @param pfProps the pf props * @param depth the depth * @param typeMask the type mask * @param count the count * * @return the int * * @throws DAVStatusException the DAV status exception * @throws SQLException the SQL exception * @throws AuthorizeException the authorize exception * @throws IOException Signals that an I/O exception has occurred. */ private int propfindCrawler(Element multistatus, int pfType, List<Element> pfProps, int depth, int typeMask, int count) throws DAVStatusException, SQLException, AuthorizeException, IOException { if ((this.type & typeMask) != 0 || this.type == TYPE_OTHER) { // check the count of resources visited ++count; if (propfindResourceLimit > 0 && count > propfindResourceLimit) { throw new DAVStatusException(HttpServletResponse.SC_CONFLICT, "PROPFIND request exceeded server's limit on number of resources to query."); } String uri = hrefURL(); log.debug("PROPFIND returning (count=" + String.valueOf(count) + ") href=" + uri); List<Element> notFound = new ArrayList<Element>(); List<Element> forbidden = new ArrayList<Element>(); Element responseElt = new Element("response", DAV.NS_DAV); multistatus.addContent(responseElt); Element href = new Element("href", DAV.NS_DAV); href.setText(uri); responseElt.addContent(href); // just get the names if (pfType == DAV.PROPFIND_PROPNAME) { responseElt.addContent( makePropstat(copyElementList(getAllProperties()), HttpServletResponse.SC_OK, "OK")); } else { List<Element> success = new LinkedList<Element>(); List<Element> props = (pfType == DAV.PROPFIND_ALLPROP) ? getAllProperties() : pfProps; ListIterator pi = props.listIterator(); while (pi.hasNext()) { Element property = (Element) pi.next(); try { Element value = propfindInternal(property); if (value != null) { success.add(value); } else { notFound.add((Element) property.clone()); } } catch (DAVStatusException se) { if (se.getStatus() == HttpServletResponse.SC_NOT_FOUND) { notFound.add((Element) property.clone()); } else { responseElt.addContent( makePropstat((Element) property.clone(), se.getStatus(), se.getMessage())); } } catch (AuthorizeException ae) { forbidden.add((Element) property.clone()); } } if (success.size() > 0) { responseElt.addContent(makePropstat(success, HttpServletResponse.SC_OK, "OK")); } if (notFound.size() > 0) { responseElt.addContent(makePropstat(notFound, HttpServletResponse.SC_NOT_FOUND, "Not found")); } if (forbidden.size() > 0) { responseElt.addContent( makePropstat(forbidden, HttpServletResponse.SC_FORBIDDEN, "Not authorized.")); } } } // recurse on children; filter on types first. // child types are all lower bits than this type, so (type - 1) is // bit-mask of all the possible child types. Skip recursion if // all child types would be masked out anyway. if (depth != 0 && ((this.type - 1) & typeMask) != 0) { DAVResource[] kids = children(); for (DAVResource element : kids) { count = element.propfindCrawler(multistatus, pfType, pfProps, depth == DAV.DAV_INFINITY ? depth : depth - 1, typeMask, count); } } return count; }
From source file:org.eclipse.packagedrone.repo.channel.web.channel.ChannelController.java
@RequestMapping(value = "/channel/{channelId}/drop", method = RequestMethod.POST) public void drop(@PathVariable("channelId") final String channelId, @RequestParameter(required = false, value = "name") String name, final @RequestParameter("file") Part file, final HttpServletResponse response) throws IOException { response.setContentType("text/plain"); try {/*from w ww . j a v a2s . c o m*/ if (name == null || name.isEmpty()) { name = file.getSubmittedFileName(); } final String finalName = name; this.channelService.accessRun(By.id(channelId), ModifiableChannel.class, channel -> { channel.getContext().createArtifact(file.getInputStream(), finalName, null); }); } catch (final Throwable e) { logger.warn("Failed to drop file", e); final Throwable cause = ExceptionHelper.getRootCause(e); if (cause instanceof VetoArtifactException) { response.setStatus(HttpServletResponse.SC_CONFLICT); response.getWriter().format("Artifact rejected! %s", ((VetoArtifactException) cause).getVetoMessage().orElse("No details given")); } else { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.getWriter().format("Internal error! %s", ExceptionHelper.getMessage(cause)); } return; } response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("OK"); }
From source file:edu.slu.action.ObjectAction.java
/** * Internal helper method to update the history.next property of an object. This will occur because updateObject will create a new object from a given object, and that * given object will have a new next value of the new object. Watch out for missing __rerum or malformed __rerum.history * /*ww w. j a v a 2 s . co m*/ * @param idForUpdate the @id of the object whose history.next needs to be updated * @param newNextID the @id of the newly created object to be placed in the history.next array. * @return Boolean altered true on success, false on fail */ private boolean alterHistoryNext(String idForUpdate, String newNextID) { //TODO @theHabes As long as we trust the objects we send to this, we can take out the lookup and pass in objects as parameters System.out.println("Trying to alter history..."); Boolean altered = false; BasicDBObject query = new BasicDBObject(); query.append("@id", idForUpdate); DBObject myAnno = mongoDBService.findOneByExample(Constant.COLLECTION_ANNOTATION, query); DBObject myAnnoWithHistoryUpdate; JSONObject annoToUpdate = JSONObject.fromObject(myAnno); if (null != myAnno) { try { annoToUpdate.getJSONObject("__rerum").getJSONObject("history").getJSONArray("next").add(newNextID); //write back to the anno from mongo myAnnoWithHistoryUpdate = (DBObject) JSON.parse(annoToUpdate.toString()); //make the JSONObject a DB object System.out.println("Update in Mongo"); mongoDBService.update(Constant.COLLECTION_ANNOTATION, myAnno, myAnnoWithHistoryUpdate); //update in mongo System.out.println("Done"); altered = true; } catch (Exception e) { //@cubap @theHabes #44. What if obj does not have __rerum or __rerum.history System.out.println("This object did not have a propery history..."); writeErrorResponse( "This object does not contain the proper history property. It may not be from RERUM, the update failed.", HttpServletResponse.SC_CONFLICT); } } else { //THIS IS A 404 System.out.println("Couldnt find the object to alter history..."); writeErrorResponse("Object for update not found...", HttpServletResponse.SC_NOT_FOUND); } return altered; }
From source file:org.gss_project.gss.server.rest.Webdav.java
@Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return;//ww w . ja v a 2 s . co m } final User user = getUser(req); String path = getRelativePath(req); boolean exists = true; Object resource = null; FileHeader file = null; try { resource = getService().getResourceAtPath(user.getId(), path, true); } catch (ObjectNotFoundException e) { exists = false; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } if (exists) if (resource instanceof FileHeader) file = (FileHeader) resource; else { resp.sendError(HttpServletResponse.SC_CONFLICT); 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_FORBIDDEN); return; } resourceInputStream = new FileInputStream(contentFile); } else resourceInputStream = req.getInputStream(); try { Object parent = getService().getResourceAtPath(user.getId(), getParentPath(path), true); if (!(parent instanceof Folder)) { resp.sendError(HttpServletResponse.SC_CONFLICT); return; } final Folder folderLocal = (Folder) parent; final String name = getLastElement(path); final String mimeType = getServletContext().getMimeType(name); File uploadedFile = null; try { uploadedFile = getService().uploadFile(resourceInputStream, user.getId()); } catch (IOException ex) { throw new GSSIOException(ex, false); } // FIXME: Add attributes FileHeader fileLocal = null; final FileHeader f = file; final File uf = uploadedFile; if (exists) fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().updateFileContents(user.getId(), f.getId(), mimeType, uf.length(), uf.getAbsolutePath()); } }); else fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() { @Override public FileHeader call() throws Exception { return getService().createFile(user.getId(), folderLocal.getId(), name, mimeType, uf.length(), uf.getAbsolutePath()); } }); updateAccounting(user, new Date(), fileLocal.getCurrentBody().getFileSize()); } catch (ObjectNotFoundException e) { result = false; } catch (InsufficientPermissionsException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } catch (QuotaExceededException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } catch (GSSIOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (RpcException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path); return; } catch (DuplicateNameException e) { resp.sendError(HttpServletResponse.SC_CONFLICT); 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:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java
@RequestMapping(method = RequestMethod.PUT, value = "/monitorroute/{clientId}") public @ResponseBody RouteMonitoring updateMonitorRoutes(HttpServletResponse response, @RequestBody(required = false) RouteMonitoring req, @PathVariable String clientId) throws Exception { try {/* ww w . j a v a2 s . co m*/ String userId = getUserId(); if (userId == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } String objectClientId = req.getClientId(); if (!clientId.equals(objectClientId)) { response.setStatus(HttpServletResponse.SC_CONFLICT); return null; } Map<String, Object> pars = new TreeMap<String, Object>(); pars.put("clientId", req.getClientId()); RouteMonitoringObject res = domainStorage.searchDomainObject(pars, RouteMonitoringObject.class); if (res != null) { if (!userId.equals(res.getUserId())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } } RouteMonitoringObject obj = new RouteMonitoringObject(req); obj.setUserId(userId); domainStorage.saveRouteMonitoring(obj); return req; } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return null; } }
From source file:org.apache.archiva.webdav.ArchivaDavResourceFactory.java
private DavResource processRepository(final DavServletRequest request, ArchivaDavResourceLocator archivaLocator, String activePrincipal, ManagedRepositoryContent managedRepositoryContent, ManagedRepository managedRepository) throws DavException { DavResource resource = null;//from w w w . j a v a 2s . c om if (isAuthorized(request, managedRepositoryContent.getId())) { boolean readMethod = WebdavMethodUtil.isReadMethod(request.getMethod()); // Maven Centric part ask evaluation if -SNAPSHOT // MRM-1846 test if read method to prevent issue with maven 2.2.1 and uniqueVersion false String path = readMethod ? evaluatePathWithVersion(archivaLocator, managedRepositoryContent, request.getContextPath()) : getLogicalResource(archivaLocator, managedRepository, false); if (path.startsWith("/")) { path = path.substring(1); } LogicalResource logicalResource = new LogicalResource(path); File resourceFile = new File(managedRepositoryContent.getRepoRoot(), path); resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), path, managedRepositoryContent.getRepository(), request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager); if (WebdavMethodUtil.isReadMethod(request.getMethod())) { if (archivaLocator.getHref(false).endsWith("/") && !resourceFile.isDirectory()) { // force a resource not found throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Resource does not exist"); } else { if (!resource.isCollection()) { boolean previouslyExisted = resourceFile.exists(); boolean fromProxy = fetchContentFromProxies(managedRepositoryContent, request, logicalResource); // At this point the incoming request can either be in default or // legacy layout format. try { // Perform an adjustment of the resource to the managed // repository expected path. String localResourcePath = repositoryRequest.toNativePath(logicalResource.getPath(), managedRepositoryContent); resourceFile = new File(managedRepositoryContent.getRepoRoot(), localResourcePath); resource = new ArchivaDavResource(resourceFile.getAbsolutePath(), logicalResource.getPath(), managedRepositoryContent.getRepository(), request.getRemoteAddr(), activePrincipal, request.getDavSession(), archivaLocator, this, mimeTypes, auditListeners, scheduler, fileLockManager); } catch (LayoutException e) { if (!resourceFile.exists()) { throw new DavException(HttpServletResponse.SC_NOT_FOUND, e); } } if (fromProxy) { String action = (previouslyExisted ? AuditEvent.MODIFY_FILE : AuditEvent.CREATE_FILE) + PROXIED_SUFFIX; log.debug("Proxied artifact '{}' in repository '{}' (current user '{}')", resourceFile.getName(), managedRepositoryContent.getId(), activePrincipal); triggerAuditEvent(request.getRemoteAddr(), archivaLocator.getRepositoryId(), logicalResource.getPath(), action, activePrincipal); } if (!resourceFile.exists()) { throw new DavException(HttpServletResponse.SC_NOT_FOUND, "Resource does not exist"); } } } } if (request.getMethod().equals(HTTP_PUT_METHOD)) { String resourcePath = logicalResource.getPath(); // check if target repo is enabled for releases // we suppose that release-artifacts can be deployed only to repos enabled for releases if (managedRepositoryContent.getRepository().isReleases() && !repositoryRequest.isMetadata(resourcePath) && !repositoryRequest.isSupportFile(resourcePath)) { ArtifactReference artifact = null; try { artifact = managedRepositoryContent.toArtifactReference(resourcePath); if (!VersionUtil.isSnapshot(artifact.getVersion())) { // check if artifact already exists and if artifact re-deployment to the repository is allowed if (managedRepositoryContent.hasContent(artifact) && managedRepositoryContent.getRepository().isBlockRedeployments()) { log.warn("Overwriting released artifacts in repository '{}' is not allowed.", managedRepositoryContent.getId()); throw new DavException(HttpServletResponse.SC_CONFLICT, "Overwriting released artifacts is not allowed."); } } } catch (LayoutException e) { log.warn("Artifact path '{}' is invalid.", resourcePath); } } /* * Create parent directories that don't exist when writing a file This actually makes this * implementation not compliant to the WebDAV RFC - but we have enough knowledge about how the * collection is being used to do this reasonably and some versions of Maven's WebDAV don't correctly * create the collections themselves. */ File rootDirectory = new File(managedRepositoryContent.getRepoRoot()); File destDir = new File(rootDirectory, logicalResource.getPath()).getParentFile(); if (!destDir.exists()) { destDir.mkdirs(); String relPath = PathUtil.getRelative(rootDirectory.getAbsolutePath(), destDir); log.debug("Creating destination directory '{}' (current user '{}')", destDir.getName(), activePrincipal); triggerAuditEvent(request.getRemoteAddr(), managedRepositoryContent.getId(), relPath, AuditEvent.CREATE_DIR, activePrincipal); } } } return resource; }