Example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

List of usage examples for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods InputStreamRequestEntity InputStreamRequestEntity.

Prototype

public InputStreamRequestEntity(InputStream paramInputStream, String paramString) 

Source Link

Usage

From source file:org.cipango.kaleo.sipunit.WatcherInfoTest.java

/**
 * <pre>/*w  ww . j ava 2s.  c om*/
Bob                Kaleo                 Alice
  |                   |(1) PUBLISH          |
  |                   |<--------------------|
  |                   |(2) 200 OK           |
  |                   |-------------------->|
  |(3) SUBSCRIBE      |                     |
  |Event:presence     |                     |
  |Expires: 0         |                     |
  |------------------>|                     |
  |(4) 200 OK         |                     |
  |<------------------|                     |
  |(5) NOTIFY         |                     | In pending state, so basic status is closed
  |<------------------|                     |
  |(6) 200 OK         |                     |
  |------------------>|                     |
  |                   |(7) SUBSCRIBE        |
  |                   |Event:presence.winfo |
  |                   |<--------------------|
  |                   |(8) 200 OK           |
  |                   |-------------------->|
  |                   |(9) NOTIFY           |
  |                   |-------------------->|
  |                   |(10) 200 OK          |
  |                   |<--------------------|
  |                   |(11) HTTP PUT        | Change subscription state from 
  |                   |<--------------------| allow to polite-block
  |                   |(12) 200 OK          |
  |                   |-------------------->|
  |(13) SUBSCRIBE     |                     |
  |Event:presence     |                     |
  |Expires: 0         |                     |
  |------------------>|                     |
  |(14) 200 OK        |                     |
  |<------------------|                     |
  |(15) NOTIFY        |                     |
  |<------------------|                     |
  |(16) 200 OK        |                     |
  |------------------>|                     |
  |                   |(17) PUBLISH         |
  |                   |Expires = 0          |
  |                   |<--------------------|
  |                   |(18) 200 OK          |
  |                   |-------------------->|
  * </pre>
  * Note: Alice and Bob are inverted in this test.
 */
public void testWaitingState() throws Exception {
    PublishSession publishSession = new PublishSession(getAlicePhone());
    Request publish = publishSession.newPublish(getClass().getResourceAsStream("publish1.xml"), 60); // 1
    publishSession.sendRequest(publish, SipResponse.OK); // 2

    SubscribeSession presenceSession = new SubscribeSession(getBobPhone(), "presence");
    Request subscribe = presenceSession.newInitialSubscribe(0, getAliceUri()); // 3
    presenceSession.sendRequest(subscribe, Response.OK); // 4

    ServerTransaction tx = presenceSession.waitForNotify(); // 5
    System.out.println("5:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 6
    Presence presence = getPresence(tx.getRequest());
    assertEquals(Basic.CLOSED, presence.getTupleArray()[0].getStatus().getBasic());

    SubscribeSession winfoSession = new SubscribeSession(getAlicePhone(), "presence.winfo"); // 7
    subscribe = winfoSession.newInitialSubscribe(60, getAliceUri());
    winfoSession.sendRequest(subscribe, Response.OK); // 8

    tx = winfoSession.waitForNotify(); // 9
    Request notify = tx.getRequest();
    System.out.println("9:\n" + notify);
    winfoSession.sendResponse(Response.OK, tx); // 10 
    SubscriptionStateHeader subState = (SubscriptionStateHeader) notify.getHeader(SubscriptionStateHeader.NAME);
    assertEquals(SubscriptionStateHeader.ACTIVE.toLowerCase(), subState.getState().toLowerCase());
    assertEquals(WatcherInfoEventPackage.NAME,
            ((EventHeader) notify.getHeader(EventHeader.NAME)).getEventType());
    Watcherinfo watcherinfo = getWatcherinfo(notify);
    assertEquals(0, watcherinfo.getVersion().intValue());
    assertEquals(Watcherinfo.State.FULL, watcherinfo.getState());
    assertEquals(1, watcherinfo.getWatcherListArray().length);
    WatcherList watcherList = watcherinfo.getWatcherListArray(0);
    assertEquals(getAliceUri(), watcherList.getResource());
    assertEquals(PresenceEventPackage.NAME, watcherList.getPackage());
    assertEquals(1, watcherList.getWatcherArray().length);
    Watcher watcher = watcherList.getWatcherArray(0);
    assertEquals(Event.TIMEOUT, watcher.getEvent());
    assertEquals(getBobUri(), watcher.getStringValue());
    assertEquals(Status.WAITING, watcher.getStatus());

    HttpClient httpClient = new HttpClient();
    PutMethod put = new PutMethod(getHttpXcapUri() + ALICE_PRES_RULES_URI); // 11

    InputStream is = WatcherInfoTest.class
            .getResourceAsStream("/xcap-root/pres-rules/users/put/elementCondAliceBob.xml");
    RequestEntity entity = new InputStreamRequestEntity(is, "application/xcap-el+xml");
    put.setRequestEntity(entity);

    int result = httpClient.executeMethod(put);
    assertEquals(200, result); // 12
    put.releaseConnection();

    presenceSession = new SubscribeSession(getBobPhone(), "presence");
    subscribe = presenceSession.newInitialSubscribe(0, getAliceUri()); // 13
    presenceSession.sendRequest(subscribe, Response.OK); // 14

    tx = presenceSession.waitForNotify(); // 15
    System.out.println("15:\n" + tx.getRequest());
    presenceSession.sendResponse(Response.OK, tx); // 16
    presence = getPresence(tx.getRequest());
    assertEquals(Basic.OPEN, presence.getTupleArray()[0].getStatus().getBasic());

    publish = publishSession.newUnpublish(); // 25
    publishSession.sendRequest(publish, Response.OK); // 26
}

From source file:org.craftercms.cstudio.alfresco.service.impl.TaxonomyServiceTest.java

@Test
public void testUpdateTaxonomies() throws Exception {
    String ticket = getTicket();/*ww  w. j  a v  a2s .c o  m*/
    File file = new File(updateTaxonomiesFileName);
    PostMethod postMethod = new PostMethod(serverUrl + updateTaxonomyUrl + ticket);
    postMethod.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(file), file.length()));
    HttpClient httpClient = new HttpClient();
    int statusCode = httpClient.executeMethod(postMethod);
    System.out.println(statusCode);
    System.out.println(postMethod.getResponseBodyAsString());
}

From source file:org.craftercms.studio.impl.v1.repository.alfresco.AlfrescoContentRepository.java

/**
 * fire POST request to Alfresco with propert security
 *///from w  w w . j  a v  a  2  s .  co m
protected String alfrescoPostRequest(String uri, Map<String, String> params, InputStream body,
        String bodyMimeType) throws Exception {
    long startTime = System.currentTimeMillis();
    String serviceURL = buildAlfrescoRequestURL(uri, params);
    PostMethod postMethod = new PostMethod(serviceURL);
    postMethod.setRequestEntity(new InputStreamRequestEntity(body, bodyMimeType));

    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    int status = httpClient.executeMethod(postMethod);

    long duration = System.currentTimeMillis() - startTime;
    logger.debug(
            "TRACE: alfrescoPostRequest(String uri, Map<String, String> params, InputStream body, String bodyMimeType; {0}, {1}, {2}, {3}\n\t\tDuration: {4}",
            uri, params, "stream", bodyMimeType, duration);
    return postMethod.getResponseBodyAsString();
}

From source file:org.deegree.framework.util.HttpUtils.java

/**
 * /*from ww  w.j av  a2 s  .  com*/
 * @param url
 * @param content
 * @param timeout
 *            timeout in milliseconds
 * @param user
 *            (can be <code>null</code>)
 * @param password
 *            (can be <code>null</code>)
 * @param contentType
 *            request content mime type (can be <code>null</code>)
 * @param encoding
 *            request encoding (can be <code>null</code>)
 * @param header
 * 
 * @return result of http post request
 * @throws HttpException
 * @throws IOException
 */
public static HttpMethod performHttpPost(String url, InputStream content, int timeout, String user,
        String password, String contentType, String encoding, Map<String, String> header)
        throws HttpException, IOException {
    HttpClient client = new HttpClient();
    URL tmp = new URL(url);
    WebUtils.enableProxyUsage(client, tmp);
    url = tmp.toExternalForm();
    client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    PostMethod pm = new PostMethod(url);
    String ct = contentType;
    if (ct != null && encoding != null) {
        ct += ("; " + encoding);
    }
    if (ct != null) {
        pm.setRequestEntity(new InputStreamRequestEntity(content, ct));
    } else {
        pm.setRequestEntity(new InputStreamRequestEntity(content));
    }
    if (header != null) {
        Iterator<String> iter = header.keySet().iterator();
        while (iter.hasNext()) {
            String key = (String) iter.next();
            if (!"content-length".equalsIgnoreCase(key)) {
                pm.addRequestHeader(new Header(key, header.get(key)));
            }
        }
    }

    setHTTPCredentials(pm, user, password);
    client.executeMethod(pm);
    if (LOG.getLevel() == ILogger.LOG_DEBUG) {
        LOG.logDebug(pm.getResponseBodyAsString());
    }
    if (pm.getStatusCode() != 200) {
        throw new HttpException("status code: " + pm.getStatusCode());
    }
    return pm;
}

From source file:org.eclipse.lyo.samples.sharepoint.SharepointConnector.java

public int createDocument(HttpServletResponse response, String library, FileItem item)
        throws UnrecognizedValueTypeException, ShareServerException {
    //   System.out.println("createDocument: uri='" + uri + "'");
    //SharepointResource sharepointResource = new SharepointResource(uri);

    //       String filename = resource.getSource();
    //       //ww w. j a v  a  2 s . c o  m
    //      OEntity newProduct = odatac.createEntity("Empire").properties(OProperties.int32("Id", 10))
    //                                                       .properties(OProperties.string("Name", filename))
    //                                                       .properties(OProperties.string("ContentType","Document"))
    //                                                       .properties(OProperties.string("Title","Architecture"))
    //                                                       .properties(OProperties.string("ApprovalStatus","2"))
    //                                                       .properties(OProperties.string("Path","/Empire"))   
    //                                                         .execute();  

    // no obvious API in odata4j to create a document, default apache http Create
    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    BufferedReader br = null;
    int returnCode = 500;
    PostMethod method = null;
    try {
        client.setConnectionTimeout(8000);

        method = new PostMethod(SharepointInitializer.getSharepointUri() + "/" + library);
        String userPassword = SharepointInitializer.getUsername() + ":" + SharepointInitializer.getPassword();
        String encoding = Base64.encodeBase64String(userPassword.getBytes());
        encoding = encoding.replaceAll("\r\n?", "");
        method.setRequestHeader("Authorization", "Basic " + encoding);
        method.addRequestHeader("Content-type", item.getContentType());
        method.addRequestHeader(IConstants.HDR_SLUG, "/" + library + "/" + item.getName());

        //InputStream is =  new FileInputStream("E:\\odata\\sharepoint\\DeathStarTest.doc");

        RequestEntity entity = new InputStreamRequestEntity(item.getInputStream(), "application/msword");
        method.setRequestEntity(entity);
        method.setDoAuthentication(true);

        returnCode = client.executeMethod(method);

        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.err.println("The Post method is not implemented by this URI");
            // still consume the response body
            method.getResponseBodyAsString();
        } else {
            //br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            InputStream is = method.getResponseBodyAsStream();
            //br = new BufferedReader(new InputStreamReader(is));          
            //    String readLine;
            //    while(((readLine = br.readLine()) != null)) {
            //      System.out.println(readLine);
            //    }

            response.setContentType("text/html");
            //response.setContentType("application/atom+xml");
            //response.setContentLength(is.getBytes().length);
            response.setStatus(IConstants.SC_OK);
            //response.getWriter().write("<html><head><title>hello world</title></head><body><p>hello world!</p></body></html>");
            //response.getWriter().write(method.getResponseBodyAsString());

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder parser = factory.newDocumentBuilder();
            Document doc = parser.parse(is);
            Element root = doc.getDocumentElement();

            System.out.println("Root element of the doc is " + root.getNodeName());

            //         String msftdPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices";
            //         String msftmPrefix = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";

            String id = null;
            String name = null;
            NodeList nl = root.getElementsByTagName("d:Id");
            if (nl.getLength() > 0) {
                id = nl.item(0).getFirstChild().getNodeValue();
            }

            //nl = root.getElementsByTagName("d:ContentType");         
            //if (nl.getLength() > 0) {
            //   type = nl.item(0).getFirstChild().getNodeValue(); 
            //}

            nl = root.getElementsByTagName("d:Name");
            if (nl.getLength() > 0) {
                name = nl.item(0).getFirstChild().getNodeValue();
            }

            response.getWriter().write("<html>");
            response.getWriter().write("<head>");
            response.getWriter().write("</head>");
            response.getWriter().write("<body>");
            response.getWriter().write("<p>" + name + " was created with an Id =" + id + "</p>");
            response.getWriter().write("</body>");
            response.getWriter().write("</html>");

            //response.getWriter().write(is.content);
            //String readLine;
            //while(((readLine = br.readLine()) != null)) {
            //   response.getWriter().write(readLine);
            //}
            //response.setContentType(IConstants.CT_XML);
            //response.getWriter().write(is.toString()); 
            //response.setStatus(IConstants.SC_OK);
            //test 
            //   String readLine;
            //   while(((readLine = br.readLine()) != null)) {
            //     System.out.println(readLine);
            //   }
        }
    } catch (Exception e) {
        System.err.println(e);
        e.printStackTrace();
    } finally {
        if (method != null)
            method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }
    return returnCode;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static String put(URL url, InputStream inputStream, String contentType, String encoding)
        throws OseeCoreException {
    int statusCode = -1;
    String response = null;/* w  w w .  ja v a  2 s.  com*/
    PutMethod method = new PutMethod(url.toString());

    InputStream responseInputStream = null;
    AcquireResult result = new AcquireResult();
    try {
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(inputStream, contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        responseInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode != HttpURLConnection.HTTP_CREATED) {
            String exceptionString = Lib.inputStreamToString(responseInputStream);
            throw new OseeCoreException(exceptionString);
        } else {
            responseInputStream = method.getResponseBodyAsStream();
            response = Lib.inputStreamToString(responseInputStream);
        }

    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(responseInputStream);
        method.releaseConnection();
    }
    return response;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static AcquireResult delete(URL url, String xml, String contentType, String encoding,
        OutputStream outputStream) throws OseeCoreException {
    AcquireResult result = new AcquireResult();
    int statusCode = -1;

    org.eclipse.osee.framework.core.util.DeleteMethod method = new DeleteMethod(url.toString());

    InputStream httpInputStream = null;
    try {// ww w. j av  a2 s  .  c  om
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(Lib.stringToInputStream(xml), contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        httpInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode == HttpStatus.SC_ACCEPTED || statusCode == HttpStatus.SC_OK) {
            Lib.inputStreamToOutputStream(httpInputStream, outputStream);
        } else {
            String exceptionString = Lib.inputStreamToString(httpInputStream);
            throw new OseeCoreException(exceptionString);
        }
    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(httpInputStream);
        result.setCode(statusCode);
        method.releaseConnection();
    }
    return result;
}

From source file:org.eclipse.osee.framework.core.util.HttpProcessor.java

public static AcquireResult post(URL url, InputStream inputStream, String contentType, String encoding,
        OutputStream outputStream) throws OseeCoreException {
    AcquireResult result = new AcquireResult();
    int statusCode = -1;

    PostMethod method = new PostMethod(url.toString());

    InputStream httpInputStream = null;
    try {/*from  w ww. j a  va 2  s .  c  o  m*/
        method.setRequestHeader(CONTENT_ENCODING, encoding);
        method.setRequestEntity(new InputStreamRequestEntity(inputStream, contentType));

        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        statusCode = executeMethod(url, method);
        httpInputStream = method.getResponseBodyAsStream();
        result.setContentType(getContentType(method));
        result.setEncoding(method.getResponseCharSet());
        if (statusCode == HttpStatus.SC_ACCEPTED || statusCode == HttpStatus.SC_OK) {
            Lib.inputStreamToOutputStream(httpInputStream, outputStream);
        } else {
            String exceptionString = Lib.inputStreamToString(httpInputStream);
            throw new OseeCoreException(exceptionString);
        }
    } catch (Exception ex) {
        OseeExceptions.wrapAndThrow(ex);
    } finally {
        Lib.close(httpInputStream);
        result.setCode(statusCode);
        method.releaseConnection();
    }
    return result;
}

From source file:org.eclipse.smarthome.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * //from  w  w  w.  j a  va2 s. c o m
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        String responseBody = IOUtils.toString(method.getResponseBodyAsStream());
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:org.exoplatform.bonitaextension.connectors.webdav.common.WebDAVClient.java

public WebDAVResponse uploadFile(String destinationUri, InputStream fis, String contentType) throws Exception {

    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine(//from  w ww  .  j a  v a2 s .  co m
                "uploadFile '" + "' with mimeType '" + contentType + "' to folder '" + destinationUri + "'");
    }

    //we first must check if folder exists
    // if not, create it.

    //we assume that destinationUri starts with /rest/private/jcr/repository/collaboration/
    String pathToCheck = destinationUri.substring("/rest/private/jcr/repository/collaboration/".length(),
            destinationUri.lastIndexOf("/"));
    // we dont want file name
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("PathToCheck : " + pathToCheck);
    }

    String[] foldersToCheck = pathToCheck.split("/");
    String currentUriTest = "/rest/private/jcr/repository/collaboration";
    for (int i = 0; i < foldersToCheck.length; i++) {
        String parentUri = currentUriTest + "/";
        currentUriTest += "/" + foldersToCheck[i];
        WebDAVResponse responseListFolder = listFolder(currentUriTest);

        if (responseListFolder.getStatusCode().equals("404")) {
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.fine("Need to create folder " + foldersToCheck[i]);
            }
            WebDAVResponse responseCreateFolder = createFolder(parentUri, foldersToCheck[i]);

            if (!responseCreateFolder.getStatusCode().equals("201")) {
                throw new Exception("Unable to create folder " + currentUriTest + " on destination platform");
            }
        }

    }

    PutMethod httpMethod = new PutMethod(destinationUri);

    RequestEntity requestEntity = new InputStreamRequestEntity(fis, contentType);
    httpMethod.setRequestEntity(requestEntity);
    client.executeMethod(httpMethod);

    WebDAVResponse objResponse = processResponse(httpMethod, true);
    httpMethod.releaseConnection();
    return objResponse;
}