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:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java

private RequestEntity createEntity(RDFInput input) throws IOException {
    if (input.isFile()) {
        File file = input.getFile();
        return new FileRequestEntity(file, input.getFormat().getDefaultMIMEType());
    } else if (input.isStream()) {
        return new InputStreamRequestEntity(input.getStream(), input.getFormat().getDefaultMIMEType());
    } else if (input.isStatements()) {
        return createEntity(input.getStatements());
    } else {//  w w w.  jav a2 s.  c o m
        throw new AssertionError();
    }
}

From source file:de.mpg.mpdl.inge.pubman.web.multipleimport.processor.ZfNProcessor.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*from  ww w.j  a va 2  s . com*/
 * @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...
 */
private 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, -1));
    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();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}

From source file:de.mpg.escidoc.pubman.multipleimport.processor.ZfNProcessor.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * @param InputStream to upload// ww  w  . jav a  2 s.co m
 * @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...
 */
private URL uploadFile(InputStream in, 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");
    method.setRequestEntity(new InputStreamRequestEntity(in, -1));
    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();
    XmlTransformingBean ctransforming = new XmlTransformingBean();
    return ctransforming.transformUploadResponseToFileURL(response);
}

From source file:eu.learnpad.core.rest.XWikiRestUtils.java

public boolean putAttachment(String wikiName, String spaceName, String pageName, String attachmentName,
        InputStream attachment) {
    HttpClient httpClient = restResource.getClient();

    String uri = String.format("%s/wikis/%s/spaces/%s/pages/%s/attachments/%s", DefaultRestResource.REST_URI,
            wikiName, spaceName, pageName, attachmentName);
    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", "application/xml");
    putMethod.addRequestHeader("Accept-Ranges", "bytes");
    RequestEntity fileRequestEntity = new InputStreamRequestEntity(attachment, "application/xml");
    putMethod.setRequestEntity(fileRequestEntity);
    try {/*from w  w w  .j a v  a  2s  .  co m*/
        httpClient.executeMethod(putMethod);
        return true;
    } catch (HttpException e) {
        String message = String.format("Unable to process PUT request for the attachment '%s:%s.%s@%s'.",
                wikiName, spaceName, pageName, attachmentName);
        logger.error(message, e);
        return false;
    } catch (IOException e) {
        String message = String.format("Unable to PUT the attachment '%s:%s.%s@%s'.", wikiName, spaceName,
                pageName, attachmentName);
        logger.error(message, e);
        return false;
    }
}

From source file:com.zimbra.qa.unittest.TestUserServlet.java

/** Bug 84362 Confirm that import with London timezone incorrectly identified as "GMT" works */
public void testIcsImportExportGMTtoLondon() throws IOException, ServiceException {
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    String calName = NAME_PREFIX + "3rdCalendar";
    String calUri = String.format("/%s?fmt=ics", calName);
    TestUtil.createFolder(mbox, calName, ZFolder.View.appointment);
    URI uri = mbox.getRestURI(calUri);
    HttpClient client = mbox.getHttpClient(uri);
    PostMethod post = new PostMethod(uri.toString());
    post.setRequestEntity(new InputStreamRequestEntity(
            new ByteArrayInputStream(TestCalDav.LOTUS_NOTES_WITH_BAD_GMT_TZID.getBytes()),
            MimeConstants.CT_TEXT_CALENDAR));
    ZimbraLog.test.debug("testIcsImportExport:ICS to be imported:%s", TestCalDav.LOTUS_NOTES_WITH_BAD_GMT_TZID);
    TestCalDav.HttpMethodExecutor.execute(client, post, HttpStatus.SC_OK);
    uri = mbox.getRestURI(calUri);//from   ww w .  j av  a  2 s  . c o  m
    GetMethod get = new GetMethod(uri.toString());
    TestCalDav.HttpMethodExecutor executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    String respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported:%s", respIcal);
    // If this is present, it implies that both the timezone and the references have been correctly changed.
    String dtstartWithNewTZID = "DTSTART;TZID=\"Europe/London\":20150721T140000";
    int dtstartIndex = respIcal.indexOf(dtstartWithNewTZID);
    assertTrue(String.format("'%s' should be present", dtstartWithNewTZID), -1 != dtstartIndex);
}

From source file:it.geosolutions.geonetwork.util.HTTPUtils.java

/**
 * POSTs a Stream content to the given URL.
 *
 * @param url       The URL where to connect to.
 * @param content   The content to be sent as an InputStream.
 * @param contentType The content-type to advert in the POST.
 * @return          The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException//from   w  ww.  ja  v a  2  s.  c om
 * @return the HTTP response or <TT>null</TT> on errors.
 */
public String post(String url, InputStream content, String contentType) {
    return post(url, new InputStreamRequestEntity(content, contentType));
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static RequestEntity toRequestEntity(Object value) throws PageException {
    if (value instanceof RequestEntity)
        return (RequestEntity) value;

    else if (value instanceof InputStream) {
        return new InputStreamRequestEntity((InputStream) value, "application/octet-stream");
    } else if (Decision.isCastableToBinary(value, false)) {
        return new ByteArrayRequestEntity(Caster.toBinary(value));
    } else {/* ww  w.jav  a2s . co  m*/
        return new StringRequestEntity(Caster.toString(value));
    }
}

From source file:hu.sztaki.lpds.pgportal.services.dspace.LNIclient.java

/**
 * Set up and initiate the PUT method, but leave the actual
 * technique of writing the request body to the caller.
 *//*from   ww w. ja v a  2  s. c om*/
private void startPutInternal(String collection, String type, NameValuePair options[], InputStream is)
        throws IOException, HttpException {
    if (lastPut != null)
        throw new IOException("Bad state: startPUT called twice without finishPUT.");

    String url = lookupHandle(collection);

    NameValuePair args[] = new NameValuePair[1 + (options == null ? 0 : options.length)];
    args[0] = new NameValuePair("package", type);
    if (options != null) {
        for (int i = 0; i < options.length; ++i)
            args[i + 1] = options[i];
    }
    lastPut = new PutMethod(url);
    lastPut.setDoAuthentication(true);
    lastPut.setQueryString(args);
    lastPut.setRequestEntity(new InputStreamRequestEntity(is, -1));
}

From source file:com.legstar.http.client.CicsHttp.java

/**
 * Create and populate an HTTP post method to send the execution request.
 * @param request the request to be serviced
 * @param hostURLPath the target host URL path
 * @return the new post method/*from  w  w w. j  a  v a2  s.  com*/
 * @throws RequestException if post method cannot be created
 */
protected PostMethod createPostMethod(final LegStarRequest request, final String hostURLPath)
        throws RequestException {

    if (_log.isDebugEnabled()) {
        _log.debug("enter createPostMethod(request)");
    }

    PostMethod postMethod = new PostMethod();

    /* Point to URL under CICS Web Support */
    postMethod.setPath(hostURLPath);

    /* Pass on trace data to host via HTTP headers */
    postMethod.setRequestHeader(REQUEST_TRACE_MODE_HHDR,
            Boolean.toString(request.getAddress().isHostTraceMode()));
    postMethod.setRequestHeader(REQUEST_ID_HHDR, request.getID());

    /* Create the binary content */
    try {
        postMethod.setRequestEntity(new InputStreamRequestEntity(request.getRequestMessage().sendToHost(),
                APPLICATION_CONTENT_TYPE));
    } catch (HostMessageFormatException e) {
        throw new RequestException(e);
    }

    return postMethod;

}

From source file:Interface.FramePrincipal.java

private void bt_uplActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_uplActionPerformed

    File diretorio = new File(dir_arq.getText());
    File file = new File(dir_arq.getText() + "/" + nom_arq.getText());

    if (!diretorio.exists()) {
        JOptionPane.showMessageDialog(null, "Informe um diretrio vlido!");
    } else if (!file.exists() || "".equals(nom_arq.getText())) {
        JOptionPane.showMessageDialog(null, "Informe um arquivo vlido!");
    } else {//ww w  .j  a  va 2 s  .  co m
        try {
            //////////////////////////////////////// Validar tamanho de arquivo/////////////////////////////////////////////////               
            RandomAccessFile arquivo = new RandomAccessFile(dir_arq.getText() + "/" + nom_arq.getText(), "r");
            long tamanho = arquivo.length();

            if (tamanho >= 104857600) {
                JOptionPane.showMessageDialog(null, "Arquivo excedeu o tamanho mximo de 100 MB!");
                arquivo.close();
                return;
            }

            //////////////////////////////////////////// Carrega arquivo para o bucket /////////////////////////////////////////
            HttpClient client = new HttpClient();
            client.getParams().setParameter("http.useragent", "Test Client");

            BufferedReader br = null;
            String apikey = "AIzaSyAuKiAdUluAz4IEaOUoXldA8XuwEbty5V8";

            File input = new File(dir_arq.getText() + "/" + nom_arq.getText());

            PostMethod method = new PostMethod("https://www.googleapis.com/upload/storage/v1/b/" + bac.getNome()
                    + "/o?uploadType=media&name=" + nom_arq.getText());
            method.addParameter("uploadType", "media");
            method.addParameter("name", nom_arq.getText());
            method.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            //       method.setRequestHeader("Content-type", "image/png; charset=ISO-8859-1");
            method.setRequestHeader("Content-type", "application/octet-stream");

            //       try{
            int returnCode = client.executeMethod(method);

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

        } catch (Exception e) {
            System.err.println(e);

        }
        JOptionPane.showMessageDialog(null, "Arquivo carregado com sucesso!");
    }
}