List of usage examples for org.apache.commons.httpclient.methods PutMethod PutMethod
public PutMethod(String paramString)
From source file:de.mpg.mpdl.inge.pubman.web.easySubmission.EasySubmission.java
/** * Uploads a file to the staging servlet and returns the corresponding URL. * /*from ww w. j a v a 2 s.co m*/ * @param uploadedFile The file to upload * @param mimetype The mimetype of the file * @param userHandle The userhandle to use for upload * @return The URL of the uploaded file. * @throws Exception If anything goes wrong... */ protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception { // Prepare the HttpMethod. String fwUrl = PropertyReader.getFrameworkUrl(); PutMethod method = new PutMethod(fwUrl + "/st/staging-file"); /* * if(uploadedFile.isTempFile()) { */ InputStream fis = uploadedFile.getInputstream(); method.setRequestEntity(new InputStreamRequestEntity(fis)); /* * } else { method.setRequestEntity(new InputStreamRequestEntity(new * ByteArrayInputStream(uploadedFile.getData()))); } */ method.setRequestHeader("Content-Type", mimetype); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); ProxyHelper.setProxy(client, fwUrl); client.executeMethod(method); String response = method.getResponseBodyAsString(); fis.close(); return xmlTransforming.transformUploadResponseToFileURL(response); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPutOperation7Json() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation7Json"; PutMethod method = new PutMethod(url); String param = this.getJsonCd(); method.setRequestEntity(new StringRequestEntity(param, "application/json", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK); byte[] responseBody = method.getResponseBody(); String jsonResponse = new String(responseBody); assertTrue(jsonResponse.indexOf("\"title\":\"My Track 1\"") > -1); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPutOperation8Xml() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation8Xml"; PutMethod method = new PutMethod(url); String param = this.getXmlCd(); method.setRequestEntity(new StringRequestEntity(param, "application/xml", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK); byte[] responseBody = method.getResponseBody(); String xmlResponse = new String(responseBody); assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1); assertTrue(xmlResponse.indexOf("<title>putOperation8</title>") > -1); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testAndroidMeetingSeries() throws Exception { Account dav1 = users[1].create();/*from w ww . j a v a2 s. co m*/ Account dav2 = users[2].create(); users[2].getZMailbox(); // Force creation of mailbox - shouldn't be needed String calFolderUrl = getFolderUrl(dav1, "Calendar").replaceAll("@", "%40"); String url = String.format("%s%s.ics", calFolderUrl, androidSeriesMeetingUid); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, dav1); putMethod.addRequestHeader("Content-Type", "text/calendar"); String body = androidSeriesMeetingTemplate.replace("%%ORG%%", dav1.getName()) .replace("%%ATT%%", dav2.getName()).replace("%%UID%%", androidSeriesMeetingUid); putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR)); HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED); String inboxhref = TestCalDav.waitForNewSchedulingRequestByUID(dav2, androidSeriesMeetingUid); assertTrue("Found meeting request for newly created item", inboxhref.contains(androidSeriesMeetingUid)); GetMethod getMethod = new GetMethod(url); addBasicAuthHeaderForUser(getMethod, dav1); HttpMethodExecutor exe = HttpMethodExecutor.execute(client, getMethod, HttpStatus.SC_OK); String etag = null; for (Header hdr : exe.respHeaders) { if (DavProtocol.HEADER_ETAG.equals(hdr.getName())) { etag = hdr.getValue(); } } assertNotNull("ETag from get", etag); // Check that we fail if the etag is wrong putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, dav1); putMethod.addRequestHeader("Content-Type", "text/calendar"); putMethod.addRequestHeader(DavProtocol.HEADER_IF_MATCH, "willNotMatch"); putMethod.setRequestEntity(new ByteArrayRequestEntity(body.getBytes(), MimeConstants.CT_TEXT_CALENDAR)); HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_PRECONDITION_FAILED); PropFindMethod propFindMethod = new PropFindMethod(getFolderUrl(dav1, "Calendar")); addBasicAuthHeaderForUser(propFindMethod, dav1); TestCalDav.HttpMethodExecutor executor; String respBody; Element respElem; propFindMethod.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML); propFindMethod.addRequestHeader("Depth", "1"); propFindMethod.setRequestEntity( new ByteArrayRequestEntity(propFindEtagResType.getBytes(), MimeConstants.CT_TEXT_XML)); executor = new TestCalDav.HttpMethodExecutor(client, propFindMethod, HttpStatus.SC_MULTI_STATUS); respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); respElem = Element.XMLElement.parseXML(respBody); assertEquals("name of top element in propfind response", DavElements.P_MULTISTATUS, respElem.getName()); assertTrue("propfind response should have child elements", respElem.hasChildren()); Iterator<Element> iter = respElem.elementIterator(); boolean hasCalendarHref = false; boolean hasCalItemHref = false; while (iter.hasNext()) { Element child = iter.next(); if (DavElements.P_RESPONSE.equals(child.getName())) { Iterator<Element> hrefIter = child.elementIterator(DavElements.P_HREF); while (hrefIter.hasNext()) { Element href = hrefIter.next(); calFolderUrl.endsWith(href.getText()); hasCalendarHref = hasCalendarHref || calFolderUrl.endsWith(href.getText()); hasCalItemHref = hasCalItemHref || url.endsWith(href.getText()); } } } assertTrue("propfind response contained entry for calendar", hasCalendarHref); assertTrue("propfind response contained entry for calendar entry ", hasCalItemHref); DeleteMethod deleteMethod = new DeleteMethod(url); addBasicAuthHeaderForUser(deleteMethod, dav1); HttpMethodExecutor.execute(client, deleteMethod, HttpStatus.SC_NO_CONTENT); }
From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java
public byte[] getData(Context context) throws IOException, EngineException { HttpMethod method = null;//from w w w . j a v a 2 s.com try { // Fire event for plugins long t0 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataStart(context); // Retrieving httpState getHttpState(context); Engine.logBeans.trace("(HttpConnector) Retrieving data as a bytes array..."); Engine.logBeans.debug("(HttpConnector) Connecting to: " + sUrl); // Setting the referer referer = sUrl; URL url = null; url = new URL(sUrl); // Proxy configuration Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url); Engine.logBeans.debug("(HttpConnector) Https: " + https); String host = ""; int port = -1; if (sUrl.toLowerCase().startsWith("https:")) { if (!https) { Engine.logBeans.debug("(HttpConnector) Setting up SSL properties"); certificateManager.collectStoreInformation(context); } url = new URL(sUrl); host = url.getHost(); port = url.getPort(); if (port == -1) port = 443; Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); Engine.logBeans .debug("(HttpConnector) CertificateManager has changed: " + certificateManager.hasChanged); if (certificateManager.hasChanged || (!host.equalsIgnoreCase(hostConfiguration.getHost())) || (hostConfiguration.getPort() != port)) { Engine.logBeans.debug("(HttpConnector) Using MySSLSocketFactory for creating the SSL socket"); Protocol myhttps = new Protocol("https", MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore, certificateManager.keyStorePassword, certificateManager.trustStore, certificateManager.trustStorePassword, this.trustAllServerCertificates), port); hostConfiguration.setHost(host, port, myhttps); } sUrl = url.getFile(); Engine.logBeans.debug("(HttpConnector) Updated URL for SSL purposes: " + sUrl); } else { url = new URL(sUrl); host = url.getHost(); port = url.getPort(); Engine.logBeans.debug("(HttpConnector) Host: " + host + ":" + port); hostConfiguration.setHost(host, port); } AbstractHttpTransaction httpTransaction = (AbstractHttpTransaction) context.transaction; // Retrieve HTTP method HttpMethodType httpVerb = httpTransaction.getHttpVerb(); String sHttpVerb = httpVerb.name(); final String sCustomHttpVerb = httpTransaction.getCustomHttpVerb(); if (sCustomHttpVerb.length() > 0) { Engine.logBeans.debug( "(HttpConnector) HTTP verb: " + sHttpVerb + " overridden to '" + sCustomHttpVerb + "'"); switch (httpVerb) { case GET: method = new GetMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case POST: method = new PostMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case PUT: method = new PutMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case DELETE: method = new DeleteMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case HEAD: method = new HeadMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case OPTIONS: method = new OptionsMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; case TRACE: method = new TraceMethod(sUrl) { @Override public String getName() { return sCustomHttpVerb; } }; break; } } else { Engine.logBeans.debug("(HttpConnector) HTTP verb: " + sHttpVerb); switch (httpVerb) { case GET: method = new GetMethod(sUrl); break; case POST: method = new PostMethod(sUrl); break; case PUT: method = new PutMethod(sUrl); break; case DELETE: method = new DeleteMethod(sUrl); break; case HEAD: method = new HeadMethod(sUrl); break; case OPTIONS: method = new OptionsMethod(sUrl); break; case TRACE: method = new TraceMethod(sUrl); break; } } // Setting HTTP parameters boolean hasUserAgent = false; for (List<String> httpParameter : httpParameters) { String key = httpParameter.get(0); String value = httpParameter.get(1); if (key.equalsIgnoreCase("host") && !value.equals(host)) { value = host; } if (!key.startsWith(DYNAMIC_HEADER_PREFIX)) { method.setRequestHeader(key, value); } if (HeaderName.UserAgent.is(key)) { hasUserAgent = true; } } // set user-agent header if not found if (!hasUserAgent) { HeaderName.UserAgent.setRequestHeader(method, getUserAgent(context)); } // Setting POST or PUT parameters if any Engine.logBeans.debug("(HttpConnector) Setting " + httpVerb + " data"); if (method instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) method; AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject; if (doMultipartFormData) { RequestableHttpVariable body = (RequestableHttpVariable) httpTransaction .getVariable(Parameter.HttpBody.getName()); if (body != null && body.getDoFileUploadMode() == DoFileUploadMode.multipartFormData) { String stringValue = httpTransaction.getParameterStringValue(Parameter.HttpBody.getName()); String filepath = Engine.theApp.filePropertyManager.getFilepathFromProperty(stringValue, getProject().getName()); File file = new File(filepath); if (file.exists()) { HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod.setRequestEntity(new FileRequestEntity(file, contentType)); } else { throw new FileNotFoundException(file.getAbsolutePath()); } } else { List<Part> parts = new LinkedList<Part>(); for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if ("POST".equals(httpVariable.getHttpMethod())) { Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addFormDataPart(parts, httpVariable, httpVariableValue); } } } else { addFormDataPart(parts, httpVariable, httpObjectVariableValue); } } } } MultipartRequestEntity mre = new MultipartRequestEntity( parts.toArray(new Part[parts.size()]), entityEnclosingMethod.getParams()); HeaderName.ContentType.setRequestHeader(method, mre.getContentType()); entityEnclosingMethod.setRequestEntity(mre); } } else if (MimeType.TextXml.is(contentType)) { final MimeMultipart[] mp = { null }; for (RequestableVariable variable : transaction.getVariablesList()) { if (variable instanceof RequestableHttpVariable) { RequestableHttpVariable httpVariable = (RequestableHttpVariable) variable; if (httpVariable.getDoFileUploadMode() == DoFileUploadMode.MTOM) { Engine.logBeans.trace( "(HttpConnector) Variable " + httpVariable.getName() + " detected as MTOM"); MimeMultipart mimeMultipart = mp[0]; try { if (mimeMultipart == null) { Engine.logBeans.debug("(HttpConnector) Preparing the MTOM request"); mimeMultipart = new MimeMultipart("related; type=\"application/xop+xml\""); MimeBodyPart bp = new MimeBodyPart(); bp.setText(postQuery, "UTF-8"); bp.setHeader(HeaderName.ContentType.value(), contentType); mimeMultipart.addBodyPart(bp); } Object httpObjectVariableValue = transaction .getVariableValue(httpVariable.getName()); if (httpVariable.isMultiValued()) { if (httpObjectVariableValue instanceof Collection<?>) { for (Object httpVariableValue : (Collection<?>) httpObjectVariableValue) { addMtomPart(mimeMultipart, httpVariable, httpVariableValue); } } } else { addMtomPart(mimeMultipart, httpVariable, httpObjectVariableValue); } mp[0] = mimeMultipart; } catch (Exception e) { Engine.logBeans.warn( "(HttpConnector) Failed to add MTOM part for " + httpVariable.getName(), e); } } } } if (mp[0] == null) { entityEnclosingMethod.setRequestEntity( new StringRequestEntity(postQuery, MimeType.TextXml.value(), "UTF-8")); } else { Engine.logBeans.debug("(HttpConnector) Commit the MTOM request with the ContentType: " + mp[0].getContentType()); HeaderName.ContentType.setRequestHeader(method, mp[0].getContentType()); entityEnclosingMethod.setRequestEntity(new RequestEntity() { @Override public void writeRequest(OutputStream outputStream) throws IOException { try { mp[0].writeTo(outputStream); } catch (MessagingException e) { new IOException(e); } } @Override public boolean isRepeatable() { return true; } @Override public String getContentType() { return mp[0].getContentType(); } @Override public long getContentLength() { return -1; } }); } } else { String charset = httpTransaction.getComputedUrlEncodingCharset(); HeaderName.ContentType.setRequestHeader(method, contentType); entityEnclosingMethod .setRequestEntity(new StringRequestEntity(postQuery, contentType, charset)); } } // Getting the result Engine.logBeans.debug("(HttpConnector) HttpClient: getting response body"); byte[] result = executeMethod(method, context); Engine.logBeans.debug("(HttpConnector) Total read bytes: " + ((result != null) ? result.length : 0)); // Fire event for plugins long t1 = System.currentTimeMillis(); Engine.theApp.pluginsManager.fireHttpConnectorGetDataEnd(context, t0, t1); fireDataChanged(new ConnectorEvent(this, result)); return result; } finally { if (method != null) method.releaseConnection(); } }
From source file:de.mpg.mpdl.inge.pubman.web.easySubmission.EasySubmission.java
/** * Uploads a file to the staging servlet and returns the corresponding URL. * /*from ww w . j a v a2s . c o m*/ * @param InputStream to upload * @param mimetype The mimetype of the file * @param userHandle The userhandle to use for upload * @return The URL of the uploaded file. * @throws Exception If anything goes wrong... */ protected URL uploadFile(InputStream in, String mimetype, String userHandle) throws Exception { // Prepare the HttpMethod. String fwUrl = PropertyReader.getFrameworkUrl(); PutMethod method = new PutMethod(fwUrl + "/st/staging-file"); method.setRequestEntity(new InputStreamRequestEntity(in)); method.setRequestHeader("Content-Type", mimetype); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); client.executeMethod(method); String response = method.getResponseBodyAsString(); return xmlTransforming.transformUploadResponseToFileURL(response); }
From source file:de.mpg.escidoc.pubman.easySubmission.EasySubmission.java
/** * Uploads a file to the staging servlet and returns the corresponding URL. * // w w w . j a v a 2 s .co m * @param uploadedFile The file to upload * @param mimetype The mimetype of the file * @param userHandle The userhandle to use for upload * @return The URL of the uploaded file. * @throws Exception If anything goes wrong... */ protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception { // Prepare the HttpMethod. String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl(); PutMethod method = new PutMethod(fwUrl + "/st/staging-file"); /* if(uploadedFile.isTempFile()) { */ InputStream fis = uploadedFile.getInputstream(); method.setRequestEntity(new InputStreamRequestEntity(fis)); /* } else { method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(uploadedFile.getData()))); } */ method.setRequestHeader("Content-Type", mimetype); method.setRequestHeader("Cookie", "escidocCookie=" + userHandle); // Execute the method with HttpClient. HttpClient client = new HttpClient(); ProxyHelper.setProxy(client, fwUrl); client.executeMethod(method); String response = method.getResponseBodyAsString(); fis.close(); return xmlTransforming.transformUploadResponseToFileURL(response); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
@Test public void testPutOperation8Json() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation8Json"; PutMethod method = new PutMethod(url); String param = this.getJsonCd(); method.setRequestEntity(new StringRequestEntity(param, "application/json", null)); int statusCode = this.getHttpClient().executeMethod(method); assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK); byte[] responseBody = method.getResponseBody(); String jsonResponse = new String(responseBody); assertTrue(jsonResponse.indexOf("\"title\":\"putOperation8\"") > -1); }
From source file:muki.tool.JavaCompilationDeploymentTestCase.java
/** * This test does nothing as we have to put form params!! *//*from ww w. j a va2s .co m*/ @Test public void testPutOperation9Xml() throws Exception { String url = URL_RESOURCE1 + "/pathPutOperation9Xml"; PutMethod method = new PutMethod(url); }
From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java
/** * Makes a PUT request to the URL. Reads data back and returns the data * read. Note that this method only works with text data as it does the * byte-to-char conversion. This method will return null for responses * with binary MIME types. The addTextType(String) method is used to * register additional MIME types as text types. Use getContentSize() to * obtain the bytes of binary data read. * * @param url The URL to read from/*from w ww .ja v a2 s. c om*/ * @param buffer containing the PUT data * @param contentType the content type, or null * @param headers The request headers, or null * @return The StringBuilder buffer containing the resulting document * @throws java.io.IOException */ public StringBuilder putURL(String url, byte[] buffer, String contentType, Map<String, String> headers) throws IOException { PutMethod method = new PutMethod(url); method.setFollowRedirects(followRedirects); setHeaders(method, headers); method.setRequestEntity(new ByteArrayRequestEntity(buffer, contentType)); try { responseCode = hc.executeMethod(method); buildResponseHeaders(method); return fetchResponse(method); } finally { method.releaseConnection(); } }