Example usage for org.apache.http.entity.mime.content InputStreamBody InputStreamBody

List of usage examples for org.apache.http.entity.mime.content InputStreamBody InputStreamBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content InputStreamBody InputStreamBody.

Prototype

public InputStreamBody(final InputStream in, final String filename) 

Source Link

Usage

From source file:com.revo.deployr.client.call.repository.RepositoryFileUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *//*from w  w  w  .  j  av  a  2 s  .  co  m*/
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        if (options.filename != null)
            entity.addPart("filename",
                    new StringBody(options.filename, "text/plain", Charset.forName("UTF-8")));
        if (options.directory != null)
            entity.addPart("directory",
                    new StringBody(options.directory, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("newversion",
                new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8")));
        if (options.newversionmsg != null)
            entity.addPart("newversionmsg",
                    new StringBody(options.newversionmsg, "text/plain", Charset.forName("UTF-8")));
        if (options.restricted != null)
            entity.addPart("restricted",
                    new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("shared",
                new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("published",
                new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8")));
        if (options.inputs != null)
            entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8")));
        if (options.outputs != null)
            entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("RepositoryFileUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("RepositoryFileUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:com.revo.deployr.client.call.repository.RepositoryDirectoryUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *///from  w w  w .  j a va2 s  . c  o  m
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new InputStreamBody(((InputStream) zipStream), "application/zip"));
        if (options.directory != null)
            entity.addPart("directory",
                    new StringBody(options.directory, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("newversion",
                new StringBody(Boolean.toString(options.newversion), "text/plain", Charset.forName("UTF-8")));
        if (options.restricted != null)
            entity.addPart("restricted",
                    new StringBody(options.restricted, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("shared",
                new StringBody(Boolean.toString(options.shared), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("published",
                new StringBody(Boolean.toString(options.published), "text/plain", Charset.forName("UTF-8")));
        if (options.inputs != null)
            entity.addPart("inputs", new StringBody(options.inputs, "text/plain", Charset.forName("UTF-8")));
        if (options.outputs != null)
            entity.addPart("outputs", new StringBody(options.outputs, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("RepositoryDirectoryUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("RepositoryDirectoryUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:com.revo.deployr.client.call.project.ProjectDirectoryUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *///from  w w  w  .  j  av a2s  . c  om
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("project", new StringBody(project, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("filename", new StringBody(options.filename, "text/plain", Charset.forName("UTF-8")));
        if (options.descr != null)
            entity.addPart("descr", new StringBody(options.descr, "text/plain", Charset.forName("UTF-8")));

        entity.addPart("overwrite",
                new StringBody(Boolean.toString(options.overwrite), "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectDirectoryUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectDirectoryUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:com.revo.deployr.client.call.project.ProjectWorkspaceUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *//*from  w  ww.ja  v a 2s  .co m*/
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("project", new StringBody(this.project, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("name", new StringBody(this.name, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectWorkspaceUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectWorkspaceUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:com.rtl.http.Upload.java

private static String send(String message, InputStream fileIn, String url) throws Exception {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000)
            .build();// 
    post.setConfig(requestConfig);//  ww w  . ja  v  a 2 s.  c om
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setCharset(Charset.forName("UTF-8"));// ?
    ContentType contentType = ContentType.create("text/html", "UTF-8");
    builder.addPart("reqParam", new StringBody(message, contentType));
    builder.addPart("version", new StringBody("1.0", contentType));
    builder.addPart("dataFile", new InputStreamBody(fileIn, "file"));
    post.setEntity(builder.build());
    CloseableHttpResponse response = client.execute(post);
    InputStream inputStream = null;
    String responseStr = "", sCurrentLine = "";
    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        inputStream = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((sCurrentLine = reader.readLine()) != null) {
            responseStr = responseStr + sCurrentLine;
        }
        return responseStr;
    }
    return null;
}

From source file:org.opencastproject.remotetest.server.IngestRestEndpointTest.java

@Test
public void testUploadClient() throws Exception {
    InputStream is = getClass().getResourceAsStream("/mp-test.zip");
    InputStreamBody fileContent = new InputStreamBody(is, "mp-test.zip");

    // create emptiy MediaPackage
    HttpPost postStart = new HttpPost(BASE_URL + "/ingest/addZippedMediaPackage");

    MultipartEntity mpEntity = new MultipartEntity();
    mpEntity.addPart("workflowDefinitionId", new StringBody("full"));
    mpEntity.addPart("userfile", fileContent);
    postStart.setEntity(mpEntity);/*from w  w  w.j  a  v a 2 s.co m*/

    HttpResponse response = client.execute(postStart);
    Assert.assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;/* w  w  w  . j  a v  a2  s  . c  o  m*/
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:fr.liglab.adele.cilia.workbench.restmonitoring.utils.http.HttpHelper.java

public static void post(PlatformID platformID, String path, String paramName, InputStream data)
        throws CiliaException {

    String url = getURL(platformID, path);

    HttpPost httppost = new HttpPost(url);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    InputStreamBody bin = new InputStreamBody(data, paramName);
    reqEntity.addPart(paramName, bin);/*w w  w.j a  v a  2s.  c om*/

    httppost.setEntity(reqEntity);

    // HTTP request
    HttpClient httpClient = getClient();
    try {
        httpClient.execute(httppost, new BasicResponseHandler());
        httpClient.getConnectionManager().shutdown();
    } catch (Exception e) {
        httpClient.getConnectionManager().shutdown();
        throw new CiliaException("can't perform HTTP PUT request", e);
    }
}

From source file:prodoc.StoreRem.java

/**
 * //from  www  .j a  va 2s . co  m
 * @param Id
 * @param Ver
 * @param Bytes
 * @return
 * @throws PDException
 */
protected int Insert(String Id, String Ver, InputStream Bytes) throws PDException {
    VerifyId(Id);
    CloseableHttpResponse response2 = null;
    Node OPDObject = null;
    int Tot = 0;
    try {
        InputStreamBody bin = new InputStreamBody(Bytes, "File" + System.currentTimeMillis());
        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin)
                .addTextBody(ORDER, DriverRemote.S_INSFILE).addTextBody("Id", Id).addTextBody("Ver", Ver)
                .build();
        UrlPost.setEntity(reqEntity);
        response2 = httpclient.execute(UrlPost, context);
        HttpEntity Resp = response2.getEntity();
        Bytes.close();
        Document XMLObjects = DB.parse(Resp.getContent());
        NodeList OPDObjectList = XMLObjects.getElementsByTagName("Result");
        OPDObject = OPDObjectList.item(0);
        if (OPDObject.getTextContent().equalsIgnoreCase("KO")) {
            OPDObjectList = XMLObjects.getElementsByTagName("Msg");
            if (OPDObjectList.getLength() > 0) {
                OPDObject = OPDObjectList.item(0);
                PDException.GenPDException("Server_Error", DriverGeneric.DeCodif(OPDObject.getTextContent()));
            } else
                PDException.GenPDException("Server_Error", "");
        }
    } catch (Exception ex) {
        PDException.GenPDException(ex.getLocalizedMessage(), "");
    } finally {
        DB.reset();
        if (response2 != null)
            try {
                response2.close();
            } catch (IOException ex) {
                PDException.GenPDException(ex.getLocalizedMessage(), "");
            }
    }
    return (Tot);
}

From source file:org.odk.voice.storage.InstanceUploader.java

public int uploadInstance(int instanceId) {
    // configure connection
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
    HttpClientParams.setRedirecting(params, false);

    // setup client
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    HttpPost httppost = new HttpPost(serverUrl);

    MultipartEntity entity = new MultipartEntity();

    // using file storage

    //        // get instance file
    //        File instanceDir = new File(instancePath);
    ///*from   ww  w.  jav  a2  s.  c  o m*/
    //        // find all files in parent directory
    //        File[] files = instanceDir.listFiles();
    //        if (files == null) {
    //            log.warn("No files to upload in " + instancePath);
    //        }

    // mime post
    //          for (int j = 0; j < files.length; j++) {
    //              File f = files[j];
    //              if (f.getName().endsWith(".xml")) {
    //                  // uploading xml file
    //                  entity.addPart("xml_submission_file", new FileBody(f,"text/xml"));
    //                  log.info("added xml file " + f.getName());
    //              } else if (f.getName().endsWith(".wav")) {
    //                  // upload audio file
    //                  entity.addPart(f.getName(), new FileBody(f, "audio/wav"));
    //                  log.info("added audio file" + f.getName());
    //              } else {
    //                log.info("unsupported file type, not adding file: " + f.getName());
    //              }
    //          }

    // using database storage      
    DbAdapter dba = null;
    try {
        dba = new DbAdapter();
        byte[] xml = dba.getInstanceXml(instanceId);
        if (xml == null) {
            log.error("No XML for instanceId " + instanceId);
            return STATUS_ERROR;
        }
        entity.addPart("xml_submission_file", new InputStreamBody(new ByteArrayInputStream(xml), "text/xml"));
        List<InstanceBinary> binaries = dba.getBinariesForInstance(instanceId);
        for (InstanceBinary b : binaries) {
            entity.addPart(b.name, new InputStreamBody(new ByteArrayInputStream(b.binary), b.mimeType, b.name));
        }
    } catch (SQLException e) {
        log.error("SQLException uploading instance", e);
        return STATUS_ERROR;
    } finally {
        dba.close();
    }

    httppost.setEntity(entity);

    // prepare response and return uploaded
    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IOException e) {
        log.error(e);
        return STATUS_ERROR;
    } catch (IllegalStateException e) {
        log.error(e);
        return STATUS_ERROR;
    }

    // check response.
    // TODO: This isn't handled correctly.
    String responseUrl = null;
    Header[] h = response.getHeaders("Location");
    if (h != null && h.length > 0) {
        responseUrl = h[0].getValue();
    } else {
        log.error("Location header was absent");
        return STATUS_ERROR;
    }
    int responseCode = response.getStatusLine().getStatusCode();
    log.info("Response code:" + responseCode);

    // verify that your response came from a known server
    if (responseUrl != null && serverUrl.contains(responseUrl) && responseCode == 201) {
        return STATUS_OK;
    }
    return STATUS_ERROR;
}