List of usage examples for org.apache.commons.httpclient HttpStatus SC_CREATED
int SC_CREATED
To view the source code for org.apache.commons.httpclient HttpStatus SC_CREATED.
Click Source Link
From source file:org.purl.sword.client.Client.java
/** * Post a file to the server. The different elements of the post are encoded * in the specified message./*from ww w .j ava2 s .co m*/ * * @param message * The message that contains the post information. * * @throws SWORDClientException * if there is an error during the post operation. */ public DepositResponse postFile(PostMessage message) throws SWORDClientException { if (message == null) { throw new SWORDClientException("Message cannot be null."); } PostMethod httppost = new PostMethod(message.getDestination()); if (doAuthentication) { setBasicCredentials(username, password); httppost.setDoAuthentication(true); } DepositResponse response = null; String messageBody = ""; try { if (message.isUseMD5()) { String md5 = ChecksumUtils.generateMD5(message.getFilepath()); if (message.getChecksumError()) { md5 = "1234567890"; } log.debug("checksum error is: " + md5); if (md5 != null) { httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_MD5, md5)); } } String filename = message.getFilename(); if (!"".equals(filename)) { httppost.addRequestHeader(new Header(HttpHeaders.CONTENT_DISPOSITION, " filename=" + filename)); } if (containsValue(message.getSlug())) { httppost.addRequestHeader(new Header(HttpHeaders.SLUG, message.getSlug())); } if (message.getCorruptRequest()) { // insert a header with an invalid boolean value httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, "Wibble")); } else { httppost.addRequestHeader(new Header(HttpHeaders.X_NO_OP, Boolean.toString(message.isNoOp()))); } httppost.addRequestHeader(new Header(HttpHeaders.X_VERBOSE, Boolean.toString(message.isVerbose()))); String packaging = message.getPackaging(); if (packaging != null && packaging.length() > 0) { httppost.addRequestHeader(new Header(HttpHeaders.X_PACKAGING, packaging)); } String onBehalfOf = message.getOnBehalfOf(); if (containsValue(onBehalfOf)) { httppost.addRequestHeader(new Header(HttpHeaders.X_ON_BEHALF_OF, onBehalfOf)); } String userAgent = message.getUserAgent(); if (containsValue(userAgent)) { httppost.addRequestHeader(new Header(HttpHeaders.USER_AGENT, userAgent)); } FileRequestEntity requestEntity = new FileRequestEntity(new File(message.getFilepath()), message.getFiletype()); httppost.setRequestEntity(requestEntity); client.executeMethod(httppost); status = new Status(httppost.getStatusCode(), httppost.getStatusText()); log.info("Checking the status code: " + status.getCode()); if (status.getCode() == HttpStatus.SC_ACCEPTED || status.getCode() == HttpStatus.SC_CREATED) { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.setLocation(httppost.getResponseHeader("Location").getValue()); // added call for the status code. lastUnmarshallInfo = response.unmarshall(messageBody, new Properties()); } else { messageBody = readResponse(httppost.getResponseBodyAsStream()); response = new DepositResponse(status.getCode()); response.unmarshallErrorDocument(messageBody); } return response; } catch (NoSuchAlgorithmException nex) { throw new SWORDClientException("Unable to use MD5. " + nex.getMessage(), nex); } catch (HttpException ex) { throw new SWORDClientException(ex.getMessage(), ex); } catch (IOException ioex) { throw new SWORDClientException(ioex.getMessage(), ioex); } catch (UnmarshallException uex) { throw new SWORDClientException(uex.getMessage() + "(<pre>" + messageBody + "</pre>)", uex); } finally { httppost.releaseConnection(); } }
From source file:org.roda.wui.filter.CasClient.java
/** * Get a <strong>Ticket Granting Ticket</strong> from the CAS server for the * specified <i>username</i> and <i>password</i>. * //w ww. java2 s. co m * @param username * the username. * @param password * the password. * @return the <strong>Ticket Granting Ticket</strong> * @throws AuthenticationDeniedException * if the CAS server rejected the specified credentials. * @throws GenericException * if some error occurred. */ public String getTicketGrantingTicket(final String username, final String password) throws AuthenticationDeniedException, GenericException { final HttpClient client = new HttpClient(); final PostMethod post = new PostMethod(String.format("%s/v1/tickets", this.casServerUrlPrefix)); post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username), new NameValuePair("password", password) }); try { client.executeMethod(post); final String response = post.getResponseBodyAsString(); if (post.getStatusCode() == HttpStatus.SC_CREATED) { final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response); if (matcher.matches()) { return matcher.group(1); } LOGGER.warn(NO_TICKET); throw new GenericException(NO_TICKET); } else if (post.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationDeniedException("Could not create ticket: " + post.getStatusText()); } else { LOGGER.warn(invalidResponseMessage(post)); throw new GenericException(invalidResponseMessage(post)); } } catch (final IOException e) { throw new GenericException(e.getMessage(), e); } finally { post.releaseConnection(); } }
From source file:org.sakaiproject.nakamura.grouper.changelog.util.NakamuraHttpUtils.java
/** * Prepare an HTTP request to Sakai OAE and parse the response (if JSON). * @param client an {@link HttpClient} to execute the request. * @param method an HTTP method to send/*from ww w.ja v a 2s. c om*/ * @return a JSONObject of the response if the request returns JSON * @throws GroupModificationException if there was an error updating the group information. */ public static JSONObject http(HttpClient client, HttpMethod method) throws GroupModificationException { method.setRequestHeader("User-Agent", HTTP_USER_AGENT); method.setRequestHeader("Referer", HTTP_REFERER); String errorMessage = null; String responseString = null; JSONObject responseJSON = null; boolean isJSONRequest = !method.getPath().toString().endsWith(".html"); if (log.isDebugEnabled() && method instanceof PostMethod) { log.debug(method.getName() + " " + method.getPath() + " params:"); for (NameValuePair nvp : ((PostMethod) method).getParameters()) { log.debug(nvp.getName() + " = " + nvp.getValue()); } } int responseCode = -1; try { responseCode = client.executeMethod(method); responseString = StringUtils.trimToNull(IOUtils.toString(method.getResponseBodyAsStream())); if (isJSONRequest) { responseJSON = parseJSONResponse(responseString); } if (log.isDebugEnabled()) { log.debug(responseCode + " " + method.getName() + " " + method.getPath()); } if (log.isTraceEnabled()) { log.trace("reponse: " + responseString); } switch (responseCode) { case HttpStatus.SC_OK: // 200 case HttpStatus.SC_CREATED: // 201 break; case HttpStatus.SC_BAD_REQUEST: // 400 case HttpStatus.SC_UNAUTHORIZED: // 401 case HttpStatus.SC_NOT_FOUND: // 404 case HttpStatus.SC_INTERNAL_SERVER_ERROR: // 500 if (isJSONRequest && responseJSON != null) { errorMessage = responseJSON.getString("status.message"); } if (errorMessage == null) { errorMessage = "Empty " + responseCode + " error. Check the logs on the Sakai OAE server."; } break; default: errorMessage = "Unknown HTTP response " + responseCode; break; } } catch (Exception e) { errorMessage = "An exception occurred communicatingSakai OAE. " + e.toString(); } finally { method.releaseConnection(); } if (errorMessage != null) { log.error(errorMessage); errorToException(responseCode, errorMessage); } return responseJSON; }
From source file:org.socraticgrid.displaycalendarlib.CalendarInit.java
public void makeCalendar(String relativePath) throws IOException { /*//from w w w . j a v a 2 s . co m GoogleCalDavDialect gdialect = new GoogleCalDavDialect(); if (dialect.equals(gdialect.getProdId())) { log.warn("Google Caldav Server doesn't support MKCALENDAR"); return; } */ MkCalendarMethod method = methodFactory.createMkCalendarMethod(); method.setPath(relativePath); executeMethod(HttpStatus.SC_CREATED, method, true); }
From source file:org.socraticgrid.displaycalendarlib.CalendarInit.java
protected void mkcalendar(String path) { MkCalendarMethod mk = new MkCalendarMethod(); mk.setPath(path);/*from w w w . j a va 2s .c o m*/ mk.addDescription("en"); try { executeMethod(HttpStatus.SC_CREATED, mk, true); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.sonatype.nexus.integrationtests.nexus258.Nexus258ReleaseDeployIT.java
@Test public void deploywithGavUsingRest() throws Exception { Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0", null, "xml", 0, new Date().getTime(), "Simple Test Artifact", false, null, false, null); // file to deploy File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension()); // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71 // url to upload to String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content"; int status = getDeployUtils().deployUsingGavWithRest(uploadURL, TEST_RELEASE_REPO, gav, fileToDeploy); if (status != HttpStatus.SC_CREATED) { Assert.fail("File did not upload successfully, status code: " + status); }/*w ww . j a v a 2 s . c o m*/ // download it File artifact = downloadArtifact(gav, "./target/downloaded-jars"); // make sure its here assertTrue(artifact.exists()); // make sure it is what we expect. assertTrue(FileTestingUtils.compareFileSHA1s(fileToDeploy, artifact)); }
From source file:org.sonatype.nexus.integrationtests.nexus258.Nexus258ReleaseDeployIT.java
@Test public void deployWithPomUsingRest() throws Exception { Gav gav = new Gav(this.getTestId(), "uploadWithPom", "1.0.0", null, "xml", 0, new Date().getTime(), "Simple Test Artifact", false, null, false, null); // file to deploy File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension()); File pomFile = this.getTestFile("pom.xml"); // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71 // url to upload to String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content"; int status = getDeployUtils().deployUsingPomWithRest(uploadURL, TEST_RELEASE_REPO, fileToDeploy, pomFile, null, null);//from w w w .j a va 2 s . c o m if (status != HttpStatus.SC_CREATED) { Assert.fail("File did not upload successfully, status code: " + status); } // download it File artifact = downloadArtifact(gav, "./target/downloaded-jars"); // make sure its here assertTrue(artifact.exists()); // make sure it is what we expect. assertTrue(FileTestingUtils.compareFileSHA1s(fileToDeploy, artifact)); }
From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java
@Override public void storeItem(ProxyRepository repository, StorageItem item) throws UnsupportedStorageOperationException, RemoteStorageException { if (!(item instanceof StorageFileItem)) { throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!"); }/* ww w .j a va 2 s . c o m*/ StorageFileItem fItem = (StorageFileItem) item; ResourceStoreRequest request = new ResourceStoreRequest(item); URL remoteURL = getAbsoluteUrlFromBase(repository, request); PutMethod method = new PutMethod(remoteURL.toString()); try { method.setRequestEntity( new InputStreamRequestEntity(fItem.getInputStream(), fItem.getLength(), fItem.getMimeType())); int response = executeMethod(repository, request, method, remoteURL); if (response != HttpStatus.SC_OK && response != HttpStatus.SC_CREATED && response != HttpStatus.SC_NO_CONTENT && response != HttpStatus.SC_ACCEPTED) { throw new RemoteStorageException("Unexpected response code while executing " + method.getName() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]. Expected: \"any success (2xx)\". Received: " + response + " : " + HttpStatus.getStatusText(response)); } } catch (IOException e) { throw new RemoteStorageException( e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]", e); } finally { method.releaseConnection(); } }
From source file:org.wso2.am.integration.tests.other.APIImportExportTestCase.java
/** * Upload a file to the given URL/*from w ww .j a v a2s . c o m*/ * * @param importUrl URL to be file upload * @param fileName Name of the file to be upload * @throws IOException throws if connection issues occurred */ private void importAPI(String importUrl, File fileName, String user, char[] pass) throws IOException { //open import API url connection and deploy the exported API URL url = new URL(importUrl); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); connection.setDoOutput(true); connection.setRequestMethod("POST"); FileBody fileBody = new FileBody(fileName); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.STRICT); multipartEntity.addPart("file", fileBody); connection.setRequestProperty("Content-Type", multipartEntity.getContentType().getValue()); connection.setRequestProperty(APIMIntegrationConstants.AUTHORIZATION_HEADER, "Basic " + encodeCredentials(user, pass)); OutputStream out = connection.getOutputStream(); try { multipartEntity.writeTo(out); } finally { out.close(); } int status = connection.getResponseCode(); BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream())); String temp; StringBuilder response = new StringBuilder(); while ((temp = read.readLine()) != null) { response.append(temp); } Assert.assertEquals(status, HttpStatus.SC_CREATED, "Response code is not as expected : " + response); }
From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java
/** * This Method is used to deploy BPMN packages to the BPMN Server * * @param fileName The name of the Package to be deployed * @param filePath The location of the BPMN package to be deployed * @throws java.io.IOException/* ww w . j a v a2 s. c o m*/ * @throws org.json.JSONException * @returns String array with status, deploymentID and Name */ public String[] deployBPMNPackage(String filePath, String fileName) throws Exception { String url = serviceURL + "repository/deployments"; HttpHost target = new HttpHost(hostname, port, "http"); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addBinaryBody("file", new File(filePath), ContentType.MULTIPART_FORM_DATA, fileName); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); HttpResponse response = httpClient.execute(httpPost); String status = response.getStatusLine().toString(); String responseData = EntityUtils.toString(response.getEntity()); JSONObject jsonResponseObject = new JSONObject(responseData); if (status.contains(Integer.toString(HttpStatus.SC_CREATED)) || status.contains(Integer.toString(HttpStatus.SC_OK))) { String deploymentID = jsonResponseObject.getString("id"); String name = jsonResponseObject.getString("name"); return new String[] { status, deploymentID, name }; } else if (status.contains(Integer.toString(HttpStatus.SC_INTERNAL_SERVER_ERROR))) { String errorMessage = jsonResponseObject.getString("errorMessage"); throw new RestClientException(errorMessage); // return new String[]{status, errorMessage}; } else { throw new RestClientException("Failed to deploy package " + fileName); } }