List of usage examples for org.apache.commons.httpclient HttpStatus SC_CONFLICT
int SC_CONFLICT
To view the source code for org.apache.commons.httpclient HttpStatus SC_CONFLICT.
Click Source Link
From source file:org.artifactory.repo.webdav.WebdavServiceImpl.java
@Override public void handleMkcol(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException { RepoPath repoPath = request.getRepoPath(); String repoKey = request.getRepoKey(); LocalRepo repo = repoService.localOrCachedRepositoryByKey(repoKey); if (repo == null) { response.sendError(HttpStatus.SC_NOT_FOUND, "Could not find repo '" + repoKey + "'.", log); return;/*from www.ja va 2 s . c o m*/ } //Return 405 if called on root or the folder already exists String path = repoPath.getPath(); if (StringUtils.isBlank(path) || repo.itemExists(path)) { response.sendError(HttpStatus.SC_METHOD_NOT_ALLOWED, "MKCOL can only be executed on non-existent resource: " + repoPath, log); return; } //Check that we are allowed to write try { // Servlet container doesn't support long values so we take it manually from the header String contentLengthHeader = request.getHeader("Content-Length"); long contentLength = StringUtils.isBlank(contentLengthHeader) ? -1 : Long.parseLong(contentLengthHeader); repoService.assertValidDeployPath(repo, path, contentLength); } catch (RepoRejectException rre) { response.sendError(rre.getErrorCode(), rre.getMessage(), log); return; } // make sure the parent exists VfsFolder parentFolder = repo.getMutableFolder(repoPath.getParent()); if (parentFolder == null) { response.sendError(HttpStatus.SC_CONFLICT, "Directory cannot be created: parent doesn't exist: " + repoPath.getParent(), log); return; } repo.createOrGetFolder(repoPath); response.setStatus(HttpStatus.SC_CREATED); }
From source file:org.artifactory.request.ResponseStatusCodesMapper.java
public int getStatusCode(Throwable e) { if (e instanceof BadPomException) { return HttpStatus.SC_CONFLICT; } else if (e instanceof DoesNotExistException) { return HttpStatus.SC_NOT_FOUND; } else if (e instanceof ItemNotFoundRuntimeException) { return HttpStatus.SC_BAD_REQUEST; } else if (e instanceof RepoRejectException) { return ((RepoRejectException) e).getErrorCode(); } else if (e instanceof IllegalArgumentException) { return HttpStatus.SC_BAD_REQUEST; }//from w ww . j a v a2 s. c om return HttpStatus.SC_INTERNAL_SERVER_ERROR; }
From source file:org.collectionspace.chain.csp.webui.authorities.AuthoritiesVocabulariesInitialize.java
public void fillVocab(Storage storage, Record thisr, Instance instance, StringBuffer tty, Option[] allOpts, Boolean appendit)// ww w.j a v a2s.com throws UIException, ExistException, UnimplementedException, UnderlyingStorageException, JSONException { // // step away if we have nothing to add // if (allOpts != null && allOpts.length > 0) { // get list from Service layer JSONObject results = new JSONObject(); Integer pageNum = 0; Integer pageSize = 0; // Setting the pageSize to 0 means the Services layer will return ALL the terms in one request. // The "paging" code here is broken. It's made some false assumptions about the order in which terms are returned from the Services layer. // In short, setting the pageSize to 0 is a workaround to the bugs in the paging code. JSONObject fulldata = list_vocab(results, instance, storage, null, pageSize, pageNum, thisr); while (!fulldata.isNull("pagination")) { Integer total = fulldata.getJSONObject("pagination").getInt("totalItems"); pageSize = fulldata.getJSONObject("pagination").getInt("pageSize"); Integer itemsInPage = fulldata.getJSONObject("pagination").getInt("itemsInPage"); pageNum = fulldata.getJSONObject("pagination").getInt("pageNum"); results = fulldata.getJSONObject("shortIdentifiers"); pageNum++; // are there more results if (total > (pageSize * (pageNum))) { fulldata = list_vocab(results, instance, storage, null, pageSize, pageNum, thisr); } else { break; } } // compare results = fulldata.getJSONObject("shortIdentifiers"); for (Option opt : allOpts) { String name = opt.getName(); String shortIdentifier = opt.getID(); if (shortIdentifier == null || shortIdentifier.equals("")) { shortIdentifier = name.trim().replaceAll("\\W", "").toLowerCase(); } if (!results.has(shortIdentifier)) { // create it if term is not already present JSONObject data = new JSONObject(); data.put("displayName", name); data.put("description", opt.getDesc()); data.put("shortIdentifier", shortIdentifier); if (thisr.getFieldFullList("termStatus") instanceof Field) { data.put("termStatus", ((Field) thisr.getFieldFullList("termStatus")).getOptionDefault()); } String url = thisr.getID() + "/" + instance.getTitleRef(); failedPosts++; // assume we're going to fail and an exception will be thrown try { storage.autocreateJSON(url, data, null); failedPosts--; // we succeeded so we can remove our assumed failure if (tty != null) { String msg = String.format("Added term %s:'%s' with short ID='%s'.", instance.getTitleRef(), name, shortIdentifier); tty.append(msg + '\n'); log.info(msg); } } catch (UnderlyingStorageException e) { if (e.getStatus() == HttpStatus.SC_CONFLICT) { log.error( "Terms must have unique short identifiers. The CollectionSpace administrator needs to change the non-unique short identifier and restart CollectionSpace."); String msg = String.format( "CollectionSpace attempted to create the term %s:'%s' using a non-unique short identifier of '%s'.", instance.getTitleRef(), name, shortIdentifier); log.error(msg); log.error(String.format("Failed JSON payload:%s", data.toString())); } else { throw e; } } } else { // remove from results so can delete everything else if // necessary in next stage // though has issues with duplicates results.remove(shortIdentifier); String msg = String.format( "Tried to create term %s:'%s' with short ID='%s', but a term with that short ID already exists.", instance.getTitleRef(), name, shortIdentifier); log.debug(msg); } } if (!appendit) { // delete everything that is not in options Iterator<String> rit = results.keys(); while (rit.hasNext()) { String key = rit.next(); String csid = results.getString(key); failedPosts++; // assume we're going to fail and an exception will be thrown storage.deleteJSON(thisr.getID() + "/" + instance.getTitleRef() + "/" + csid); failedPosts--; // we succeeded so remove our assumed failure if (tty != null) { log.info("Deleting term " + key); tty.append("Deleting term " + key + '\n'); } } } } }
From source file:org.collectionspace.chain.csp.webui.misc.WebReset.java
private boolean initialiseAll(Storage storage, UIRequest request, String path, boolean modifyResponse) throws UIException { StringBuffer responseMessage = new StringBuffer(); boolean initializationFailed = false; boolean initializationUnknown = false; try {// w w w . ja va 2 s . c o m logInitMessage(responseMessage, "Initializing vocab/auth entries...", modifyResponse); JSONObject myjs = new JSONObject(); myjs.put("pageSize", "10"); myjs.put("pageNum", "0"); JSONObject data = storage.getPathsJSON("/", null); String[] paths = (String[]) data.get("listItems"); for (String dir : paths) { try { if (this.spec.hasRecord(dir)) { Record record = this.spec.getRecord(dir); if (record.isType("authority") == true) { for (Instance instance : record.getAllInstances()) { if (instance.getCreateUnreferenced() || isInstanceReferenced(instance)) { avi = new AuthoritiesVocabulariesInitialize(instance, populate, modifyResponse); Option[] allOpts = instance.getAllOptions(); boolean creatingTerm = false; try { if (avi.createIfMissingAuthority(storage, responseMessage, record, instance) == -1) { log.warn(String.format( "The currently authenticated user does not have sufficient permission to determine if the '%s' authority/term-list is properly initialized.", instance.getID())); initializationUnknown = true; // since the logged in user doesn't have the correct perms, we can't verify that the authorities and term lists have been properly initialized } else { // // Create the missing items. // creatingTerm = true; avi.fillVocab(storage, record, instance, responseMessage, allOpts, true); } } catch (UnderlyingStorageException e) { if (e.getStatus() == HttpStatus.SC_CONFLICT) { // This means the authority/vocabulary instance already exists in the backend, so move on to the next instance. log.warn(String.format( "A short ID for the authority/vocabulary instance '%s' already exists.", instance.getID())); continue; // Not a fatal error. } else { throw e; } } catch (Exception e) { if (avi.success() == false) { initializationFailed = true; } throw e; } } else { logInitMessage(responseMessage, "Instance " + instance.getID() + " is defined by not referenced.", modifyResponse); } } } } } catch (UnderlyingStorageException e) { // // If we get here, the system is either in an unknown or incomplete initialization state. If it's incomplete, we'll put up // a message. // if (e.getCause() instanceof ConnectionException) { if (initializationFailed == true) { modifyResponse = true; if (e.getStatus() == HttpStatus.SC_UNAUTHORIZED || e.getStatus() == HttpStatus.SC_FORBIDDEN) { logInitMessage(responseMessage, "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: The CollectionSpace administrator needs to login to the correct tenant and initialize the default term lists and authorities.\n\n", modifyResponse); } else { logInitMessage(responseMessage, "\nSummary:\n\t*** ERROR *** CollectionSpace has not been properly initialized: Ask the CollectionSpace administrator to login to the correct tenant and initialize the default term lists and authorities.\n\n", modifyResponse); } } else if (initializationUnknown == true) { log.warn( "The currently logged in user does not have the correct permissions to determin whether or not the default authorities and term lists have been properly initialized."); } else { throw e; // Should never get here unless we've got a bug in our code } } logException(e, responseMessage, modifyResponse); break; // no need to continue if the user hasn't authenticated or has incorrect permissions } } } catch (ExistException e) { logInitMessage(responseMessage, "ExistException " + e.getLocalizedMessage(), modifyResponse); throw new UIException("Existence problem", e); } catch (UnimplementedException e) { logInitMessage(responseMessage, "UnimplementedException " + e.getLocalizedMessage(), modifyResponse); throw new UIException("Unimplemented ", e); } catch (UnderlyingStorageException x) { if (x.getStatus() == HttpStatus.SC_UNAUTHORIZED) { initializationFailed = true; logInitMessage(responseMessage, "\n*** ERROR *** You need to be logged in to the correct tenant with the proper credentials before attempting to initialize the default term lists and authorities.\n", modifyResponse); logException(x, responseMessage, modifyResponse); } else { logInitMessage(responseMessage, "UnderlyingStorageException " + x.getLocalizedMessage(), modifyResponse); throw new UIException("Problem storing:" + x.getLocalizedMessage(), x.getStatus(), x.getUrl(), x); } } catch (JSONException e) { logInitMessage(responseMessage, "JSONException " + e.getLocalizedMessage(), modifyResponse); throw new UIException("Invalid JSON", e); } // // If the caller is requesting we add our messages to the HTTP request response, then create a // TTY out instance and add our messages. // if (modifyResponse == true && request != null) { TTYOutputter tty = request.getTTYOutputter(); tty.line(responseMessage.toString()); } return !initializationFailed; // report success if we didn't see a failure }
From source file:org.eclipsecon.e4rover.client.PlayersQueueView.java
@PostConstruct public void init() { text = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.BORDER); GridDataFactory.defaultsFor(text).span(2, 1).applyTo(text); new Label(parent, SWT.NONE).setText("Player Key:"); keyText = new Text(parent, SWT.SINGLE | SWT.BORDER); keyText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { preferences.put("PLAYER_KEY", keyText.getText()); }/*from ww w . j ava 2s .co m*/ }); Composite buttonComposite = new Composite(parent, SWT.NONE); buttonComposite.setLayout(new GridLayout(2, false)); buttonComposite.setLayoutData(new GridData(SWT.BEGINNING, SWT.BEGINNING, false, false, 2, 1)); final Button enqueue = new Button(buttonComposite, SWT.PUSH); enqueue.setText("Request Control"); enqueue.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { platform.enterPlayerQueue(keyText.getText()); } catch (RobotServerException rse) { if (rse.getResponseCode() == HttpStatus.SC_CONFLICT) { statusReporter.get().show(StatusReporter.ERROR, "Player queue full! Please try again later.", null); } else { statusReporter.get().show(StatusReporter.ERROR, "An error occurred when requesting control", rse); } } catch (IOException e1) { statusReporter.get().show(StatusReporter.ERROR, "An error occurred when requesting control", e1); } } }); final Button dequeue = new Button(buttonComposite, SWT.PUSH); dequeue.setText("Leave Queue"); dequeue.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { try { platform.leavePlayerQueue(keyText.getText()); } catch (IOException e1) { statusReporter.get().show(StatusReporter.ERROR, "An error occurred when leaving queue", e1); } } }); GridLayoutFactory.fillDefaults().numColumns(2).generateLayout(parent); }
From source file:org.eclipsecon.e4rover.client.production.ProductionServer.java
public void setWheelVelocity(int leftWheel, int rightWheel, String playerKey) throws IOException, NotYourTurnException { final PostMethod post = new PostMethod(IServerConstants.COMMAND_RESTLET_URI + playerKey); try {//from w ww. j av a 2s . c o m String command = leftWheel + "," + rightWheel; //TODO replace with constants post.setRequestEntity(new StringRequestEntity(command, "text/xml", "UTF-8")); int resp = httpClient.executeMethod(post); if (resp == HttpStatus.SC_CONFLICT) { throw new NotYourTurnException(post.getResponseBodyAsString()); } else if (resp != HttpStatus.SC_OK) { throw new RobotServerException(resp, post.getURI(), post.getResponseBodyAsString()); } } finally { post.releaseConnection(); } }
From source file:org.hydracache.client.partition.Messager.java
private void registerDefaultHandlers() { transport.registerHandler(HttpStatus.SC_CONFLICT, new ConflictStatusHandler()); transport.registerHandler(HttpStatus.SC_OK, new DefaultResponseMessageHandler()); transport.registerHandler(HttpStatus.SC_CREATED, new DefaultResponseMessageHandler()); }
From source file:org.hydracache.client.transport.ConflictStatusHandler.java
@Override public ResponseMessage accept(int responseCode, byte[] responseBody) throws Exception { if (responseCode == HttpStatus.SC_CONFLICT) { throw new VersionConflictException("Version conflict detected, please refresh your local cache."); }/*from w w w. j a v a2s.c o m*/ return null; }
From source file:org.opens.tanaguru.util.http.HttpRequestHandler.java
private int computeStatus(int status) { switch (status) { case HttpStatus.SC_FORBIDDEN: case HttpStatus.SC_METHOD_NOT_ALLOWED: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_UNAUTHORIZED: case HttpStatus.SC_PAYMENT_REQUIRED: case HttpStatus.SC_NOT_FOUND: case HttpStatus.SC_NOT_ACCEPTABLE: case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED: case HttpStatus.SC_REQUEST_TIMEOUT: case HttpStatus.SC_CONFLICT: case HttpStatus.SC_GONE: case HttpStatus.SC_LENGTH_REQUIRED: case HttpStatus.SC_PRECONDITION_FAILED: case HttpStatus.SC_REQUEST_TOO_LONG: case HttpStatus.SC_REQUEST_URI_TOO_LONG: case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE: case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE: case HttpStatus.SC_EXPECTATION_FAILED: case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE: case HttpStatus.SC_METHOD_FAILURE: case HttpStatus.SC_UNPROCESSABLE_ENTITY: case HttpStatus.SC_LOCKED: case HttpStatus.SC_FAILED_DEPENDENCY: case HttpStatus.SC_INTERNAL_SERVER_ERROR: case HttpStatus.SC_NOT_IMPLEMENTED: case HttpStatus.SC_BAD_GATEWAY: case HttpStatus.SC_SERVICE_UNAVAILABLE: case HttpStatus.SC_GATEWAY_TIMEOUT: case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED: case HttpStatus.SC_INSUFFICIENT_STORAGE: return 0; case HttpStatus.SC_CONTINUE: case HttpStatus.SC_SWITCHING_PROTOCOLS: case HttpStatus.SC_PROCESSING: case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION: case HttpStatus.SC_NO_CONTENT: case HttpStatus.SC_RESET_CONTENT: case HttpStatus.SC_PARTIAL_CONTENT: case HttpStatus.SC_MULTI_STATUS: case HttpStatus.SC_MULTIPLE_CHOICES: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_NOT_MODIFIED: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_TEMPORARY_REDIRECT: return 1; default:/*from w w w . j a va 2 s .co m*/ return 1; } }
From source file:org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService.java
@Path("/push_temperature") @POST/* ww w. j a va 2 s .c o m*/ @Consumes(MediaType.APPLICATION_JSON) public void pushTemperatureData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { boolean result; String deviceId = dataMsg.deviceId; String deviceIp = dataMsg.reply; String temperature = dataMsg.value; String registeredIp = deviceToIpMap.get(deviceId); if (registeredIp == null) { log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp + " for device ID - " + deviceId); response.setStatus(HttpStatus.SC_PRECONDITION_FAILED); return; } else if (!registeredIp.equals(deviceIp)) { log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId + " is already registered under some other IP. Re-registration " + "required"); response.setStatus(HttpStatus.SC_CONFLICT); return; } try { DeviceController deviceController = new DeviceController(); result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", temperature, DataStreamDefinitions.StreamTypeLabel.TEMPERATURE); if (!result) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (UnauthorizedException e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); log.error("Data Push Attempt Failed for BAM Publisher: " + e.getMessage()); } try { DeviceController deviceController = new DeviceController(); result = deviceController.pushCepData(dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId, System.currentTimeMillis(), "DeviceData", temperature, DataStreamDefinitions.StreamTypeLabel.TEMPERATURE); if (!result) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); } } catch (UnauthorizedException e) { response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); log.error("Data Push Attempt Failed for CEP Publisher: " + e.getMessage()); } }