List of usage examples for org.apache.commons.httpclient.methods ByteArrayRequestEntity ByteArrayRequestEntity
public ByteArrayRequestEntity(byte[] paramArrayOfByte, String paramString)
From source file:com.zimbra.qa.unittest.TestCalDav.java
@Test public void testBadPostToSchedulingOutbox() throws Exception { Account dav1 = users[1].create();/*from ww w . j a va 2 s . c o m*/ Account dav2 = users[2].create(); Account dav3 = users[3].create(); String url = getSchedulingOutboxUrl(dav2, dav2); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(url); addBasicAuthHeaderForUser(method, dav2); method.addRequestHeader("Content-Type", "text/calendar"); method.addRequestHeader("Originator", "mailto:" + dav2.getName()); method.addRequestHeader("Recipient", "mailto:" + dav3.getName()); method.setRequestEntity(new ByteArrayRequestEntity(exampleCancelIcal(dav1, dav2, dav3).getBytes(), MimeConstants.CT_TEXT_CALENDAR)); HttpMethodExecutor.execute(client, method, HttpStatus.SC_BAD_REQUEST); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public static Document calendarQuery(String url, Account acct) throws IOException, XmlParseException { ReportMethod method = new ReportMethod(url); addBasicAuthHeaderForUser(method, acct); HttpClient client = new HttpClient(); TestCalDav.HttpMethodExecutor executor; method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML); method.setRequestEntity(//from ww w .j a va2s . c o m new ByteArrayRequestEntity(calendar_query_etags_by_vevent.getBytes(), MimeConstants.CT_TEXT_XML)); executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS); String respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); Document doc = W3cDomUtil.parseXMLToDoc(respBody); org.w3c.dom.Element docElement = doc.getDocumentElement(); assertEquals("Report node name", DavElements.P_MULTISTATUS, docElement.getLocalName()); return doc; }
From source file:flex.messaging.services.http.proxy.RequestFilter.java
/** * Send the request./*from w w w .j a v a 2 s. c o m*/ * * @param context the context */ protected void sendRequest(ProxyContext context) { Target target = context.getTarget(); String method = context.getMethod(); HttpMethod httpMethod = context.getHttpMethod(); final String BEGIN = "-- Begin "; final String END = "-- End "; final String REQUEST = " request --"; if (httpMethod instanceof EntityEnclosingMethod) { Object data = processBody(context); Class dataClass = data.getClass(); if (data instanceof String) { String requestString = (String) data; if (Log.isInfo()) { Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY); logger.debug(BEGIN + method + REQUEST); logger.debug(StringUtils.prettifyString(requestString)); logger.debug(END + method + REQUEST); } try { StringRequestEntity requestEntity = new StringRequestEntity(requestString, null, "UTF-8"); ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity); } catch (UnsupportedEncodingException ex) { ProxyException pe = new ProxyException(CAUGHT_ERROR); pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex }); throw pe; } } else if (dataClass.isArray() && Byte.TYPE.equals(dataClass.getComponentType())) { byte[] dataBytes = (byte[]) data; ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(dataBytes, context.getContentType()); ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity); } else if (data instanceof InputStream) { InputStreamRequestEntity requestEntity = new InputStreamRequestEntity((InputStream) data, context.getContentType()); ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity); } //TODO: Support multipart post //else //{ //FIXME: Throw exception if unhandled data type //} } else if (httpMethod instanceof GetMethod) { Object req = processBody(context); if (req instanceof String) { String requestString = (String) req; if (Log.isInfo()) { Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY); logger.debug(BEGIN + method + REQUEST); logger.debug(StringUtils.prettifyString(requestString)); logger.debug(END + method + REQUEST); } if (!"".equals(requestString)) { String query = context.getHttpMethod().getQueryString(); if (query != null) { query += "&" + requestString; } else { query = requestString; } context.getHttpMethod().setQueryString(query); } } } context.getHttpClient().setHostConfiguration(target.getHostConfig()); try { context.getHttpClient().executeMethod(context.getHttpMethod()); } catch (UnknownHostException uhex) { ProxyException pe = new ProxyException(); pe.setMessage(UNKNOWN_HOST, new Object[] { uhex.getMessage() }); pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED); throw pe; } catch (Exception ex) { // FIXME: JRB - could be more specific by looking for timeout and sending 504 in that case. // rfc2616 10.5.5 504 - could get more specific if we parse the HttpException ProxyException pe = new ProxyException(CAUGHT_ERROR); pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex.getMessage() }); pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED); throw pe; } }
From source file:com.basho.riak.client.RiakObject.java
/** * Serializes this object to an existing {@link HttpMethod} which can be * sent as an HTTP request. Specifically, sends the object's link, * user-defined metadata and vclock as HTTP headers and the value as the * body. Used by {@link RiakClient} to create PUT requests. *///w w w . j av a 2 s .com public void writeToHttpMethod(HttpMethod httpMethod) { // Serialize headers String basePath = getBasePathFromHttpMethod(httpMethod); writeLinks(httpMethod, basePath); for (String name : userMetaData.keySet()) { httpMethod.setRequestHeader(Constants.HDR_USERMETA_REQ_PREFIX + name, userMetaData.get(name)); } if (vclock != null) { httpMethod.setRequestHeader(Constants.HDR_VCLOCK, vclock); } // Serialize body if (httpMethod instanceof EntityEnclosingMethod) { EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod; // Any value set using setValueAsStream() has precedent over value // set using setValue() if (valueStream != null) { if (valueStreamLength != null && valueStreamLength >= 0) { entityEnclosingMethod.setRequestEntity( new InputStreamRequestEntity(valueStream, valueStreamLength, contentType)); } else { entityEnclosingMethod.setRequestEntity(new InputStreamRequestEntity(valueStream, contentType)); } } else if (value != null) { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity(value, contentType)); } else { entityEnclosingMethod.setRequestEntity(new ByteArrayRequestEntity("".getBytes(), contentType)); } } }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public void checkPropFindSupportedReportSet(Account user, String fullurl, String shorturl) throws Exception { PropFindMethod method = new PropFindMethod(fullurl); addBasicAuthHeaderForUser(method, user); HttpClient client = new HttpClient(); TestCalDav.HttpMethodExecutor executor; String respBody;/*from w ww . j a v a2 s. c o m*/ Element respElem; method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML); method.setRequestEntity( new ByteArrayRequestEntity(propFindSupportedReportSet.getBytes(), MimeConstants.CT_TEXT_XML)); executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS); respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); respElem = Element.XMLElement.parseXML(respBody); assertEquals("name of top element in response", DavElements.P_MULTISTATUS, respElem.getName()); assertTrue("top element response should have child elements", respElem.hasChildren()); checkSupportedReportSet(respElem, shorturl); }
From source file:com.xmlcalabash.library.HttpRequest.java
private void doPutOrPostMultipart(EntityEnclosingMethod method, XdmNode multipart) { // The Apache HTTP libraries just don't handle this case...we treat it as a "single part" // and build the body ourselves, using the boundaries etc. // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Check for consistency of content-type contentType = multipart.getAttributeValue(_content_type); if (contentType == null) { contentType = "multipart/mixed"; }/*from w ww .j av a2 s .com*/ if (headerContentType != null && !headerContentType.equals(contentType.toLowerCase())) { throw XProcException.stepError(20); } if (!contentType.startsWith("multipart/")) { throw new UnsupportedOperationException("Multipart content-type must be multipart/..."); } for (Header header : headers) { method.addRequestHeader(header); } String boundary = multipart.getAttributeValue(_boundary); if (boundary == null) { throw new XProcException(step.getNode(), "A boundary value must be specified on c:multipart"); } if (boundary.startsWith("--")) { throw XProcException.stepError(2); } String q = "\""; if (boundary.contains(q)) { q = "'"; } if (boundary.contains(q)) { q = ""; } String multipartContentType = contentType + "; boundary=" + q + boundary + q; // FIXME: This sucks rocks. I want to write the data to be posted, not provide some way to read it MessageBytes byteContent = new MessageBytes(); byteContent.append("This is a multipart message.\r\n"); //String postContent = "This is a multipart message.\r\n"; for (XdmNode body : new RelevantNodes(runtime, multipart, Axis.CHILD)) { if (!XProcConstants.c_body.equals(body.getNodeName())) { throw new XProcException(step.getNode(), "A c:multipart may only contain c:body elements."); } String bodyContentType = body.getAttributeValue(_content_type); if (bodyContentType == null) { throw new XProcException(step.getNode(), "Content-type on c:body is required."); } String bodyId = body.getAttributeValue(_id); String bodyDescription = body.getAttributeValue(_description); String bodyDisposition = body.getAttributeValue(_disposition); String bodyCharset = HttpUtils.getCharset(bodyContentType); if (bodyContentType.contains(";")) { int pos = bodyContentType.indexOf(";"); bodyContentType = bodyContentType.substring(0, pos); } String bodyEncoding = body.getAttributeValue(_encoding); if (bodyEncoding != null && !"base64".equals(bodyEncoding)) { throw new UnsupportedOperationException("The '" + bodyEncoding + "' encoding is not supported"); } if (bodyCharset != null) { bodyContentType += "; charset=" + bodyCharset; } else { // Is utf-8 the right default? What about the image/ case? bodyContentType += "; charset=utf-8"; } //postContent += "--" + boundary + "\r\n"; //postContent += "Content-Type: " + bodyContentType + "\r\n"; byteContent.append("--" + boundary + "\r\n"); byteContent.append("Content-Type: " + bodyContentType + "\r\n"); if (bodyDescription != null) { //postContent += "Content-Description: " + bodyDescription + "\r\n"; byteContent.append("Content-Description: " + bodyDescription + "\r\n"); } if (bodyId != null) { //postContent += "Content-ID: " + bodyId + "\r\n"; byteContent.append("Content-ID: " + bodyId + "\r\n"); } if (bodyDisposition != null) { //postContent += "Content-Disposition: " + bodyDisposition + "\r\n"; byteContent.append("Content-Disposition: " + bodyDisposition + "\r\n"); } if (bodyEncoding != null) { //postContent += "Content-Transfer-Encoding: " + bodyEncoding + "\r\n"; if (encodeBinary) { byteContent.append("Content-Transfer-Encoding: " + bodyEncoding + "\r\n"); } } //postContent += "\r\n"; byteContent.append("\r\n"); try { if (xmlContentType(bodyContentType)) { Serializer serializer = makeSerializer(); Vector<XdmNode> content = new Vector<XdmNode>(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); content.add(node); } // FIXME: set serializer properties appropriately! StringWriter writer = new StringWriter(); serializer.setOutputWriter(writer); S9apiUtils.serialize(runtime, content, serializer); writer.close(); //postContent += writer.toString(); byteContent.append(writer.toString()); } else if (jsonContentType(contentType)) { byteContent.append(XMLtoJSON.convert(body)); } else if (!encodeBinary && "base64".equals(bodyEncoding)) { byte[] decoded = Base64.decode(body.getStringValue()); byteContent.append(decoded, decoded.length); } else { StringWriter writer = new StringWriter(); XdmSequenceIterator iter = body.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmNode node = (XdmNode) iter.next(); if (node.getNodeKind() != XdmNodeKind.TEXT) { throw XProcException.stepError(28); } writer.write(node.getStringValue()); } writer.close(); //postContent += writer.toString(); byteContent.append(writer.toString()); } //postContent += "\r\n"; byteContent.append("\r\n"); } catch (IOException ioe) { throw new XProcException(ioe); } catch (SaxonApiException sae) { throw new XProcException(sae); } } //postContent += "--" + boundary + "--\r\n"; byteContent.append("--" + boundary + "--\r\n"); ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(byteContent.content(), multipartContentType); //StringRequestEntity requestEntity = new StringRequestEntity(postContent, multipartContentType, null); method.setRequestEntity(requestEntity); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public void checkPropFindSupportedCalendarComponentSet(Account user, String fullurl, String shorturl, String[] compNames) throws Exception { PropFindMethod method = new PropFindMethod(fullurl); addBasicAuthHeaderForUser(method, user); HttpClient client = new HttpClient(); TestCalDav.HttpMethodExecutor executor; String respBody;//from www.j a va 2 s . com method.addRequestHeader("Content-Type", MimeConstants.CT_TEXT_XML); method.setRequestEntity(new ByteArrayRequestEntity(propFindSupportedCalendarComponentSet.getBytes(), MimeConstants.CT_TEXT_XML)); executor = new TestCalDav.HttpMethodExecutor(client, method, HttpStatus.SC_MULTI_STATUS); respBody = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8); Document doc = W3cDomUtil.parseXMLToDoc(respBody); XPath xpath = XPathFactory.newInstance().newXPath(); xpath.setNamespaceContext(TestCalDav.NamespaceContextForXPath.forCalDAV()); XPathExpression xPathExpr; String text; NodeList result; xPathExpr = xpath.compile("/D:multistatus/D:response/D:href/text()"); result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET); text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING); assertEquals("HREF", shorturl.replaceAll("@", "%40"), text); xPathExpr = xpath.compile("/D:multistatus/D:response/D:propstat/D:status/text()"); text = (String) xPathExpr.evaluate(doc, XPathConstants.STRING); assertEquals("status", "HTTP/1.1 200 OK", text); xPathExpr = xpath .compile("/D:multistatus/D:response/D:propstat/D:prop/C:supported-calendar-component-set/C:comp"); result = (NodeList) xPathExpr.evaluate(doc, XPathConstants.NODESET); assertEquals("Number of comp nodes under supported-calendar-component-set", compNames.length, result.getLength()); List<String> names = Arrays.asList(compNames); for (int ndx = 0; ndx < result.getLength(); ndx++) { org.w3c.dom.Element child = (org.w3c.dom.Element) result.item(ndx); String name = child.getAttribute("name"); assertNotNull("comp should have a 'name' attribute", name); assertTrue(String.format("comp 'name' attribute '%s' should be one of the expected names", name), names.contains(name)); } }
From source file:com.funambol.json.api.dao.FunambolJSONApiDAO.java
protected String sendPostRequest(String REQUEST, String body, long since, long until) throws IOOperationException { String response = null;// ww w.j a v a 2 s . co m PostMethod method = null; try { HttpClient httpClient = new HttpClient(); method = new PostMethod(REQUEST); addSinceUntil(method, since, until); if (log.isTraceEnabled()) { log.trace("\nREQUEST: " + REQUEST + ""); } if (this.sessionid != null) { method.setRequestHeader("Authorization", this.sessionid); } if (body != null) { byte[] raw = body.getBytes(CHARSET); method.setRequestEntity(new ByteArrayRequestEntity(raw, "text/plain; charset=" + CHARSET)); //method.setRequestContentLength(raw.length); //method.setRequestEntity(new StringRequestEntity(body)); //method.setRequestBody(body); if (log.isTraceEnabled()) { log.trace("body: " + body); } } printHeaderFields(method.getRequestHeaders(), "REQUEST"); int code = httpClient.executeMethod(method); response = method.getResponseBodyAsString(); if (log.isTraceEnabled()) { log.trace("RESPONSE code: " + code); } printHeaderFields(method.getResponseHeaders(), "RESPONSE"); } catch (Exception e) { throw new IOOperationException("Error GET Request ", e); } finally { if (method != null) { method.releaseConnection(); } } return response; }
From source file:com.zimbra.qa.unittest.TestCalDav.java
/** * dav - sending http error 302 because: wrong url - redirecting to: * http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics * com.zimbra.cs.dav.DavException: wrong url - redirecting to: * http://pan.local:7070/dav/dav1@pan.local/Calendar/d123f102-42a7-4283-b025-3376dabe53b3.ics * at com.zimbra.cs.dav.resource.CalendarCollection.createItem(CalendarCollection.java:431) * at com.zimbra.cs.dav.service.method.Put.handle(Put.java:49) * at com.zimbra.cs.dav.service.DavServlet.service(DavServlet.java:322) *//*from ww w .j a va 2s . co m*/ @Test public void testCreateUsingClientChosenName() throws ServiceException, IOException { Account dav1 = users[1].create(); String davBaseName = "clientInvented.now"; String calFolderUrl = getFolderUrl(dav1, "Calendar"); String url = String.format("%s%s", calFolderUrl, davBaseName); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, dav1); putMethod.addRequestHeader("Content-Type", "text/calendar"); putMethod.setRequestEntity(new ByteArrayRequestEntity(simpleEvent(dav1), MimeConstants.CT_TEXT_CALENDAR)); if (DebugConfig.enableDAVclientCanChooseResourceBaseName) { HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_CREATED); } else { HttpMethodExecutor.execute(client, putMethod, HttpStatus.SC_MOVED_TEMPORARILY); // Not testing much in this mode but... return; } doGetMethod(url, dav1, HttpStatus.SC_OK); 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); doDeleteMethod(url, dav1, HttpStatus.SC_NO_CONTENT); }
From source file:com.zimbra.qa.unittest.TestCalDav.java
public HttpMethodExecutor doIcalPut(String url, Account authAcct, byte[] vcalendar, int expected) throws IOException { HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(url); addBasicAuthHeaderForUser(putMethod, authAcct); putMethod.addRequestHeader("Content-Type", "text/calendar"); putMethod.setRequestEntity(new ByteArrayRequestEntity(vcalendar, MimeConstants.CT_TEXT_CALENDAR)); return HttpMethodExecutor.execute(client, putMethod, expected); }