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.apache.webdav.lib.methods.LockMethod.java
/** * Parse response./*from www .j av a 2s .c o m*/ * * @param input Input stream */ public void parseResponse(InputStream input, HttpState state, HttpConnection conn) throws IOException, HttpException { int status = getStatusLine().getStatusCode(); if (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_MULTI_STATUS) { parseXMLResponse(input); NodeList list = getResponseDocument().getDocumentElement().getElementsByTagNameNS("DAV:", "locktoken"); if (list.getLength() == 1) { Element locktoken = (Element) list.item(0); NodeList list2 = locktoken.getElementsByTagNameNS("DAV:", "href"); if (list2.getLength() == 1) { this.lockToken = DOMUtils.getTextValue(list2.item(0)); if (state instanceof WebdavState) { /* * lockMethod/unlockMethod take unescaped URIs but LockMathod.getPath() * func returns an escaped URI so searching for the lock by path name in * the state object doesn't work. Convert escaped back to unescaped. */ ((WebdavState) state).addLock(URIUtil.decode(getPath()), this.lockToken); } } } list = getResponseDocument().getDocumentElement().getElementsByTagNameNS("DAV:", "owner"); if (list.getLength() == 1) { Element owner = (Element) list.item(0); this.owner = DOMUtils.getTextValue(owner); } } }
From source file:org.apache.wookie.proxy.ProxyClient.java
private String executeMethod(HttpMethod method, Configuration properties) throws Exception, AuthenticationException { // Execute the method. try {/*from w w w .j av a 2 s . co m*/ HttpClient client = new HttpClient(); // set the clients proxy values if needed ConnectionsPrefsManager.setProxySettings(client, properties); if (fUseProxyAuthentication) { if (fBase64Auth != null) { method.setRequestHeader("Authorization", fBase64Auth); } else { List<String> authPrefs = new ArrayList<String>(2); authPrefs.add(AuthPolicy.DIGEST); authPrefs.add(AuthPolicy.BASIC); client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); // send the basic authentication response even before the server gives an unauthorized response client.getParams().setAuthenticationPreemptive(true); // Pass our credentials to HttpClient client.getState().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(fProxyUsername, fProxyPassword)); } } // Add user language to http request in order to notify server of user's language Locale locale = Locale.getDefault(); method.setRequestHeader("Accept-Language", locale.getLanguage()); //$NON-NLS-1$ method.removeRequestHeader("Content-Type"); //method.setRequestHeader("Content-Type","application/json"); //method.setRequestHeader("Referer", ""); //method.removeRequestHeader("Referer"); method.setRequestHeader("Accept", "*/*"); int statusCode = client.executeMethod(method); //System.out.println("response="+method.getResponseBodyAsString()); //System.out.println("method="+method.toString()); //System.out.println("response="+method.getResponseBodyAsStream()); if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) { Header hType = method.getResponseHeader("Content-Type"); if (hType != null) { fContentType = hType.getValue(); } // for now we are only expecting Strings //return method.getResponseBodyAsString(); return readFully(new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8")); } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED || statusCode == HttpStatus.SC_UNAUTHORIZED) { throw new AuthenticationException("Authentication failed:" + method.getStatusLine() + ' ' + method.getURI() + ' ' + method.getStatusText()); } else { throw new Exception("Method failed: " + method.getStatusLine() + ' ' + method.getURI() + ' ' //$NON-NLS-1$ + method.getStatusText()); } } catch (IOException e) { throw e; } finally { // Release the connection. method.releaseConnection(); } }
From source file:org.archiviststoolkit.plugin.utils.WebServiceHelper.java
/** * Method to generate a handle by using the restful interface to the * handle server. Those handles will be assessable using the url like * <p/>//from w w w . ja va2s . c o m * http://hdl.handle.net/prefix/handle * * @param handleServiceUrl The URL of the Restful handle service * @param handleUrl The url this handle will be bound to i.e. http://some_location/item * @param description A brief description of this handle */ public static String createHandle(String handleServiceUrl, String handleUrl, String description, String userid, String password) throws Exception { String handle = ""; // this is the handle that was returned from server // set the correct url if (handleServiceUrl == null) { handleServiceUrl = RESTFUL_HANDLE_TEST_URL; } // Get the HTTP client and set the authentication credentials String host = getHostFromURL(handleServiceUrl); HttpClient httpclient = new HttpClient(); httpclient.getState().setCredentials(new AuthScope(host, 443, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userid, password)); // do automatic authentication if the server request it. httpclient.getParams().setAuthenticationPreemptive(true); // create the xml that is sent to the restful handle service String xml = getHandleXML(handleUrl, description); // Prepare HTTP post method. PostMethod post = new PostMethod(handleServiceUrl); post.setRequestEntity(new StringRequestEntity(xml, "text/xml", null)); // Execute request try { int statusCode = httpclient.executeMethod(post); // Display status code String statusMessage = "Status code: " + statusCode + "\nStatus text: " + post.getStatusText(); System.out.println(statusMessage); // Display response System.out.println("Response body: "); System.out.println(post.getResponseBodyAsString()); // if status code doesn't equal to success throw exception if (statusCode == HttpStatus.SC_CREATED) { handle = getHandleFromXML(post.getResponseBodyAsString()); } else { post.releaseConnection(); throw new Exception(statusMessage); } } finally { // Release current connection to the server post.releaseConnection(); } return handle; }
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 w w w . j av a2s. co 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.bibsonomy.rest.client.AbstractQuery.java
/** * @return <code>true</code> iff the request was successful *//* ww w.ja va 2 s . c o m*/ public boolean isSuccess() { return this.getHttpStatusCode() == HttpStatus.SC_OK || this.getHttpStatusCode() == HttpStatus.SC_CREATED; }
From source file:org.datacleaner.metamodel.datahub.DataHubDataContext.java
private String retrieveTenantName() { final String getUserInfoUrl = _repoConnection.getUserInfoUrl(); final HttpGet request = new HttpGet(getUserInfoUrl); try (final MonitorHttpClient monitorHttpClient = _repoConnection.getHttpClient()) { final HttpResponse response = monitorHttpClient.execute(request); final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK || statusLine.getStatusCode() == HttpStatus.SC_CREATED) { // read response as JSON. final InputStream content = response.getEntity().getContent(); final UserInfo userInfo; try { userInfo = new ObjectMapper().readValue(content, UserInfo.class); return userInfo.tenant; } finally { FileHelper.safeClose(content); }/*from w ww .j ava 2s . c o m*/ } else { final String reasonPhrase = statusLine.getReasonPhrase(); throw new RuntimeException("Failed to retrieve the tenant name: " + reasonPhrase); } } catch (Exception exception) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } throw new RuntimeException("Failed to retrieve the tenant name: " + exception.getMessage()); } }
From source file:org.datacleaner.windows.DataHubDatastoreDialog.java
@Inject public DataHubDatastoreDialog(WindowContext windowContext, MutableDatastoreCatalog datastoreCatalog, @Nullable DataHubDatastore originalDatastore, UserPreferences userPreferences) { super(originalDatastore, datastoreCatalog, windowContext, userPreferences); _hostTextField = WidgetFactory.createTextField("Hostname"); _portTextField = WidgetFactory.createTextField("Port"); _usernameTextField = WidgetFactory.createTextField("Username"); _passwordTextField = WidgetFactory.createPasswordField(); // _contextPathTextField = // WidgetFactory.createTextField("Context path"); _securityModeSelector = new JComboBox<>( new String[] { DataHubSecurityMode.DEFAULT.toString(), DataHubSecurityMode.CAS.toString() }); _securityModeSelector.setEditable(false); _urlLabel = DCLabel.bright(""); _urlLabel.setForeground(WidgetUtils.BG_COLOR_LESS_BRIGHT); _urlLabel.setBorder(new EmptyBorder(5, 0, 5, 0)); final DCDocumentListener genericDocumentListener = new DCDocumentListener() { @Override//from ww w . ja va 2 s .c o m protected void onChange(DocumentEvent event) { validateAndUpdate(); updateUrlLabel(); } }; _httpsCheckBox = new JCheckBox("Use HTTPS?", false); _httpsCheckBox.setOpaque(false); _httpsCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _httpsCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { updateUrlLabel(); validateAndUpdate(); } }); _acceptUnverifiedSslPeersCheckBox = new JCheckBox("Accept unverified SSL peers?", false); _acceptUnverifiedSslPeersCheckBox.setOpaque(false); _acceptUnverifiedSslPeersCheckBox.setForeground(WidgetUtils.BG_COLOR_BRIGHTEST); _acceptUnverifiedSslPeersCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { validateAndUpdate(); } }); _hostTextField.getDocument().addDocumentListener(genericDocumentListener); _portTextField.getDocument().addDocumentListener(genericDocumentListener); _usernameTextField.getDocument().addDocumentListener(genericDocumentListener); _passwordTextField.getDocument().addDocumentListener(genericDocumentListener); _securityModeSelector.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { validateAndUpdate(); updateUrlLabel(); } }); _testButton = WidgetFactory.createDefaultButton("Test connection", IconUtils.ACTION_REFRESH); _testButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { final DataHubRepoConnection connection = createConnection(); final String getTenantInfoUrl = connection.getUserInfoUrl(); final HttpGet request = new HttpGet(getTenantInfoUrl); try (final MonitorHttpClient monitorHttpClient = connection.getHttpClient()) { final HttpResponse response = monitorHttpClient.execute(request); final StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == HttpStatus.SC_OK || statusLine.getStatusCode() == HttpStatus.SC_CREATED) { // read response as JSON. final InputStream content = response.getEntity().getContent(); final UserInfo userInfo; try { userInfo = new ObjectMapper().readValue(content, UserInfo.class); } finally { FileHelper.safeClose(content); } LOGGER.info("Get tenant info request responded with tenant name: {}", userInfo.tenant); JOptionPane.showMessageDialog(DataHubDatastoreDialog.this, "Connection successful!"); } else { final String reasonPhrase = statusLine.getReasonPhrase(); WidgetUtils.showErrorMessage("Server reported error", "Server replied with status " + statusLine.getStatusCode() + ":\n" + reasonPhrase); } } catch (Exception e) { // TODO: This dialog is shown behind the modal dialog WidgetUtils.showErrorMessage("Connection failed", "Connecting to DataHub failed. Did you remember to fill in all the necessary fields?", e); } validateAndUpdate(); } }); if (originalDatastore != null) { _hostTextField.setText(originalDatastore.getHost()); _portTextField.setText(originalDatastore.getPort() + ""); _httpsCheckBox.setSelected(originalDatastore.isHttps()); _acceptUnverifiedSslPeersCheckBox.setSelected(originalDatastore.isAcceptUnverifiedSslPeers()); if (originalDatastore.getSecurityMode().equals(DataHubSecurityMode.CAS)) { _securityModeSelector.setSelectedIndex(1); } else { _securityModeSelector.setSelectedIndex(0); } _datastoreNameTextField.setText(originalDatastore.getName()); _datastoreNameTextField.setEditable(false); _usernameTextField.setText(originalDatastore.getUsername()); _passwordTextField.setText(originalDatastore.getPassword()); } else { _hostTextField.setText("localhost"); _portTextField.setText("8080"); } updateUrlLabel(); }
From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java
private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp) throws IOException { /* File tmp = null; FileOutputStream fos = null;/*from ww w . ja va 2 s . co m*/ PostMethod post = null; //System.out.println(filename + " -> " + depositurl); */ try { /* tmp = File.createTempFile("fileupload", null); fos = new FileOutputStream(tmp); FileUtil.copy(is, fos); HttpClient client = new HttpClient(); post = new PostMethod(depositurl); Part[] parts = {new FilePart(filename, tmp)}; post.setRequestEntity(new MultipartRequestEntity(parts, post .getParams())); */ org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(depositurl); InputStreamEntity data = new InputStreamEntity(is, -1); data.setContentType("binary/octet-stream"); data.setChunked(false); post.setEntity(data); HttpResponse response = client.execute(post); System.out.println(response.toString()); int status = 202;//response.getStatusLine(); // int status = client.executeMethod(post); if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) { resp.setStatus(status); String src = response.getHeaders("X-dcs-src")[0].getValue(); String atomurl = response.getHeaders("Location")[0].getValue(); resp.setContentType("text/html"); resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>"); resp.flushBuffer(); } else { resp.sendError(status, response.getStatusLine().toString()); return; } } finally { /* if (tmp != null) { tmp.delete(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (post != null) { post.releaseConnection(); }*/ } }
From source file:org.dataconservancy.dcs.ingest.ui.server.FileUploadServlet.java
private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp) throws IOException { File tmp = null;/*from ww w . ja v a2 s . c o m*/ FileOutputStream fos = null; PostMethod post = null; //System.out.println(filename + " -> " + depositurl); try { tmp = File.createTempFile("fileupload", null); fos = new FileOutputStream(tmp); FileUtil.copy(is, fos); HttpClient client = new HttpClient(); post = new PostMethod(depositurl); Part[] parts = { new FilePart(filename, tmp) }; post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams())); int status = client.executeMethod(post); if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) { resp.setStatus(status); String src = post.getResponseHeader("X-dcs-src").getValue(); String atomurl = post.getResponseHeader("Location").getValue(); resp.setContentType("text/html"); resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>"); resp.flushBuffer(); } else { resp.sendError(status, post.getStatusText()); return; } } finally { if (tmp != null) { tmp.delete(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (post != null) { post.releaseConnection(); } } }
From source file:org.dcm4chex.archive.hsm.module.castor.CAStorHSMModule.java
/** * The method that is called by the FileCopy service to copy a study tarball * to nearline storage (i.e. CAStor)./*from w ww .j a va2s .c o m*/ * * @param file * The tar file to copy. * @param fsID * The file system ID for nearline storage. * @param filePath * The relative path to the study tarball in online storage. * @return The relative path to the study files in nearline storage. * @throws HSMException */ @Override public String storeHSMFile(File file, String fsID, String filePath) throws HSMException { logger.debug("storeHSMFile called with file=" + file + ", fsID=" + fsID + ", filePath=" + filePath); // Open the tar file in read mode ResettableFileInputStream fis = null; try { fis = new ResettableFileInputStream(file); } catch (IOException e) { throw new HSMException("Could not open file " + file, e); } String newFilePath = null; ScspHeaders scspHeaders = new ScspHeaders(); addStudyLifepoint(scspHeaders, file, filePath); logger.info("Uploading " + file + " to CAStor"); // Read the tar file and write the data to the CAStor object try { if (client == null) { createClient(); } ScspResponse response = client.write("", fis, file.length(), new ScspQueryArgs(), scspHeaders); switch (response.getHttpStatusCode()) { case HttpStatus.SC_CREATED: case HttpStatus.SC_ACCEPTED: newFilePath = extractUUIDFromScspResponse(response); break; default: logger.error("Unexpected WRITE response: " + response.toString()); } } catch (ScspExecutionException e) { throw new HSMException("Could not upload " + file + " to CAStor", e); } catch (Exception e) { throw new HSMException("Could not store " + filePath + " in nearline storage", e); } finally { // Always close the opened file if (fis != null) { try { fis.close(); } catch (IOException e) { logger.error("Could not close input stream for " + file, e); } } // Delete the temporary tar file if (!file.delete()) { logger.warn("Could not delete temporary file: " + file); } } return newFilePath; }