List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity
public void setRequestEntity(RequestEntity paramRequestEntity)
From source file:org.eclipse.swordfish.tools.deployer.SwordfishClientCommandProvider.java
public Object _sfupdate(CommandInterpreter intp) { try {/* w ww .j a v a2s . c o m*/ String ius = getMandatoryParameter(intp, IU_LIST); String profile = intp.nextArgument(); PutMethod putMethod = createPutRequest(ius, OP_UPDATE, profile); RequestEntity entity = new InputStreamRequestEntity(new FileInputStream(repository)); putMethod.setRequestEntity(entity); httpClient.executeMethod(putMethod); showResponse(intp, putMethod); } catch (Exception e) { handleException(intp, "Update", e); } return null; }
From source file:org.ednovo.gooru.converter.service.ConversionServiceImpl.java
public List<String> resizeImageByDimensions(String srcFilePath, String targetFolderPath, String filenamePrefix, String dimensions, String resourceGooruOid, String sessionToken, String thumbnail, String apiEndPoint) { String imagePath = null;/*from w ww . j av a2s . co m*/ List<String> list = new ArrayList<String>(); try { logger.debug(" src : {} /= target : {}", srcFilePath, targetFolderPath); String[] imageDimensions = dimensions.split(","); if (filenamePrefix == null) { filenamePrefix = StringUtils.substringAfterLast(srcFilePath, "/"); if (filenamePrefix.contains(".")) { filenamePrefix = StringUtils.substringBeforeLast(filenamePrefix, "."); } } for (String dimension : imageDimensions) { String[] xy = dimension.split(X); int width = Integer.valueOf(xy[0]); int height = Integer.valueOf(xy[1]); imagePath = resizeImageByDimensions(srcFilePath, width, height, targetFolderPath + filenamePrefix + "-" + dimension + "." + getFileExtenstion(srcFilePath)); list.add(imagePath); } try { JSONObject json = new JSONObject(); json.put(RESOURCE_GOORU_OID, resourceGooruOid); json.put(THUMBNAIL, thumbnail); JSONObject jsonAlias = new JSONObject(); jsonAlias.put(MEDIA, json); String jsonString = jsonAlias.toString(); StringRequestEntity requestEntity = new StringRequestEntity(jsonString, APP_JSON, "UTF-8"); HttpClient client = new HttpClient(); PutMethod postmethod = new PutMethod( apiEndPoint + "/media/resource/thumbnail?sessionToken=" + sessionToken); postmethod.setRequestEntity(requestEntity); client.executeMethod(postmethod); } catch (Exception ex) { logger.error("rest api call failed!", ex.getMessage()); } } catch (Exception ex) { logger.error("Multiple scaling of image failed for src : " + srcFilePath + " : ", ex); } return list; }
From source file:org.elasticsearch.hadoop.rest.RestClient.java
public void putMapping(String index, String mapping, byte[] bytes) { // create index first (if needed) - it might return 403 execute(new PutMethod(index), false); // create actual mapping PutMethod put = new PutMethod(mapping); put.setRequestEntity(new ByteArrayRequestEntity(bytes)); execute(put);/*from w w w .ja va 2 s. c o m*/ }
From source file:org.exist.netedit.NetEditApplet.java
/** * Upload file to server //ww w. java2s . c o m * @param file uploaded file * @param uploadTo URL of remote doc to upload * @throws HttpException * @throws IOException */ public void upload(File file, String uploadTo) throws HttpException, IOException { PutMethod put = new PutMethod(uploadTo); useCurrentSession(put); InputStream is = new FileInputStream(file); RequestEntity entity = new InputStreamRequestEntity(is); put.setRequestEntity(entity); http.executeMethod(put); is.close(); put.releaseConnection(); }
From source file:org.exist.xquery.modules.httpclient.PUTFunction.java
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { Sequence response = null;//from w w w . j a v a2s .c om // must be a URL if (args[0].isEmpty()) { return (Sequence.EMPTY_SEQUENCE); } //get the url String url = args[0].itemAt(0).getStringValue(); //get the payload Item payload = args[1].itemAt(0); //get the persist state boolean persistState = args[2].effectiveBooleanValue(); String indentLevel = (args.length >= 5 && !args[4].isEmpty()) ? args[4].itemAt(0).toString() : null; RequestEntity entity = null; if (Type.subTypeOf(payload.getType(), Type.NODE)) { //serialize the node to SAX ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStreamWriter osw = new OutputStreamWriter(baos, UTF_8); IndentingXMLWriter xmlWriter = new IndentingXMLWriter(osw); Properties outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8"); if (indentLevel != null) { outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty(EXistOutputKeys.INDENT_SPACES, indentLevel); } else { outputProperties.setProperty(OutputKeys.INDENT, "no"); } xmlWriter.setOutputProperties(outputProperties); SAXSerializer sax = new SAXSerializer(); sax.setReceiver(xmlWriter); try { payload.toSAX(context.getBroker(), sax, new Properties()); osw.flush(); osw.close(); } catch (Exception e) { throw new XPathException(this, e); } entity = new ByteArrayRequestEntity(baos.toByteArray(), "application/xml; charset=utf-8"); } else if (Type.subTypeOf(payload.getType(), Type.BASE64_BINARY)) { entity = new ByteArrayRequestEntity(payload.toJavaObject(byte[].class)); } else { try { entity = new StringRequestEntity(payload.getStringValue(), "text/text; charset=utf-8", "UTF-8"); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } } //setup PUT request PutMethod put = new PutMethod(url); put.setRequestEntity(entity); //setup PUT Request Headers if (!args[3].isEmpty()) { setHeaders(put, ((NodeValue) args[3].itemAt(0)).getNode()); } try { //execute the request response = doRequest(context, put, persistState, null, null); } catch (IOException ioe) { throw (new XPathException(this, ioe.getMessage(), ioe)); } finally { put.releaseConnection(); } return (response); }
From source file:org.exjello.mail.Exchange2003Connection.java
public void send(MimeMessage message) throws Exception { Address[] bccRecipients = message.getRecipients(Message.RecipientType.BCC); if (bccRecipients == null || bccRecipients.length == 0) { bccRecipients = null;/*from www . j a va2 s . co m*/ } message.setRecipients(Message.RecipientType.BCC, (Address[]) null); synchronized (this) { if (!isConnected()) { throw new IllegalStateException("Not connected."); } if (!canSend()) { throw new IllegalStateException("Unable to access outbox."); } HttpClient client = getClient(); String path = drafts; if (!path.endsWith("/")) path += "/"; String messageName = generateMessageName(); path += escape(messageName + ".eml"); PutMethod op = new PutMethod(path); op.setRequestHeader("Content-Type", MESSAGE_CONTENT_TYPE); op.setRequestEntity(createMessageEntity(message)); InputStream stream = null; try { int status = client.executeMethod(op); stream = op.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to post message to draft folder."); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { op.releaseConnection(); } } if (bccRecipients != null) { ExchangeMethod patch = new ExchangeMethod(PROPPATCH_METHOD, path); patch.setHeader("Content-Type", XML_CONTENT_TYPE); patch.addHeader("Depth", "0"); patch.addHeader("Translate", "f"); patch.addHeader("Brief", "t"); patch.setRequestEntity(createAddBccEntity(bccRecipients)); stream = null; try { int status = client.executeMethod(patch); stream = patch.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to add BCC recipients. Status: " + status); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { patch.releaseConnection(); } } } ExchangeMethod move = new ExchangeMethod(MOVE_METHOD, path); String destination = submissionUri; if (!destination.endsWith("/")) destination += "/"; move.setHeader("Destination", destination); stream = null; try { int status = client.executeMethod(move); stream = move.getResponseBodyAsStream(); if (status >= 300) { throw new IllegalStateException("Unable to move message to outbox: Status " + status); } } finally { try { if (stream != null) { byte[] buf = new byte[65536]; try { if (session.getDebug()) { PrintStream log = session.getDebugOut(); log.println("Response Body:"); int count; while ((count = stream.read(buf, 0, 65536)) != -1) { log.write(buf, 0, count); } log.flush(); log.println(); } else { while (stream.read(buf, 0, 65536) != -1) ; } } catch (Exception ignore) { } finally { try { stream.close(); } catch (Exception ignore2) { } } } } finally { move.releaseConnection(); } } if (session.getDebug()) { session.getDebugOut().println("Sent successfully."); } } }
From source file:org.fabric8.demo.cxf.test.CrmTest.java
/** * HTTP PUT http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of * the update_customer.xml file to update the customer information for customer 123. * <p/>/*from w ww .j ava 2 s . c o m*/ * On the server side, it matches the CustomerService's updateCustomer() method * * @throws Exception */ @Test public void putCutomerTest() throws IOException { LOG.info("Sent HTTP PUT request to update customer info"); String inputFile = this.getClass().getResource("/update_customer.xml").getFile(); File input = new File(inputFile); PutMethod put = new PutMethod(CUSTOMER_SERVICE_URL); RequestEntity entity = new FileRequestEntity(input, "application/xml; charset=ISO-8859-1"); put.setRequestEntity(entity); HttpClient httpclient = new HttpClient(); int result = 0; try { result = httpclient.executeMethod(put); LOG.info("Response status code: " + result); LOG.info("Response body: "); LOG.info(put.getResponseBodyAsString()); } catch (IOException e) { LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL); LOG.error( "You should build the 'rest' quick start and deploy it to a local Fuse before running this test"); LOG.error("Please read the README.md file in 'rest' quick start root"); Assert.fail("Connection error"); } finally { // Release current connection to the connection pool once you are // done put.releaseConnection(); } LOG.info("HTTP: " + result); Assert.assertEquals(result, 200); }
From source file:org.geoserver.script.js.RemoteConsole.java
private String eval(String input) { BufferedReader reader;/* w w w. j av a 2 s. c o m*/ String sessionUrl = url.toString() + sessionId; PutMethod method = new PutMethod(sessionUrl); String result = ""; try { RequestEntity entity = new StringRequestEntity(input, "text/plain", "UTF-8"); method.setRequestEntity(entity); client.executeMethod(method); reader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream())); String line; while (((line = reader.readLine()) != null)) { result = result + line; } } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { method.releaseConnection(); } return result; }
From source file:org.geotools.data.couchdb.client.CouchDBClient.java
/** * Send a PUT with a body (for creating documents) * @param path//from w ww .j a v a 2s.c o m * @param content * @return * @throws IOException */ public CouchDBResponse put(String path, String content) throws IOException { PutMethod put = new PutMethod(url(path)); if (content != null) { try { put.setRequestEntity(new StringRequestEntity(content, MIME_TYPE_JSON, DEFAULT_CHARSET)); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } return executeMethod(put); }
From source file:org.gradle.api.internal.artifacts.repositories.CommonsHttpClientBackedRepository.java
private void doPut(File source, String destination) throws IOException { PutMethod method = new PutMethod(destination); configureMethod(method);//from ww w .j ava 2 s .c om method.setRequestEntity(new FileRequestEntity(source)); int result = client.executeMethod(method); if (result != 200) { throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s", destination, result, method.getStatusText())); } }