Search in sources :

Example 61 with StringEntity

use of org.apache.http.entity.StringEntity in project voltdb by VoltDB.

the class TestJSONOverHttps method callProcOverJSON.

private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
    URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder b = HttpClientBuilder.create();
    b.setSslcontext(sslContext);
    b.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = b.build()) {
        HttpPost post = new HttpPost(uri);
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        post.setProtocolVersion(HttpVersion.HTTP_1_1);
        post.setConfig(rc);
        post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || status == 400) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(post, rh);
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) RequestConfig(org.apache.http.client.config.RequestConfig) TrustStrategy(org.apache.http.conn.ssl.TrustStrategy) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StringEntity(org.apache.http.entity.StringEntity) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder)

Example 62 with StringEntity

use of org.apache.http.entity.StringEntity in project intellij-plugins by StepicOrg.

the class HttpTransportClient method post.

@NotNull
@Override
public ClientResponse post(@NotNull StepikApiClient stepikApiClient, @NotNull String url, @Nullable String body, @Nullable Map<String, String> headers) {
    HttpPost request = new HttpPost(url);
    if (headers == null) {
        headers = new HashMap<>();
    }
    headers.forEach(request::setHeader);
    if (body != null) {
        ContentType contentType;
        contentType = ContentType.create(headers.getOrDefault(CONTENT_TYPE_HEADER, CONTENT_TYPE), Consts.UTF_8);
        request.setEntity(new StringEntity(body, contentType));
    }
    return call(stepikApiClient, request);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) ContentType(org.apache.http.entity.ContentType) NotNull(org.jetbrains.annotations.NotNull)

Example 63 with StringEntity

use of org.apache.http.entity.StringEntity in project intellij-community by JetBrains.

the class CCStepicConnector method postTask.

public static void postTask(final Project project, @NotNull final Task task, final int lessonId) {
    final HttpPost request = new HttpPost(EduStepicNames.STEPIC_API_URL + "/step-sources");
    final Gson gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().registerTypeAdapter(AnswerPlaceholder.class, new StudySerializationUtils.Json.StepicAnswerPlaceholderAdapter()).create();
    ApplicationManager.getApplication().invokeLater(() -> {
        final String requestBody = gson.toJson(new StepicWrappers.StepSourceWrapper(project, task, lessonId));
        request.setEntity(new StringEntity(requestBody, ContentType.APPLICATION_JSON));
        try {
            final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
            if (client == null)
                return;
            final CloseableHttpResponse response = client.execute(request);
            final StatusLine line = response.getStatusLine();
            final HttpEntity responseEntity = response.getEntity();
            final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
            EntityUtils.consume(responseEntity);
            if (line.getStatusCode() != HttpStatus.SC_CREATED) {
                LOG.error("Failed to push " + responseString);
                return;
            }
            final JsonObject postedTask = new Gson().fromJson(responseString, JsonObject.class);
            final JsonObject stepSource = postedTask.getAsJsonArray("step-sources").get(0).getAsJsonObject();
            task.setStepId(stepSource.getAsJsonPrimitive("id").getAsInt());
        } catch (IOException e) {
            LOG.error(e.getMessage());
        }
    });
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpEntity(org.apache.http.HttpEntity) GsonBuilder(com.google.gson.GsonBuilder) StudySerializationUtils(com.jetbrains.edu.learning.StudySerializationUtils) Gson(com.google.gson.Gson) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) StatusLine(org.apache.http.StatusLine) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse)

Example 64 with StringEntity

use of org.apache.http.entity.StringEntity in project Activiti by Activiti.

the class TaskResourceTest method testResolveTask.

/**
   * Test resolving a single task and all exceptional cases related to resolution.
   * POST runtime/tasks/{taskId}
   */
public void testResolveTask() throws Exception {
    try {
        Task task = taskService.newTask();
        task.setAssignee("initialAssignee");
        taskService.saveTask(task);
        taskService.delegateTask(task.getId(), "anotherUser");
        String taskId = task.getId();
        // Resolve the task and check result
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("action", "resolve");
        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK, taskId));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));
        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertNotNull(task);
        assertEquals("initialAssignee", task.getAssignee());
        assertEquals("initialAssignee", task.getOwner());
        assertEquals(DelegationState.RESOLVED, task.getDelegationState());
        // Resolving again shouldn't cause an exception
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));
        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertNotNull(task);
        assertEquals("initialAssignee", task.getAssignee());
        assertEquals("initialAssignee", task.getOwner());
        assertEquals(DelegationState.RESOLVED, task.getDelegationState());
    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) Task(org.activiti.engine.task.Task) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode)

Example 65 with StringEntity

use of org.apache.http.entity.StringEntity in project Activiti by Activiti.

the class TaskResourceTest method testClaimTask.

/**
   * Test claiming a single task and all exceptional cases related to claiming.
   * POST runtime/tasks/{taskId}
   */
public void testClaimTask() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);
        taskService.addCandidateUser(task.getId(), "newAssignee");
        assertEquals(1L, taskService.createTaskQuery().taskCandidateUser("newAssignee").count());
        // Add candidate group
        String taskId = task.getId();
        task.setAssignee("fred");
        // Claiming without assignee should set asisgnee to null
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("action", "claim");
        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK, taskId));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));
        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertNotNull(task);
        assertNull(task.getAssignee());
        assertEquals(1L, taskService.createTaskQuery().taskCandidateUser("newAssignee").count());
        // Claim the task and check result
        requestNode.put("assignee", "newAssignee");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));
        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertNotNull(task);
        assertEquals("newAssignee", task.getAssignee());
        assertEquals(0L, taskService.createTaskQuery().taskCandidateUser("newAssignee").count());
        // Claiming with the same user shouldn't cause an exception
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_OK));
        task = taskService.createTaskQuery().taskId(taskId).singleResult();
        assertNotNull(task);
        assertEquals("newAssignee", task.getAssignee());
        assertEquals(0L, taskService.createTaskQuery().taskCandidateUser("newAssignee").count());
        // Claiming with another user should cause exception
        requestNode.put("assignee", "anotherUser");
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        closeResponse(executeRequest(httpPost, HttpStatus.SC_CONFLICT));
    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
        // Clean historic tasks with no runtime-counterpart
        List<HistoricTaskInstance> historicTasks = historyService.createHistoricTaskInstanceQuery().list();
        for (HistoricTaskInstance task : historicTasks) {
            historyService.deleteHistoricTaskInstance(task.getId());
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) Task(org.activiti.engine.task.Task) HistoricTaskInstance(org.activiti.engine.history.HistoricTaskInstance) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode)

Aggregations

StringEntity (org.apache.http.entity.StringEntity)456 HttpPost (org.apache.http.client.methods.HttpPost)249 HttpResponse (org.apache.http.HttpResponse)147 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)141 Test (org.junit.Test)105 HttpPut (org.apache.http.client.methods.HttpPut)94 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)88 IOException (java.io.IOException)84 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)68 HttpEntity (org.apache.http.HttpEntity)60 JsonNode (com.fasterxml.jackson.databind.JsonNode)54 Deployment (org.activiti.engine.test.Deployment)50 TestHttpClient (io.undertow.testutils.TestHttpClient)30 ProcessInstance (org.activiti.engine.runtime.ProcessInstance)27 StatusLine (org.apache.http.StatusLine)27 HttpGet (org.apache.http.client.methods.HttpGet)27 Gson (com.google.gson.Gson)24 UnsupportedEncodingException (java.io.UnsupportedEncodingException)24 ProtocolVersion (org.apache.http.ProtocolVersion)24 BasicHttpResponse (org.apache.http.message.BasicHttpResponse)23