Example usage for org.apache.http.entity ContentType create

List of usage examples for org.apache.http.entity ContentType create

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType create.

Prototype

public static ContentType create(String str, String str2) throws UnsupportedCharsetException 

Source Link

Usage

From source file:de.hska.ld.oidc.client.SSSClient.java

public SSSFileEntitiesDto getFileEntity(List<String> attachmentIds, String accessToken) throws IOException {
    String attachmentIdString = "";
    boolean firstAttachmentId = true;
    for (String attachmentId : attachmentIds) {
        String separator = ",";
        if (firstAttachmentId) {
            separator = "";
            firstAttachmentId = false;/* w w w. j  ava2  s .c o  m*/
        }
        try {
            attachmentIdString += separator + URLEncoder.encode(attachmentId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    attachmentIdString = URLEncoder.encode(attachmentIdString, "UTF-8");
    String url = null;
    if (getSssAPIVersion() == 1) {
        url = env.getProperty("sss.server.endpoint") + "/entities/entities/filtered/" + attachmentIdString;
    } else {
        url = env.getProperty("sss.server.endpoint") + "/rest/entities/filtered/" + attachmentIdString;
    }

    HttpClient client = getHttpClientFor(url);
    HttpPost post = new HttpPost(url);
    addHeaderInformation(post, accessToken);

    SSSEntitiesFilteredEntitiesRequestDto sssDiscsFilteredTargetsRequestDto = new SSSEntitiesFilteredEntitiesRequestDto();
    sssDiscsFilteredTargetsRequestDto.setSetDiscs(false);
    sssDiscsFilteredTargetsRequestDto.setSetThumb(false);
    String sssLivingdocsRequestDtoString = mapper.writeValueAsString(sssDiscsFilteredTargetsRequestDto);
    StringEntity stringEntity = new StringEntity(sssLivingdocsRequestDtoString,
            ContentType.create("application/json", "UTF-8"));
    post.setEntity(stringEntity);

    HttpResponse response = client.execute(post);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new UserNotAuthorizedException();
        }
    }

    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        SSSFileEntitiesDto fileEntitiesDto = mapper.readValue(result.toString(), SSSFileEntitiesDto.class);

        return fileEntitiesDto;
    } catch (ValidationException ve) {
        throw ve;
    } catch (Exception e) {
        return null;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ LDP.class, HappyPath.class })
@OperateOnDeployment(DEPLOYMENT)/*from  w  ww .j av  a2s .c  o m*/
public void testClientContainerSimulation(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);
    HttpGet get = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpGet.class);
    HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpPost.class);
    post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8")));
    HELPER.httpRequest(get);
    String location = HELPER.httpRequest(post).location;
    HELPER.httpRequest(get);
    String path = HELPER.relativize(location);
    HELPER.httpRequest(HELPER.newRequest(path, HttpOptions.class));
    HELPER.httpRequest(HELPER.newRequest(path, HttpGet.class));
    HELPER.httpRequest(HELPER.newRequest(path, HttpDelete.class));
    HELPER.httpRequest(HELPER.newRequest(path, HttpGet.class));
    HELPER.httpRequest(get);
    LOGGER.info("Completed {}", testName.getMethodName());
}

From source file:de.unioninvestment.eai.portal.portlet.crud.scripting.domain.container.rest.ReSTDelegateImpl.java

private ContentType createContentType() {
    String mimetype = creator.getMimeType();
    if (config.getMimetype() != null) {
        mimetype = config.getMimetype();
    }//from  w w  w  .  j a v  a 2  s. c o  m
    return ContentType.create(mimetype, config.getCharset());
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public IHttpResponse post(String url, byte[] content) throws Exception {
    return post(url, ContentType.create("application/octet-stream", DEFAULT_CHARSET), content, null);
}

From source file:de.hska.ld.recommendation.client.SSSClient.java

@Transactional(readOnly = false)
private void addTagToDocumentUser(String url, Document document, List<String> tagStringList, Tag tag,
        String accessToken) throws IOException {

    String userPrefix = env.getProperty("sss.user.name.prefix");
    String documentPrefix = env.getProperty("sss.document.name.prefix");

    RecommUpdateDto recommUpdateDto = new RecommUpdateDto();

    recommUpdateDto.setRealm(env.getProperty("sss.recomm.realm"));
    Long creatorId = null;// w w w . ja  va2 s .co m
    if (tag != null) {
        creatorId = tag.getCreator().getId();
        if (creatorId == null) {
            creatorId = Core.currentUser().getId();
        }
    } else {
        creatorId = Core.currentUser().getId();
    }
    recommUpdateDto.setForUser(userPrefix + creatorId);
    recommUpdateDto.setEntity(documentPrefix + document.getId());
    recommUpdateDto.setTags(tagStringList);

    HttpClient client = getHttpClientFor(url);
    HttpPut put = new HttpPut(url);
    addHeaderInformation(put, accessToken);

    String recommUpdateDtoString = mapper.writeValueAsString(recommUpdateDto);
    StringEntity stringEntity = new StringEntity(recommUpdateDtoString,
            ContentType.create("application/json", "UTF-8"));
    put.setEntity(stringEntity);
    BufferedReader rd = null;

    HttpResponse response = client.execute(put);
    System.out.println("Response Code : " + response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new UserNotAuthorizedException();
        }
    }

    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        if (result.toString().contains("\"error_description\":\"Invalid access token:")) {
            throw new ValidationException("access token is invalid");
        }
        mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        RecommUpdateResponseDto recommUpdateResponseDto = mapper.readValue(result.toString(),
                RecommUpdateResponseDto.class);
        if (!recommUpdateResponseDto.isWorked()) {
            throw new Exception("Updating recommendations didn't work!");
        } else {
            document = documentService.findById(document.getId());
            DocumentRecommInfo documentRecommInfo = new DocumentRecommInfo();
            documentRecommInfo.setDocument(document);
            documentRecommInfo.setInitialImportToSSSDone(true);
            entityManager.persist(documentRecommInfo);
        }
        return;
    } catch (ValidationException ve) {
        throw ve;
    } catch (Exception e) {
        return;
    } finally {
        if (rd != null) {
            rd.close();
        }
    }
}

From source file:org.cloudcoder.app.server.rpc.GetCoursesAndProblemsServiceImpl.java

@Override
public OperationResult submitExercise(ProblemAndTestCaseList exercise, String repoUsername, String repoPassword)
        throws CloudCoderAuthenticationException {
    logger.warn("Sharing exercise: " + exercise.getProblem().getTestname());

    // Only a course instructor may share an exercise.
    User authenticatedUser = ServletUtil.checkClientIsAuthenticated(getThreadLocalRequest(),
            GetCoursesAndProblemsServiceImpl.class);
    Course course = new Course();
    course.setId(exercise.getProblem().getCourseId());
    Database.getInstance().reloadModelObject(course);
    CourseRegistrationList regList = Database.getInstance().findCourseRegistrations(authenticatedUser, course);
    if (!regList.isInstructor()) {
        return new OperationResult(false, "You must be an instructor to share an exercise");
    }/*from w w  w .j a va2 s .  c  o m*/

    // Get the exercise repository URL
    ConfigurationSetting repoUrlSetting = Database.getInstance()
            .getConfigurationSetting(ConfigurationSettingName.PUB_REPOSITORY_URL);
    if (repoUrlSetting == null) {
        return new OperationResult(false, "URL of exercise repository is not configured");
    }
    String repoUrl = repoUrlSetting.getValue();
    if (repoUrl.endsWith("/")) {
        repoUrl = repoUrl.substring(0, repoUrl.length() - 1);
    }

    HttpPost post = new HttpPost(repoUrl + "/exercisedata");

    // Encode an Authorization header using the provided repository username and password.
    String authHeaderValue = "Basic " + DatatypeConverter
            .printBase64Binary((repoUsername + ":" + repoPassword).getBytes(Charset.forName("UTF-8")));
    //System.out.println("Authorization: " + authHeaderValue);
    post.addHeader("Authorization", authHeaderValue);

    // Convert the exercise to a JSON string
    StringEntity entity;
    StringWriter sw = new StringWriter();
    try {
        JSONConversion.writeProblemAndTestCaseData(exercise, sw);
        entity = new StringEntity(sw.toString(), ContentType.create("application/json", "UTF-8"));
    } catch (IOException e) {
        return new OperationResult(false, "Could not convert exercise to JSON: " + e.getMessage());
    }
    post.setEntity(entity);

    // POST the exercise to the repository
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(post);

        StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            // Update the exercise's shared flag so we have a record that it was shared.
            exercise.getProblem().setShared(true);
            Database.getInstance().storeProblemAndTestCaseList(exercise, course, authenticatedUser);

            return new OperationResult(true, "Exercise successfully published to the repository - thank you!");
        } else if (statusLine.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            return new OperationResult(false,
                    "Authentication with repository failed - incorrect username/password?");
        } else {
            return new OperationResult(false,
                    "Failed to publish exercise to repository: " + statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        return new OperationResult(false, "Error sending exercise to repository: " + e.getMessage());
    } catch (IOException e) {
        return new OperationResult(false, "Error sending exercise to repository: " + e.getMessage());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.pepstock.jem.commands.util.HttpUtil.java

/**
 * Performs the login using user and password
 * //from w ww. j  a  va 2 s  .com
 * @param user user to authenticate
 * @param password password to authenticate
 * @param url http URL to call
 * @param httpclient hhtp client already created
 * @throws ClientProtocolException if any errors occurs on calling the
 *             servlet
 * @throws IOException if I/O error occurs
 */
private static void login(String user, String password, String url, HttpClient httpclient)
        throws ClientProtocolException, IOException {
    // account info in a properties
    Properties properties = new Properties();
    properties.setProperty(USER_PROPERTY_KEY, user);
    properties.setProperty(PASSWORD_PROPERTY_KEY, password);
    StringWriter writer = new StringWriter();
    properties.store(writer, "Account info");
    // login

    // concats URL with query string
    String completeUrl = url + HttpUtil.LOGIN_QUERY_STRING;
    StringEntity entity = new StringEntity(writer.toString(), ContentType.create("text/plain", "UTF-8"));

    // prepares POST request and basic response handler
    HttpPost httppost = new HttpPost(completeUrl);
    httppost.setEntity(entity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();

    // executes and no parsing
    // result must be only a string
    httpclient.execute(httppost, responseHandler);
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

@Test
@Category({ LDP.class, ExceptionPath.class })
@OperateOnDeployment(DEPLOYMENT)/*from   w  w  w  .ja va  2  s. c  o m*/
public void testUnsupportedCreationPreferences(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);
    HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpPost.class);
    post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8")));
    String interactionModel = Link.fromUri(InteractionModel.INDIRECT_CONTAINER.asURI()).rel("type").build()
            .toString();
    post.setHeader("Link", interactionModel);
    Metadata response = HELPER.httpRequest(post);
    assertThat(response.status, equalTo(HttpStatus.SC_BAD_REQUEST));
    LOGGER.info("Completed {}", testName.getMethodName());
}

From source file:com.serphacker.serposcope.scraper.http.ScrapClient.java

public int post(String url, Map<String, Object> data, PostType dataType, String charset, String referrer) {
    clearPreviousRequest();/*w w w  .j a  v  a 2s .  c o m*/

    HttpPost request = new HttpPost(url);
    HttpEntity entity = null;

    if (charset == null) {
        charset = "utf-8";
    }

    Charset detectedCharset = null;
    try {
        detectedCharset = Charset.forName(charset);
    } catch (Exception ex) {
        LOG.warn("invalid charset name {}, switching to utf-8");
        detectedCharset = Charset.forName("utf-8");
    }

    data = handleUnsupportedEncoding(data, detectedCharset);

    switch (dataType) {
    case URL_ENCODED:
        List<NameValuePair> formparams = new ArrayList<>();
        for (Map.Entry<String, Object> entry : data.entrySet()) {
            if (entry.getValue() instanceof String) {
                formparams.add(new BasicNameValuePair(entry.getKey(), (String) entry.getValue()));
            } else {
                LOG.warn("trying to url encode non string data");
                formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }

        try {
            entity = new UrlEncodedFormEntity(formparams, detectedCharset);
        } catch (Exception ex) {
            statusCode = -1;
            exception = ex;
            return statusCode;
        }
        break;

    case MULTIPART:
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(detectedCharset)
                .setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        ContentType formDataCT = ContentType.create("form-data", detectedCharset);
        //                formDataCT = ContentType.DEFAULT_TEXT;

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            String key = entry.getKey();

            if (entry.getValue() instanceof String) {
                builder = builder.addTextBody(key, (String) entry.getValue(), formDataCT);
            } else if (entry.getValue() instanceof byte[]) {
                builder = builder.addBinaryBody(key, (byte[]) entry.getValue());
            } else if (entry.getValue() instanceof ContentBody) {
                builder = builder.addPart(key, (ContentBody) entry.getValue());
            } else {
                exception = new UnsupportedOperationException(
                        "unssuported body type " + entry.getValue().getClass());
                return statusCode = -1;
            }
        }

        entity = builder.build();
        break;

    default:
        exception = new UnsupportedOperationException("unspported PostType " + dataType);
        return statusCode = -1;
    }

    request.setEntity(entity);
    if (referrer != null) {
        request.addHeader("Referer", referrer);
    }
    return request(request);
}

From source file:com.offbytwo.jenkins.client.JenkinsHttpClient.java

public String post_xml(String path, String xml_data, boolean crumbFlag) throws IOException {
    HttpPost request = new HttpPost(api(path));
    if (crumbFlag == true) {
        Crumb crumb = getQuietly("/crumbIssuer", Crumb.class);
        if (crumb != null) {
            request.addHeader(new BasicHeader(crumb.getCrumbRequestField(), crumb.getCrumb()));
        }//from w  ww .  j a  va2s  .  c  o  m
    }

    if (xml_data != null) {
        request.setEntity(new StringEntity(xml_data, ContentType.create("text/xml", "utf-8")));
    }
    HttpResponse response = client.execute(request, localContext);
    getJenkinsVersionFromHeader(response);
    httpResponseValidator.validateResponse(response);
    try {
        return IOUtils.toString(response.getEntity().getContent());
    } finally {
        EntityUtils.consume(response.getEntity());
        releaseConnection(request);
    }
}