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

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

Introduction

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

Prototype

public ByteArrayBody(final byte[] data, final String mimeType, final String filename) 

Source Link

Document

Creates a new ByteArrayBody.

Usage

From source file:com.serphacker.serposcope.scraper.captcha.solver.AntiCaptchaSolver.java

@Override
public boolean solve(Captcha cap) {
    if (!(cap instanceof CaptchaImage)) {
        return false;
    }//from w  w  w.  j  ava2 s .c o m

    captchaCount.incrementAndGet();

    CaptchaImage captcha = (CaptchaImage) cap;
    captcha.setLastSolver(this);
    captcha.setStatus(Captcha.Status.CREATED);

    String filename = null;
    String textMimeType = captcha.getMimes()[0];
    String[] mimes = null;

    if (textMimeType != null)
        mimes = textMimeType.split("/");
    else
        textMimeType = "application/octet-stream";
    if (mimes != null && mimes.length == 2) {
        if (isValidImageExtension(mimes[1])) {
            filename = "image." + mimes[1];
        }
    } else {
        filename = "image.png";
    }

    Map<String, Object> data = new HashMap<>();
    data.put("method", "post");
    data.put("key", apiKey);
    data.put("file", new ByteArrayBody(captcha.getImage(), ContentType.create(textMimeType), filename));

    long started = System.currentTimeMillis();
    captcha.setStatus(Captcha.Status.SUBMITTED);
    try (ScrapClient http = new ScrapClient()) {
        String response;
        int retry = 0;
        while (true) {
            http.post(apiUrl + "in.php", data, ScrapClient.PostType.MULTIPART);
            response = http.getContentAsString();
            if (!isRetryable(response)) {
                break;
            }

            if (++retry > maxRetryOnOverload) {
                break;
            }

            try {
                Long sleep = 5000l * retry;
                LOG.debug("server is overloaded \"{}\", sleeping {} ms", response, sleep);
                Thread.sleep(sleep);
            } catch (InterruptedException ex) {
                break;
            }
        }

        if (response == null) {
            captcha.setError(Captcha.Error.NETWORK_ERROR);
            return false;
        }

        if (!response.startsWith("OK|") || response.length() < 4) {
            switch (response) {
            case "ERROR_WRONG_USER_KEY":
            case "ERROR_KEY_DOES_NOT_EXIST":
                captcha.setError(Captcha.Error.INVALID_CREDENTIALS);
                return false;

            case "ERROR_ZERO_BALANCE":
                captcha.setError(Captcha.Error.OUT_OF_CREDITS);
                return false;

            case "ERROR_NO_SLOT_AVAILABLE":
                captcha.setError(Captcha.Error.SERVICE_OVERLOADED);
                return false;

            default:
                captcha.setError(Captcha.Error.NETWORK_ERROR);
                return false;
            }
        }

        captcha.setId(response.substring(3));

        long timeLimit = System.currentTimeMillis() + timeoutMS;
        while (System.currentTimeMillis() < timeLimit) {

            int status = http.get(apiUrl + "res.php?key=" + apiKey + "&action=get" + "&id=" + captcha.getId()
                    + "&random=" + random.nextInt(Integer.MAX_VALUE));

            String res = http.getContentAsString();
            if (res == null) {
                captcha.setError(Captcha.Error.NETWORK_ERROR);
                return false;
            }

            if (!"CAPCHA_NOT_READY".equals(apiKey)) {
                if (res.startsWith("OK|")) {
                    captcha.setResponse(res.substring(3));
                    captcha.setStatus(Captcha.Status.SOLVED);
                    return true;
                }

                captcha.setError(Captcha.Error.NETWORK_ERROR);
                captcha.setStatus(Captcha.Status.ERROR);
            }

            try {
                Thread.sleep(POLLING_PAUSE_MS);
            } catch (InterruptedException ex) {
                break;
            }
        }

        captcha.setError(Captcha.Error.TIMEOUT);
        captcha.setStatus(Captcha.Status.ERROR);

    } catch (IOException ex) {
        LOG.error("io exception", ex);
        captcha.setError(EXCEPTION);
    } finally {
        captcha.setSolveDuration(System.currentTimeMillis() - started);
    }

    return false;
}

From source file:com.serphacker.serposcope.scraper.captcha.solver.DeathByCaptchaSolver.java

@Override
public boolean solve(Captcha cap) {
    if (!(cap instanceof CaptchaImage)) {
        return false;
    }// w  w w .  ja  va  2 s  .c o m

    captchaCount.incrementAndGet();

    CaptchaImage captcha = (CaptchaImage) cap;
    captcha.setLastSolver(this);
    captcha.setStatus(Captcha.Status.CREATED);

    String filename = null;
    String textMimeType = captcha.getMimes()[0];
    String[] mimes = null;

    if (textMimeType != null)
        mimes = textMimeType.split("/");
    else
        textMimeType = "application/octet-stream";
    if (mimes != null && mimes.length == 2) {
        if (isValidImageExtension(mimes[1])) {
            filename = "image." + mimes[1];
        }
    } else {
        filename = "image.png";
    }

    Map<String, Object> data = getMapWithCredentials();
    data.put("captchafile", new ByteArrayBody(captcha.getImage(), ContentType.create(textMimeType), filename));

    long started = System.currentTimeMillis();
    captcha.setStatus(Captcha.Status.SUBMITTED);
    try (ScrapClient http = new ScrapClient()) {
        int httpStatus = 0;
        int retry = 0;
        while (true) {
            httpStatus = http.post(apiUrl + "captcha", data, ScrapClient.PostType.MULTIPART);
            if (!isRetryableStatus(httpStatus)) {
                break;
            }

            if (++retry > maxRetryOnOverload) {
                break;
            }

            try {
                Long sleep = 5000l * retry;
                LOG.debug("server is overloaded, sleeping {} ms", sleep);
                Thread.sleep(sleep);
            } catch (InterruptedException ex) {
                break;
            }
        }

        if (httpStatus >= 500) {
            captcha.setError(Captcha.Error.SERVICE_OVERLOADED);
            return false;
        } else if (httpStatus == 403) {
            captcha.setError(Captcha.Error.INVALID_CREDENTIALS);
            return false;
        } else if (httpStatus == 400) {
            captcha.setError(Captcha.Error.INVALID_CREDENTIALS);
            return false;
        } else if (httpStatus != 303) {
            captcha.setError(Captcha.Error.NETWORK_ERROR);
            return false;
        }

        String location = http.getResponseHeader("location");
        if (location == null || !location.startsWith(apiUrl)) {
            LOG.warn("invalid location : {}", location);
            captcha.setError(Captcha.Error.NETWORK_ERROR);
            return false;
        }

        String captchaId = extractId(location);
        if (captchaId == null) {
            captcha.setError(Captcha.Error.NETWORK_ERROR);
            return false;
        }
        captcha.setId(captchaId);

        long timeLimit = System.currentTimeMillis() + timeoutMS;
        while (System.currentTimeMillis() < timeLimit) {

            int status = http.get(location + "?" + random.nextInt(Integer.MAX_VALUE));
            if (status == 200) {
                Map<String, String> answer = parseAnswer(http.getContentAsString());
                if (answer.get("text") != null && !answer.get("text").isEmpty()) {
                    captcha.setResponse(answer.get("text"));
                    captcha.setStatus(Captcha.Status.SOLVED);
                    return true;
                }
            }

            try {
                Thread.sleep(POLLING_PAUSE_MS);
            } catch (InterruptedException ex) {
                break;
            }
        }

        captcha.setError(Captcha.Error.TIMEOUT);
        captcha.setStatus(Captcha.Status.ERROR);

    } catch (IOException ex) {
        LOG.error("io exception", ex);
        captcha.setError(EXCEPTION);
    } finally {
        captcha.setSolveDuration(System.currentTimeMillis() - started);
    }

    return false;
}

From source file:com.app.precared.utils.MultipartEntityBuilder.java

public MultipartEntityBuilder addBinaryBody(final String name, final byte[] b, final ContentType contentType,
        final String filename) {
    return addPart(name, new ByteArrayBody(b, contentType, filename));
}

From source file:gov.nasa.arc.geocam.talk.service.SiteAuthCookie.java

@Override
public ServerResponse post(String relativePath, Map<String, String> params, byte[] audioBytes)
        throws AuthenticationFailedException, IOException, ClientProtocolException, InvalidParameterException {
    if (params == null) {
        throw new InvalidParameterException("Post parameters are required");
    }// w  ww  .j a  v  a  2  s.c o m

    ensureAuthenticated();

    httpClient = new DefaultHttpClient();

    HttpParams httpParams = httpClient.getParams();
    HttpClientParams.setRedirecting(httpParams, false);

    HttpPost post = new HttpPost(this.serverRootUrl + "/" + appPath + "/" + relativePath);
    post.setParams(httpParams);

    HttpEntity httpEntity;

    if (audioBytes != null) {
        httpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String key : params.keySet()) {
            ((MultipartEntity) httpEntity).addPart(key, new StringBody(params.get(key)));
        }
        if (audioBytes != null) {
            ((MultipartEntity) httpEntity).addPart("audio",
                    new ByteArrayBody(audioBytes, "audio/mpeg", "audio.mp4"));
        }
    } else {
        List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();

        for (String key : params.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
        }

        httpEntity = new UrlEncodedFormEntity(nameValuePairs, HTTP.ASCII);
    }

    post.setEntity(httpEntity);
    httpClient.getCookieStore().addCookie(sessionIdCookie);
    ServerResponse sr = new ServerResponse(httpClient.execute(post));

    if (sr.getResponseCode() == 401 || sr.getResponseCode() == 403) {
        throw new AuthenticationFailedException("Server responded with code: " + sr.getResponseCode());
    }

    return sr;
}

From source file:functionaltests.RestSchedulerJobTaskTest.java

@Test
public void testLoginWithCredentials() throws Exception {
    RestFuncTestConfig config = RestFuncTestConfig.getInstance();
    Credentials credentials = RestFuncTUtils.createCredentials(config.getLogin(), config.getPassword(),
            RestFuncTHelper.getSchedulerPublicKey());
    String schedulerUrl = getResourceUrl("login");
    HttpPost httpPost = new HttpPost(schedulerUrl);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create().addPart("credential",
            new ByteArrayBody(credentials.getBase64(), ContentType.APPLICATION_OCTET_STREAM, null));
    httpPost.setEntity(multipartEntityBuilder.build());
    HttpResponse response = executeUriRequest(httpPost);
    assertHttpStatusOK(response);/*from   w  ww .  j  av  a 2s.  c  o m*/
    String sessionId = assertContentNotEmpty(response);

    String currentUserUrl = getResourceUrl("logins/sessionid/" + sessionId);

    HttpGet httpGet = new HttpGet(currentUserUrl);
    response = executeUriRequest(httpGet);
    assertHttpStatusOK(response);
    String userName = assertContentNotEmpty(response);
    Assert.assertEquals(config.getLogin(), userName);
}

From source file:nl.nn.adapterframework.http.mime.MultipartEntityBuilder.java

public MultipartEntityBuilder addBinaryBody(String name, byte[] b, ContentType contentType, String filename) {
    return addPart(name, new ByteArrayBody(b, contentType, filename));
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public MultipartBody field(String name, byte[] bytes, ContentType contentType, String fileName) {
    return field(name, new ByteArrayBody(bytes, contentType, fileName), true, contentType.getMimeType());
}

From source file:net.ychron.unirestinst.request.body.MultipartBody.java

public MultipartBody field(String name, byte[] bytes, String fileName) {
    return field(name, new ByteArrayBody(bytes, ContentType.APPLICATION_OCTET_STREAM, fileName), true,
            ContentType.APPLICATION_OCTET_STREAM.getMimeType());
}

From source file:org.guvnor.ala.wildfly.access.WildflyClient.java

public int deploy(File file) throws WildflyClientException {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, managementPort),
            new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + managementPort + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {/*from  w  ww  . j  ava 2 s  .co m*/
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(WildflyClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new WildflyClientException("Error Deploying App Status Code: " + statusCode);
        }
        return statusCode;
    } catch (IOException ex) {
        LOG.error("Error Deploying App : " + ex.getMessage(), ex);
        throw new WildflyClientException("Error Deploying App : " + ex.getMessage(), ex);
    }
}

From source file:eu.trentorise.opendata.jackan.test.ckan.ExperimentalCkanClient.java

/**
 * Uploads a file using file storage api, which I think is deprecated. As of
 * Aug 2015, coesn't work neither with demo.ckan.org nor dati.trentino
 *
 * Adapted from/*from w w w. j  a va  2  s  .com*/
 * https://github.com/Ontodia/openrefine-ckan-storage-extension/blob/c99de78fd605c4754197668c9396cffd1f9a0267/src/org/deri/orefine/ckan/StorageApiProxy.java#L34
 */
public String uploadFile(String fileContent, String fileLabel) {
    HttpResponse formFields = null;
    try {
        String filekey = null;
        HttpClient client = new DefaultHttpClient();

        //   get the form fields required from ckan storage
        // notice if you put '3/' it gives not found :-/
        String formUrl = getCatalogUrl() + "/api/storage/auth/form/file/" + fileLabel;
        HttpGet getFormFields = new HttpGet(formUrl);
        getFormFields.setHeader("Authorization", getCkanToken());
        formFields = client.execute(getFormFields);
        HttpEntity entity = formFields.getEntity();
        if (entity != null) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            entity.writeTo(os);

            //now parse JSON
            //JSONObject obj = new JSONObject(os.toString());
            JsonNode obj = new ObjectMapper().readTree(os.toString());

            //post the file now
            String uploadFileUrl = getCatalogUrl() + obj.get("action").asText();
            HttpPost postFile = new HttpPost(uploadFileUrl);
            postFile.setHeader("Authorization", getCkanToken());
            MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.STRICT);

            //JSONArray fields = obj.getJSONArray("fields");
            Iterator<JsonNode> fields = obj.get("fields").elements();
            while (fields.hasNext()) {
                JsonNode fieldObj = fields.next();
                //JSONObject fieldObj = fields.getJSONObject(i);
                String fieldName = fieldObj.get("name").asText();
                String fieldValue = fieldObj.get("value").asText();
                if (fieldName.equals("key")) {
                    filekey = fieldValue;
                }
                mpEntity.addPart(fieldName,
                        new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));
            }

            /*
             for (int i = 0; i < fields.length(); i++) {
             //JSONObject fieldObj = fields.getJSONObject(i);
             JSONObject fieldObj = fields.getJSONObject(i);
             String fieldName = fieldObj.getString("name");
             String fieldValue = fieldObj.getString("value");
             if (fieldName.equals("key")) {
             filekey = fieldValue;
             }
             mpEntity.addPart(fieldName, new StringBody(fieldValue, "multipart/form-data", Charset.forName("UTF-8")));                    
             }
             */
            //   assure that we got the file key
            if (filekey == null) {
                throw new RuntimeException(
                        "failed to get the file key from CKAN storage form API. the response from " + formUrl
                                + " was: " + os.toString());
            }

            //the file should be the last part
            //hack... StringBody didn't work with large files
            mpEntity.addPart("file", new ByteArrayBody(fileContent.getBytes(Charset.forName("UTF-8")),
                    "multipart/form-data", fileLabel));

            postFile.setEntity(mpEntity);

            HttpResponse fileUploadResponse = client.execute(postFile);

            //check if the response status code was in the 200 range
            if (fileUploadResponse.getStatusLine().getStatusCode() < 200
                    || fileUploadResponse.getStatusLine().getStatusCode() >= 300) {
                throw new RuntimeException("failed to add the file to CKAN storage. response status line from "
                        + uploadFileUrl + " was: " + fileUploadResponse.getStatusLine());
            }
            return getCatalogUrl() + "/storage/f/" + filekey;

            //return CKAN_STORAGE_FILES_BASE_URI + filekey;
        }
        throw new RuntimeException("failed to get form details from CKAN storage. response line was: "
                + formFields.getStatusLine());
    } catch (IOException ioe) {
        throw new RuntimeException("failed to upload file to CKAN Storage ", ioe);
    }
}