Example usage for org.apache.http.entity.mime MultipartEntityBuilder addBinaryBody

List of usage examples for org.apache.http.entity.mime MultipartEntityBuilder addBinaryBody

Introduction

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

Prototype

public MultipartEntityBuilder addBinaryBody(final String name, final InputStream stream,
            final ContentType contentType, final String filename) 

Source Link

Usage

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

void buildFilePart(final KeyDataPair pairWithFile, final MultipartEntityBuilder builder) throws IOException {
    String mimeType = pairWithFile.getMimeType();
    if (mimeType == null) {
        mimeType = "application/octet-stream";
    }/*from   www. j a v a  2  s  . co  m*/

    final ContentType contentType = ContentType.create(mimeType);
    final File file = pairWithFile.getFile();

    if (pairWithFile.getData() != null) {
        final String filename;
        if (file == null) {
            filename = pairWithFile.getValue();
        } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
            filename = file.getAbsolutePath();
        } else {
            filename = file.getName();
        }

        builder.addBinaryBody(pairWithFile.getName(), new ByteArrayInputStream(pairWithFile.getData()),
                contentType, filename);
        return;
    }

    if (file == null) {
        builder.addPart(pairWithFile.getName(),
                // Overridden in order not to have a chunked response.
                new InputStreamBody(new ByteArrayInputStream(new byte[0]), contentType,
                        pairWithFile.getValue()) {
                    @Override
                    public long getContentLength() {
                        return 0;
                    }
                });
        return;
    }

    String filename;
    if (pairWithFile.getFile() == null) {
        filename = pairWithFile.getValue();
    } else if (webClient_.getBrowserVersion().hasFeature(HEADER_CONTENT_DISPOSITION_ABSOLUTE_PATH)) {
        filename = pairWithFile.getFile().getAbsolutePath();
    } else {
        filename = pairWithFile.getFile().getName();
    }
    builder.addBinaryBody(pairWithFile.getName(), pairWithFile.getFile(), contentType, filename);
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Upload a sample datatset from resources
 * /*from w  w  w.  ja  va  2  s  .  co m*/
 * @param datasetName   Name for the dataset
 * @param version       Version for the dataset
 * @param resourcePath  Relative path the CSV file in resources
 * @return              Response from the backend
 * @throws              MLHttpClientException 
 */
public CloseableHttpResponse uploadDatasetFromCSV(String datasetName, String version, String resourcePath)
        throws MLHttpClientException {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    try {
        HttpPost httpPost = new HttpPost(getServerUrlHttps() + "/api/datasets/");
        httpPost.setHeader(MLIntegrationTestConstants.AUTHORIZATION_HEADER, getBasicAuthKey());

        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.addPart("description",
                new StringBody("Sample dataset for Testing", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("sourceType", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("destination", new StringBody("file", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("dataFormat", new StringBody("CSV", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addPart("containsHeader", new StringBody("true", ContentType.TEXT_PLAIN));

        if (datasetName != null) {
            multipartEntityBuilder.addPart("datasetName", new StringBody(datasetName, ContentType.TEXT_PLAIN));
        }
        if (version != null) {
            multipartEntityBuilder.addPart("version", new StringBody(version, ContentType.TEXT_PLAIN));
        }
        if (resourcePath != null) {
            File file = new File(getResourceAbsolutePath(resourcePath));
            multipartEntityBuilder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM,
                    "IndiansDiabetes.csv");
        }
        httpPost.setEntity(multipartEntityBuilder.build());
        return httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to upload dataset from csv " + resourcePath, e);
    }
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#publish(java.io.InputStream,
 *      java.lang.String, java.lang.String, java.lang.String, java.lang.String,
 *      java.lang.String, org.opentravel.schemacompiler.model.TLLibraryStatus)
 *//*from   w w w.ja v  a  2 s .  co  m*/
@Override
public RepositoryItem publish(InputStream unmanagedContent, String filename, String libraryName,
        String namespace, String versionIdentifier, String versionScheme, TLLibraryStatus initialStatus)
        throws RepositoryException {
    try {
        // Build a repository item to represent the content that we are attempting to publish
        String targetNS = RepositoryNamespaceUtils.normalizeUri(namespace);
        RepositoryItemImpl item = new RepositoryItemImpl();
        String baseNamespace = targetNS;

        if (versionScheme != null) {
            VersionScheme vScheme = VersionSchemeFactory.getInstance().getVersionScheme(versionScheme);
            baseNamespace = vScheme.getBaseNamespace(targetNS);
        }

        item.setRepository(this);
        item.setNamespace(targetNS);
        item.setBaseNamespace(baseNamespace);
        item.setFilename(filename);
        item.setVersion(versionIdentifier);
        item.setStatus(initialStatus);
        item.setState(RepositoryItemState.MANAGED_UNLOCKED);

        // Invoke the remote web service call to perform the publication
        HttpPost postRequest = newPostRequest(PUBLISH_ENDPOINT);
        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();

        if (versionScheme != null) {
            mpEntity.addTextBody("versionScheme", versionScheme);
        }
        mpEntity.addBinaryBody("fileContent", toByteArray(unmanagedContent), ContentType.DEFAULT_BINARY,
                filename);
        mpEntity.addTextBody("namespace", targetNS);
        mpEntity.addTextBody("libraryName", libraryName);
        mpEntity.addTextBody("version", versionIdentifier);
        mpEntity.addTextBody("status", initialStatus.toRepositoryStatus().toString());
        postRequest.setEntity(mpEntity.build());

        log.info("Sending publish request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(postRequest);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Publish response received - Status OK");
        return item;

    } catch (VersionSchemeException e) {
        throw new RepositoryException(e.getMessage(), e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        try {
            if (unmanagedContent != null)
                unmanagedContent.close();
        } catch (Throwable t) {
        }
    }
}

From source file:nzilbb.bas.BAS.java

/**
 * Invoke the general MAUS service, for forced alignment given a WAV file and a phonemic transcription.
 * @param LANGUAGE <a href="https://tools.ietf.org/html/rfc5646">RFC 5646</a> tag for identifying the language.
 * @param SIGNAL The signal, in WAV format.
 * @param BPF Phonemic transcription of the utterance to be segmented. Format is a <a href="http://www.bas.uni-muenchen.de/forschung/Bas/BasFormatseng.html">BAS Partitur Format (BPF)</a> file with a KAN tier.
 * @param MINPAUSLEN Controls the behaviour of optional inter-word silence. If set to 1, maus will detect all inter-word silence intervals that can be found (minimum length for a silence interval is then 10 msec = 1 frame). If set to values n&gt;1, the minimum length for an inter-word silence interval to be detected is set to n&times;10 msec.
 * @param STARTWORD If set to a value n&gt;0, this option causes maus to start the segmentation with the word number n (word numbering in BPF starts with 0).
 * @param ENDWORD If set to a value n&lt;999999, this option causes maus to end the segmentation with the word number n (word numbering in BPF starts with 0). 
 * @param RULESET MAUS rule set file; UTF-8 encoded; one rule per line; two different file types defined by the extension: '*.nrul' : phonological rule set without statistical information
 * @param OUTFORMAT Defines the output format:
 *  <ul>//from w  w  w .ja  v  a  2  s.c om
 *   <li>"TextGrid" - a praat compatible TextGrid file</li> 
 *   <li>"par" or "mau-append" - the input BPF file with a new (or replaced) tier MAU</li>
 *   <li>"csv" or "mau" - only the BPF MAU tier (CSV table)</li> 
 *   <li>"legacyEMU" - a file with extension *.EMU that contains in the first part the Emu hlb file (*.hlb) and in the second part the Emu phonetic segmentation (*.phonetic)</li>
 *   <li>emuR - an Emu compatible *_annot.json file</li>
 *  </ul>
 * @param MAUSSHIFT If set to n, this option causes the calculated MAUS segment boundaries to be shifted by n msec (default: 10) into the future.
 * @param INSPROB The option INSPROB influences the probability of deletion of segments. It is a constant factor (a constant value added to the log likelihood score) after each segment. Therefore, a higher value of INSPROB will cause the probability of segmentations with more segments go up, thus decreasing the probability of deletions (and increasing the probability of insertions, which are rarely modelled in the rule sets).
 * @param INSKANTEXTGRID Switch to create an additional tier in the TextGrid output file with a word segmentation labelled with the canonic phonemic transcript.
 * @param INSORTTEXTGRID Switch to create an additional tier ORT in the TextGrid output file with a word segmentation labelled with the orthographic transcript (taken from the input ORT tier)
 * @param USETRN  If set to true, the service searches the input BPF for a TRN tier. The synopsis for a TRN entry is: 'TRN: (start-sample) (duration-sample) (word-link-list) (label)', e.g. 'TRN: 23654 56432 0,1,2,3,4,5,6 sentence1' (the speech within the recording 'sentence1' starts with sample 23654, last for 56432 samples and covers the words 0-6). If only one TRN entry is found, the segmentation is restricted within a time range given by this TRN tier entry.
 * @param OUTSYMBOL Defines the encoding of phonetic symbols in output. 
 *  <ul>
 *   <li>"sampa" - (default), phonetic symbols are encoded in language specific SAM-PA (with some coding differences to official SAM-PA</li>
 *   <li>"ipa" - the service produces UTF-8 IPA output.</li> 
 *   <li>"manner" - the service produces IPA manner of articulation for each segment; possible values are: silence, vowel, diphthong, plosive, nasal, fricative, affricate, approximant, lateral-approximant, ejective.</li>
 *   <li>"place" - the service produces IPA place of articulation for each segment; possible values are: silence, labial, dental, alveolar, post-alveolar, palatal, velar, uvular, glottal, front, central, back.</li> </ul>
 * @param NOINITIALFINALSILENCE Switch to suppress the automatic modeling on a leading/trailing silence interval. 
 * @param WEIGHT weights the influence of the statistical pronunciation model against the acoustical scores. More precisely WEIGHT is multiplied to the pronunciation model score (log likelihood) before adding the score to the acoustical score within the search. Since the pronunciation model in most cases favors the canonical pronunciation, increasing WEIGHT will at some point cause MAUS to choose always the canonical pronunciation; lower values of WEIGHT will favor less probable paths be selected according to acoustic evidence
 * @param MODUS Operation modus of MAUS: 
 *  <ul>
 *   <li>"standard" (default) - the segmentation and labelling using the MAUS technique as described in Schiel ICPhS 1999.</li> 
 *   <li>"align" - a forced alignment is performed on the input SAM-PA string defined in the KAN tier of the BPF.</li>
 * </ul>
 * @return The response to the request.
 * @throws IOException If an IO error occurs.
 * @throws ParserConfigurationException If the XML parser for parsing the response could not be configured.
 */
public BASResponse MAUS(String LANGUAGE, InputStream SIGNAL, InputStream BPF, String OUTFORMAT,
        String OUTSYMBOL, Integer MINPAUSLEN, Integer STARTWORD, Integer ENDWORD, InputStream RULESET,
        Integer MAUSSHIFT, Double INSPROB, Boolean INSKANTEXTGRID, Boolean INSORTTEXTGRID, Boolean USETRN,
        Boolean NOINITIALFINALSILENCE, Double WEIGHT, String MODUS)
        throws IOException, ParserConfigurationException {
    if (OUTSYMBOL == null)
        OUTSYMBOL = "sampa";
    // "40 msec seems to be the border of perceivable silence, we set this option default to 5"
    if (MINPAUSLEN == null)
        MINPAUSLEN = 5;
    HttpPost request = new HttpPost(getMAUSUrl());
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .addTextBody("LANGUAGE", languageTagger.tag(LANGUAGE))
            .addBinaryBody("SIGNAL", SIGNAL, ContentType.create("audio/wav"), "BAS.wav")
            .addBinaryBody("BPF", BPF, ContentType.create("text/plain-bas"), "BAS.par")
            .addTextBody("OUTFORMAT", OUTFORMAT).addTextBody("OUTSYMBOL", OUTSYMBOL);
    if (USETRN != null)
        builder.addTextBody("USETRN", USETRN.toString());
    if (MINPAUSLEN != null)
        builder.addTextBody("MINPAUSLEN", MINPAUSLEN.toString());
    if (STARTWORD != null)
        builder.addTextBody("STARTWORD", STARTWORD.toString());
    if (ENDWORD != null)
        builder.addTextBody("ENDWORD", ENDWORD.toString());
    if (RULESET != null)
        builder.addBinaryBody("RULESET", RULESET, ContentType.create("text/plain"), "RULESET.txt");
    if (MAUSSHIFT != null)
        builder.addTextBody("MAUSSHIFT", MAUSSHIFT.toString());
    if (INSPROB != null)
        builder.addTextBody("INSPROB", INSPROB.toString());
    if (INSKANTEXTGRID != null)
        builder.addTextBody("INSKANTEXTGRID", INSKANTEXTGRID.toString());
    if (INSORTTEXTGRID != null)
        builder.addTextBody("INSORTTEXTGRID", INSORTTEXTGRID.toString());
    if (NOINITIALFINALSILENCE != null)
        builder.addTextBody("NOINITIALFINALSILENCE", NOINITIALFINALSILENCE.toString());
    if (WEIGHT != null)
        builder.addTextBody("WEIGHT", WEIGHT.toString());
    if (MODUS != null)
        builder.addTextBody("MODUS", MODUS.toString());
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(request);
    HttpEntity result = httpResponse.getEntity();
    return new BASResponse(result.getContent());
}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#commit(org.opentravel.schemacompiler.repository.RepositoryItem)
 *//* w w  w.j a va2  s  .c  o  m*/
@Override
public void commit(RepositoryItem item) throws RepositoryException {
    InputStream wipContent = null;
    try {
        validateRepositoryItem(item);

        // Obtain a file stream for the item's WIP content
        File wipFile = manager.getFileManager().getLibraryWIPContentLocation(item.getBaseNamespace(),
                item.getFilename());

        if (!wipFile.exists()) {
            throw new RepositoryException("The work-in-process file does not exist: " + item.getFilename());
        }
        wipContent = new FileInputStream(wipFile);

        // Build the HTTP request for the remote service
        RepositoryItemIdentityType itemIdentity = createItemIdentity(item);
        Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller();
        HttpPost request = newPostRequest(COMMIT_ENDPOINT);
        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        StringWriter xmlWriter = new StringWriter();

        marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter);
        mpEntity.addTextBody("item", xmlWriter.toString(), ContentType.TEXT_XML);
        mpEntity.addBinaryBody("fileContent", toByteArray(wipContent), ContentType.DEFAULT_BINARY,
                item.getFilename());

        // mpEntity.addPart( "fileContent", new InputStreamBody(wipContent, item.getFilename())
        // );

        request.setEntity(mpEntity.build());

        // Send the web service request and check the response
        log.info("Sending commit request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(request);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Commit response received - Status OK");

        // Update the local cache with the content we just sent to the remote web service
        downloadContent(item, true);

    } catch (JAXBException e) {
        throw new RepositoryException("The format of the library meta-data is unreadable.", e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        try {
            if (wipContent != null)
                wipContent.close();
        } catch (Throwable t) {
        }
    }
}

From source file:com.lgallardo.qbittorrentclient.JSONParser.java

public String postCommand(String command, String hash) throws JSONParserStatusCodeException {

    String key = "hash";

    String urlContentType = "application/x-www-form-urlencoded";

    String limit = "";
    String tracker = "";

    String boundary = null;//from www . j  av  a  2  s  . c  o m

    String fileId = "";

    String filePriority = "";

    String result = "";

    StringBuilder fileContent = null;

    HttpResponse httpResponse;
    DefaultHttpClient httpclient;

    String url = "";

    String label = "";

    if ("start".equals(command) || "startSelected".equals(command)) {
        url = "command/resume";
    }

    if ("pause".equals(command) || "pauseSelected".equals(command)) {
        url = "command/pause";
    }

    if ("delete".equals(command) || "deleteSelected".equals(command)) {
        url = "command/delete";
        key = "hashes";
    }

    if ("deleteDrive".equals(command) || "deleteDriveSelected".equals(command)) {
        url = "command/deletePerm";
        key = "hashes";
    }

    if ("addTorrent".equals(command)) {
        url = "command/download";
        key = "urls";
    }

    if ("addTracker".equals(command)) {
        url = "command/addTrackers";
        key = "hash";

    }

    if ("addTorrentFile".equals(command)) {
        url = "command/upload";
        key = "urls";

        boundary = "-----------------------" + (new Date()).getTime();

        urlContentType = "multipart/form-data; boundary=" + boundary;

    }

    if ("pauseall".equals(command)) {
        url = "command/pauseall";
    }

    if ("pauseAll".equals(command)) {
        url = "command/pauseAll";
    }

    if ("resumeall".equals(command)) {
        url = "command/resumeall";
    }

    if ("resumeAll".equals(command)) {
        url = "command/resumeAll";
    }

    if ("increasePrio".equals(command)) {
        url = "command/increasePrio";
        key = "hashes";
    }

    if ("decreasePrio".equals(command)) {
        url = "command/decreasePrio";
        key = "hashes";

    }

    if ("maxPrio".equals(command)) {
        url = "command/topPrio";
        key = "hashes";
    }

    if ("minPrio".equals(command)) {
        url = "command/bottomPrio";
        key = "hashes";

    }

    if ("setFilePrio".equals(command)) {
        url = "command/setFilePrio";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];
        fileId = tmpString[1];
        filePriority = tmpString[2];

        //            Log.d("Debug", "hash: " + hash);
        //            Log.d("Debug", "fileId: " + fileId);
        //            Log.d("Debug", "filePriority: " + filePriority);
    }

    if ("setQBittorrentPrefefrences".equals(command)) {
        url = "command/setPreferences";
        key = "json";
    }

    if ("setUploadRateLimit".equals(command)) {

        url = "command/setTorrentsUpLimit";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }
    }

    if ("setDownloadRateLimit".equals(command)) {
        url = "command/setTorrentsDlLimit";
        key = "hashes";

        Log.d("Debug", "Hash before: " + hash);

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            limit = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            limit = "-1";
        }

        //            Log.d("Debug", "url: " + url);
        //            Log.d("Debug", "Hashes: " + hash + " | limit: " + limit);

    }

    if ("recheckSelected".equals(command)) {
        url = "command/recheck";
    }

    if ("toggleFirstLastPiecePrio".equals(command)) {
        url = "command/toggleFirstLastPiecePrio";
        key = "hashes";

    }

    if ("toggleSequentialDownload".equals(command)) {
        url = "command/toggleSequentialDownload";
        key = "hashes";

    }

    if ("toggleAlternativeSpeedLimits".equals(command)) {

        //            Log.d("Debug", "Toggling alternative rates");

        url = "command/toggleAlternativeSpeedLimits";
        key = "hashes";

    }

    if ("setLabel".equals(command)) {
        url = "command/setLabel";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("setCategory".equals(command)) {
        url = "command/setCategory";
        key = "hashes";

        String[] tmpString = hash.split("&");
        hash = tmpString[0];

        try {
            label = tmpString[1];
        } catch (ArrayIndexOutOfBoundsException e) {
            label = "";
        }

        //            Log.d("Debug", "Hash2: " + hash + "| label2: " + label);

    }

    if ("alternativeSpeedLimitsEnabled".equals(command)) {

        //            Log.d("Debug", "Getting alternativeSpeedLimitsEnabled");

        url = "command/alternativeSpeedLimitsEnabled";

        key = "hashes";
    }

    // if server is publish in a subfolder, fix url
    if (subfolder != null && !subfolder.equals("")) {
        url = subfolder + "/" + url;
    }

    HttpParams httpParameters = new BasicHttpParams();

    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = connection_timeout * 1000;

    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = data_timeout * 1000;

    // Set http parameters
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android");
    HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8);

    // Making HTTP request
    HttpHost targetHost = new HttpHost(this.hostname, this.port, this.protocol);

    // httpclient = new DefaultHttpClient();
    httpclient = getNewHttpClient();

    httpclient.setParams(httpParameters);

    try {

        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password);

        httpclient.getCredentialsProvider().setCredentials(authScope, credentials);

        url = protocol + "://" + hostname + ":" + port + "/" + url;

        HttpPost httpget = new HttpPost(url);

        if ("addTorrent".equals(command)) {

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();
        }

        if ("addTracker".equals(command)) {

            String[] tmpString = hash.split("&");
            hash = tmpString[0];

            URI hash_uri = new URI(hash);
            hash = hash_uri.toString();

            try {
                tracker = tmpString[1];
            } catch (ArrayIndexOutOfBoundsException e) {
                tracker = "";
            }

            //                Log.d("Debug", "addTracker - hash: " + hash);
            //                Log.d("Debug", "addTracker - tracker: " + tracker);

        }

        // In order to pass the hash we must set the pair name value
        BasicNameValuePair bnvp = new BasicNameValuePair(key, hash);

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(bnvp);

        // Add limit
        if (!limit.equals("")) {
            Log.d("Debug", "JSONParser - Limit: " + limit);
            nvps.add(new BasicNameValuePair("limit", limit));
        }

        // Set values for setting file priority
        if ("setFilePrio".equals(command)) {

            nvps.add(new BasicNameValuePair("id", fileId));
            nvps.add(new BasicNameValuePair("priority", filePriority));
        }

        // Add label
        if (label != null && !label.equals("")) {

            label = Uri.decode(label);

            if ("setLabel".equals(command)) {

                nvps.add(new BasicNameValuePair("label", label));
            } else {

                nvps.add(new BasicNameValuePair("category", label));
            }

            //                Log.d("Debug", "Hash3: " + hash + "| label3: >" + label + "<");
        }

        // Add tracker
        if (tracker != null && !tracker.equals("")) {

            nvps.add(new BasicNameValuePair("urls", tracker));

            //                Log.d("Debug", ">Tracker: " + key + " | " + hash + " | " + tracker + "<");

        }

        String entityValue = URLEncodedUtils.format(nvps, HTTP.UTF_8);

        // This replaces encoded char "+" for "%20" so spaces can be passed as parameter
        entityValue = entityValue.replaceAll("\\+", "%20");

        StringEntity stringEntity = new StringEntity(entityValue, HTTP.UTF_8);
        stringEntity.setContentType(URLEncodedUtils.CONTENT_TYPE);

        httpget.setEntity(stringEntity);

        // Set content type and urls
        if ("addTorrent".equals(command) || "increasePrio".equals(command) || "decreasePrio".equals(command)
                || "maxPrio".equals(command) || "setFilePrio".equals(command)
                || "toggleAlternativeSpeedLimits".equals(command)
                || "alternativeSpeedLimitsEnabled".equals(command) || "setLabel".equals(command)
                || "setCategory".equals(command) || "addTracker".equals(command)) {
            httpget.setHeader("Content-Type", urlContentType);
        }

        // Set cookie
        if (this.cookie != null) {
            httpget.setHeader("Cookie", this.cookie);
        }

        // Set content type and urls
        if ("addTorrentFile".equals(command)) {

            httpget.setHeader("Content-Type", urlContentType);

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

            // Add boundary
            builder.setBoundary(boundary);

            // Add torrent file as binary
            File file = new File(hash);
            // FileBody fileBody = new FileBody(file);
            // builder.addPart("file", fileBody);

            builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, hash);

            // Build entity
            HttpEntity entity = builder.build();

            // Set entity to http post
            httpget.setEntity(entity);

        }

        httpResponse = httpclient.execute(targetHost, httpget);

        StatusLine statusLine = httpResponse.getStatusLine();

        int mStatusCode = statusLine.getStatusCode();

        //            Log.d("Debug", "JSONPArser - mStatusCode: " + mStatusCode);

        if (mStatusCode != 200) {
            httpclient.getConnectionManager().shutdown();
            throw new JSONParserStatusCodeException(mStatusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        result = EntityUtils.toString(httpEntity);

        //            Log.d("Debug", "JSONPArser - command result: " + result);

        return result;

    } catch (UnsupportedEncodingException e) {

    } catch (ClientProtocolException e) {
        Log.e("Debug", "Client: " + e.toString());
        e.printStackTrace();
    } catch (SSLPeerUnverifiedException e) {
        Log.e("JSON", "SSLPeerUnverifiedException: " + e.toString());
        throw new JSONParserStatusCodeException(NO_PEER_CERTIFICATE);
    } catch (IOException e) {
        Log.e("Debug", "IO: " + e.toString());
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(TIMEOUT_ERROR);
    } catch (JSONParserStatusCodeException e) {
        httpclient.getConnectionManager().shutdown();
        throw new JSONParserStatusCodeException(e.getCode());
    } catch (Exception e) {
        Log.e("Debug", "Generic: " + e.toString());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }

    return null;

}

From source file:org.opentravel.schemacompiler.repository.impl.RemoteRepositoryClient.java

/**
 * @see org.opentravel.schemacompiler.repository.Repository#unlock(org.opentravel.schemacompiler.repository.RepositoryItem,
 *      boolean)/* w  w w  .  ja  va  2  s.co m*/
 */
@SuppressWarnings("unchecked")
@Override
public void unlock(RepositoryItem item, boolean commitWIP) throws RepositoryException {
    InputStream wipContent = null;
    boolean success = false;
    try {
        validateRepositoryItem(item);
        manager.getFileManager().startChangeSet();

        // Build the HTTP request for the remote service
        RepositoryItemIdentityType itemIdentity = createItemIdentity(item);
        Marshaller marshaller = RepositoryFileManager.getSharedJaxbContext().createMarshaller();
        HttpPost request = newPostRequest(UNLOCK_ENDPOINT);

        MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
        StringWriter xmlWriter = new StringWriter();

        if (commitWIP) {
            File wipFile = manager.getFileManager().getLibraryWIPContentLocation(item.getBaseNamespace(),
                    item.getFilename());

            if (!wipFile.exists()) {
                throw new RepositoryException("The work-in-process file does not exist: " + item.getFilename());
            }
            wipContent = new FileInputStream(wipFile);
            mpEntity.addBinaryBody("fileContent", toByteArray(wipContent), ContentType.DEFAULT_BINARY,
                    item.getFilename());
            // mpEntity.addPart( "fileContent", new InputStreamBody(wipContent,
            // item.getFilename()) );
        }
        marshaller.marshal(objectFactory.createRepositoryItemIdentity(itemIdentity), xmlWriter);
        mpEntity.addTextBody("item", xmlWriter.toString(), ContentType.TEXT_XML);
        request.setEntity(mpEntity.build());

        // Send the web service request and unmarshall the updated meta-data from the response
        log.info("Sending lock request to HTTP endpoint: " + endpointUrl);
        HttpResponse response = executeWithAuthentication(request);

        if (response.getStatusLine().getStatusCode() != HTTP_RESPONSE_STATUS_OK) {
            throw new RepositoryException(getResponseErrorMessage(response));
        }
        log.info("Lock response received - Status OK");

        Unmarshaller unmarshaller = RepositoryFileManager.getSharedJaxbContext().createUnmarshaller();
        JAXBElement<LibraryInfoType> jaxbElement = (JAXBElement<LibraryInfoType>) unmarshaller
                .unmarshal(response.getEntity().getContent());

        // Update the local cache with the content we just received from the remote web service
        manager.getFileManager().saveLibraryMetadata(jaxbElement.getValue());

        // Update the local repository item with the latest state information
        ((RepositoryItemImpl) item).setState(RepositoryItemState.MANAGED_UNLOCKED);
        ((RepositoryItemImpl) item).setLockedByUser(null);

        // Force a re-download of the updated content to make sure the local copy is
        // synchronized
        // with the remote repository.
        downloadContent(item, true);

        success = true;

    } catch (JAXBException e) {
        throw new RepositoryException("The format of the library meta-data is unreadable.", e);

    } catch (IOException e) {
        throw new RepositoryException("The remote repository is unavailable.", e);

    } finally {
        // Close the WIP content input stream
        try {
            if (wipContent != null)
                wipContent.close();
        } catch (Throwable t) {
        }

        // Commit or roll back the changes based on the result of the operation
        if (success) {
            manager.getFileManager().commitChangeSet();
        } else {
            try {
                manager.getFileManager().rollbackChangeSet();
            } catch (Throwable t) {
                log.error("Error rolling back the current change set.", t);
            }
        }
    }
}

From source file:com.adobe.aem.demomachine.communities.Loader.java

private static void addBinaryBody(MultipartEntityBuilder builder, LinkedList<InputStream> lIs,
        ResourceResolver rr, String field, String csvfile, String value) {
    if (rr == null) {
        File attachment = new File(csvfile.substring(0, csvfile.indexOf(".csv")) + File.separator + value);
        // Check for file existence
        if (attachment.exists()) {
            logger.debug("Adding file named " + value + " to POST");
            builder.addBinaryBody(field, attachment, getContentType(value), attachment.getName());
        } else {// www  .  j a v  a2  s.  c o  m
            attachment = new File(csvfile.substring(0, csvfile.lastIndexOf("/")) + File.separator
                    + "attachments" + File.separator + value);
            if (attachment.exists()) {
                builder.addBinaryBody(field, attachment, getContentType(value), attachment.getName());
            } else {
                logger.error("A non existent resource named " + value + " was referenced");
            }
        }
    } else {
        Resource res = rr.getResource(csvfile + "/attachments/" + value + "/jcr:content");
        if (res != null) {
            logger.debug("Adding resource named " + value + " to POST");
            InputStream is = res.adaptTo(InputStream.class);
            lIs.add(is);
            builder.addBinaryBody(field, is, getContentType(value), value);
        } else {
            logger.error("A non existent resource named " + value + " was referenced");
        }
    }
}