org.apache.http.client.methods.HttpPut Java Examples

The following examples show how to use org.apache.http.client.methods.HttpPut. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpUtil.java    From api-gateway-demo-sign-java with Apache License 2.0 8 votes vote down vote up
/**
 * HTTP PUT字节数组
 * @param host
 * @param path
 * @param connectTimeout
 * @param headers
 * @param querys
 * @param bodys
 * @param signHeaderPrefixList
 * @param appKey
 * @param appSecret
 * @return
 * @throws Exception
 */
public static Response httpPut(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, byte[] bodys, List<String> signHeaderPrefixList, String appKey, String appSecret)
        throws Exception {
	headers = initialBasicHeader(HttpMethod.PUT, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret);

	HttpClient httpClient = wrapClient(host);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout));

    HttpPut put = new HttpPut(initUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
    	put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (bodys != null) {
    	put.setEntity(new ByteArrayEntity(bodys));
    }

    return convert(httpClient.execute(put));
}
 
Example #2
Source File: ApacheHttpRequestFactory.java    From aws-sdk-java-v2 with Apache License 2.0 7 votes vote down vote up
private HttpRequestBase createApacheRequest(HttpExecuteRequest request, String uri) {
    switch (request.httpRequest().method()) {
        case HEAD:
            return new HttpHead(uri);
        case GET:
            return new HttpGet(uri);
        case DELETE:
            return new HttpDelete(uri);
        case OPTIONS:
            return new HttpOptions(uri);
        case PATCH:
            return wrapEntity(request, new HttpPatch(uri));
        case POST:
            return wrapEntity(request, new HttpPost(uri));
        case PUT:
            return wrapEntity(request, new HttpPut(uri));
        default:
            throw new RuntimeException("Unknown HTTP method name: " + request.httpRequest().method());
    }
}
 
Example #3
Source File: ODataTestUtils.java    From product-ei with Apache License 2.0 7 votes vote down vote up
public static int sendPUT(String endpoint, String content, Map<String, String> headers) throws IOException {
	HttpClient httpClient = new DefaultHttpClient();
	HttpPut httpPut = new HttpPut(endpoint);
	for (String headerType : headers.keySet()) {
		httpPut.setHeader(headerType, headers.get(headerType));
	}
	if (null != content) {
		HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
		if (headers.get("Content-Type") == null) {
			httpPut.setHeader("Content-Type", "application/json");
		}
		httpPut.setEntity(httpEntity);
	}
	HttpResponse httpResponse = httpClient.execute(httpPut);
	return httpResponse.getStatusLine().getStatusCode();
}
 
Example #4
Source File: PlanItemInstanceResourceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Test action on a single plan item instance.
 */
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/runtime/oneManualActivationHumanTaskCase.cmmn" })
public void testDisablePlanItem() throws Exception {
    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase").businessKey("myBusinessKey").start();

    PlanItemInstance planItem = runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();

    String url = buildUrl(CmmnRestUrls.URL_PLAN_ITEM_INSTANCE, planItem.getId());
    HttpPut httpPut = new HttpPut(url);

    httpPut.setEntity(new StringEntity("{\"action\": \"disable\"}"));
    executeRequest(httpPut, HttpStatus.SC_NO_CONTENT);

    planItem = runtimeService.createPlanItemInstanceQuery().caseInstanceId(caseInstance.getId()).singleResult();
    assertThat(planItem).isNull();
}
 
Example #5
Source File: ExecutionCollectionResourceTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test signalling all executions
 */
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ExecutionResourceTest.process-with-signal-event.bpmn20.xml" })
public void testSignalEventExecutions() throws Exception {
  Execution signalExecution = runtimeService.startProcessInstanceByKey("processOne");
  assertNotNull(signalExecution);

  ObjectNode requestNode = objectMapper.createObjectNode();
  requestNode.put("action", "signalEventReceived");
  requestNode.put("signalName", "alert");

  Execution waitingExecution = runtimeService.createExecutionQuery().activityId("waitState").singleResult();
  assertNotNull(waitingExecution);

  // Sending signal event causes the execution to end (scope-execution for
  // the catching event)
  HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_EXECUTION_COLLECTION));
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPut, HttpStatus.SC_NO_CONTENT));

  // Check if process is moved on to the other wait-state
  waitingExecution = runtimeService.createExecutionQuery().activityId("anotherWaitState").singleResult();
  assertNotNull(waitingExecution);
}
 
Example #6
Source File: HttpAPIPinsTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testSync() throws Exception {
    HttpPut request = new HttpPut(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/update/a14");
    HttpGet getRequest = new HttpGet(httpsServerUrl + "4ae3851817194e2596cf1b7103603ef8/get/a14");

    for (int i = 0; i < 100; i++) {
        request.setEntity(new StringEntity("[\""+ i + "\"]", ContentType.APPLICATION_JSON));

        try (CloseableHttpResponse response = httpclient.execute(request)) {
            assertEquals(200, response.getStatusLine().getStatusCode());
            EntityUtils.consume(response.getEntity());
        }

        try (CloseableHttpResponse response2 = httpclient.execute(getRequest)) {
            assertEquals(200, response2.getStatusLine().getStatusCode());
            List<String> values = TestUtil.consumeJsonPinValues(response2);
            assertEquals(1, values.size());
            assertEquals(String.valueOf(i), values.get(0));
        }
    }
}
 
Example #7
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Renames the specified stack.
 *
 * @param  fromStack       source stack to rename.
 * @param  toStackId       new owner, project, and/or stack names.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public void renameStack(final String fromStack,
                        final StackId toStackId)
        throws IOException {

    final String json = toStackId.toJson();
    final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);

    final URI uri = getUri(urls.getStackUrlString(fromStack) + "/stackId");

    final String requestContext = "PUT " + uri;
    final EmptyResponseHandler responseHandler = new EmptyResponseHandler(requestContext);

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    LOG.info("renameStack: submitting {} with body {}", requestContext, json);

    httpClient.execute(httpPut, responseHandler);
}
 
Example #8
Source File: StreamingAnalyticsServiceV1.java    From streamsx.topology with Apache License 2.0 6 votes vote down vote up
/**
 * Submit the job from the built artifact.
 */
@Override
protected JsonObject submitBuildArtifact(CloseableHttpClient httpclient,
        JsonObject jobConfigOverlays, String submitUrl)
        throws IOException {
    HttpPut httpput = new HttpPut(submitUrl);
    httpput.addHeader("Authorization", getAuthorization());
    httpput.addHeader("content-type", ContentType.APPLICATION_JSON.getMimeType());

    StringEntity params = new StringEntity(jobConfigOverlays.toString(),
            ContentType.APPLICATION_JSON);
    httpput.setEntity(params);

    JsonObject jso = StreamsRestUtils.getGsonResponse(httpclient, httpput);

    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response: " + jso.toString());
    return jso;
}
 
Example #9
Source File: HttpsAdminServerTest.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testForceAssignNewToken() throws Exception {
    login(admin.email, admin.pass);
    HttpGet request = new HttpGet(httpsAdminServerUrl + "/users/token/[email protected]&app=Blynk&dashId=79780619&deviceId=0&new=123");

    try (CloseableHttpResponse response = httpclient.execute(request)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpPut put = new HttpPut(httpServerUrl + "123/update/v10");
    put.setEntity(new StringEntity("[\"100\"]", ContentType.APPLICATION_JSON));

    try (CloseableHttpResponse response = httpclient.execute(put)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
    }

    HttpGet get = new HttpGet(httpServerUrl + "123/get/v10");

    try (CloseableHttpResponse response = httpclient.execute(get)) {
        assertEquals(200, response.getStatusLine().getStatusCode());
        List<String> values = TestUtil.consumeJsonPinValues(response);
        assertEquals(1, values.size());
        assertEquals("100", values.get(0));
    }
}
 
Example #10
Source File: HttpComponentsClientHttpRequestFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a Commons HttpMethodBase object for the given HTTP method and URI specification.
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpUriRequest createHttpUriRequest(HttpMethod httpMethod, URI uri) {
	switch (httpMethod) {
		case GET:
			return new HttpGet(uri);
		case HEAD:
			return new HttpHead(uri);
		case POST:
			return new HttpPost(uri);
		case PUT:
			return new HttpPut(uri);
		case PATCH:
			return new HttpPatch(uri);
		case DELETE:
			return new HttpDelete(uri);
		case OPTIONS:
			return new HttpOptions(uri);
		case TRACE:
			return new HttpTrace(uri);
		default:
			throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
	}
}
 
Example #11
Source File: ModelResourceSourceTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetModelEditorSource() throws Exception {

    Model model = null;
    try {

        model = repositoryService.newModel();
        model.setName("Model name");
        repositoryService.saveModel(model);

        HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL_SOURCE, model.getId()));
        httpPut.setEntity(HttpMultipartHelper
                .getMultiPartEntity("sourcefile", "application/octet-stream", new ByteArrayInputStream("This is the new editor source".getBytes()), null));
        closeResponse(executeBinaryRequest(httpPut, HttpStatus.SC_NO_CONTENT));

        assertThat(new String(repositoryService.getModelEditorSource(model.getId()))).isEqualTo("This is the new editor source");

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}
 
Example #12
Source File: ProcessInstanceResourceTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Test suspending a single process instance.
 */
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testSuspendProcessInstance() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");

  ObjectNode requestNode = objectMapper.createObjectNode();
  requestNode.put("action", "suspend");

  HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

  // Check engine id instance is suspended
  assertEquals(1, runtimeService.createProcessInstanceQuery().suspended().processInstanceId(processInstance.getId()).count());

  // Check resulting instance is suspended
  JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
  closeResponse(response);
  assertNotNull(responseNode);
  assertEquals(processInstance.getId(), responseNode.get("id").textValue());
  assertTrue(responseNode.get("suspended").booleanValue());

  // Suspending again should result in conflict
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}
 
Example #13
Source File: HttpResponseMock.java    From iaf with Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
	HttpHost host = (HttpHost) invocation.getArguments()[0];
	HttpRequestBase request = (HttpRequestBase) invocation.getArguments()[1];
	HttpContext context = (HttpContext) invocation.getArguments()[2];

	InputStream response = null;
	if(request instanceof HttpGet)
		response = doGet(host, (HttpGet) request, context);
	else if(request instanceof HttpPost)
		response = doPost(host, (HttpPost) request, context);
	else if(request instanceof HttpPut)
		response = doPut(host, (HttpPut) request, context);
	else
		throw new Exception("mock method not implemented");

	return buildResponse(response);
}
 
Example #14
Source File: HttpResponseMock.java    From iaf with Apache License 2.0 6 votes vote down vote up
public InputStream doPut(HttpHost host, HttpPut request, HttpContext context) throws IOException {
	assertEquals("PUT", request.getMethod());
	StringBuilder response = new StringBuilder();
	response.append(request.toString() + lineSeparator);

	appendHeaders(request, response);

	Header contentTypeHeader = request.getEntity().getContentType();
	if(contentTypeHeader != null) {
		response.append(contentTypeHeader.getName() + ": " + contentTypeHeader.getValue() + lineSeparator);
	}

	response.append(lineSeparator);
	response.append(EntityUtils.toString(request.getEntity()));
	return new ByteArrayInputStream(response.toString().getBytes());
}
 
Example #15
Source File: HttpUtils.java    From frpMgr with MIT License 6 votes vote down vote up
/**
 * Put stream
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method,
		Map<String, String> headers,
		Map<String, String> querys,
		byte[] body)
           throws Exception {
   	HttpClient httpClient = wrapClient(host);

   	HttpPut request = new HttpPut(buildUrl(host, path, querys));
       for (Map.Entry<String, String> e : headers.entrySet()) {
       	request.addHeader(e.getKey(), e.getValue());
       }

       if (body != null) {
       	request.setEntity(new ByteArrayEntity(body));
       }

       return httpClient.execute(request);
   }
 
Example #16
Source File: TestServerBootstrapper.java    From java-client-api with Apache License 2.0 6 votes vote down vote up
private void installBootstrapExtension() throws IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(
      new AuthScope(host, port),
      new UsernamePasswordCredentials(username, password));

    HttpPut put = new HttpPut("http://" + host + ":" + port
      + "/v1/config/resources/bootstrap?method=POST&post%3Abalanced=string%3F");

    put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery"));
    HttpResponse response = client.execute(put);
    @SuppressWarnings("unused")
    HttpEntity entity = response.getEntity();
    System.out.println("Installed bootstrap extension.  Response is "
      + response.toString());

  }
 
Example #17
Source File: HttpRequestFactoryTest.java    From confluence-publisher with Apache License 2.0 6 votes vote down vote up
@Test
public void updatePageRequest_withValidParametersWithAncestorId_returnsValidHttpPutRequest() throws Exception {
    // arrange
    String contentId = "1234";
    String ancestorId = "1";
    String title = "title";
    String content = "content";
    Integer version = 2;
    String versionMessage = "version message";

    // act
    HttpPut updatePageRequest = this.httpRequestFactory.updatePageRequest(contentId, ancestorId, title, content, version, versionMessage);

    // assert
    assertThat(updatePageRequest.getMethod(), is("PUT"));
    assertThat(updatePageRequest.getURI().toString(), is(CONFLUENCE_REST_API_ENDPOINT + "/content/" + contentId));
    assertThat(updatePageRequest.getFirstHeader("Content-Type").getValue(), is(APPLICATION_JSON_UTF8));

    String jsonPayload = inputStreamAsString(updatePageRequest.getEntity().getContent(), UTF_8);
    String expectedJsonPayload = fileContent(Paths.get(CLASS_LOCATION, "update-page-request-with-ancestor-id.json").toString(), UTF_8);
    assertThat(jsonPayload, isSameJsonAs(expectedJsonPayload));
}
 
Example #18
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Updates the z value for the specified stack section.
 *
 * @param  stack          name of stack.
 * @param  sectionId      identifier for section.
 * @param  z              z value for section.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public void updateZForSection(final String stack,
                              final String sectionId,
                              final Double z)
        throws IOException {

    final String json = z.toString();
    final StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
    final URI uri = getUri(urls.getSectionZUrlString(stack, sectionId));
    final String requestContext = "PUT " + uri;
    final ResourceCreatedResponseHandler responseHandler = new ResourceCreatedResponseHandler(requestContext);

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    LOG.info("updateZForSection: submitting {}", requestContext);

    httpClient.execute(httpPut, responseHandler);
}
 
Example #19
Source File: HelmPublish.java    From gradle-plugins with Apache License 2.0 6 votes vote down vote up
@TaskAction
public void run() throws IOException {
	Project project = getProject();
	HelmExtension extension = project.getExtensions().getByType(HelmExtension.class);
	HelmExtension helm = project.getExtensions().getByType(HelmExtension.class);

	CredentialsProvider credentialsProvider = getCredentialsProvider();
	Set<String> packageNames = helm.getPackageNames();

	for (String packageName : packageNames) {
		try (CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()) {
			String url = extension.getRepository() + "/" + packageName + "-" + project.getVersion() + ".tgz";
			File helmChart = helm.getOutputFile(packageName);
			HttpPut post = new HttpPut(url);

			FileEntity entity = new FileEntity(helmChart);
			post.setEntity(entity);

			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() > 299) {
				throw new IOException(
						"failed to publish " + packageName + " to " + url + ", reason=" + response.getStatusLine());
			}
		}
	}
}
 
Example #20
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @return list of tile specs with the specified ids.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<TileSpec> getTileSpecsWithIds(final List<String> tileIdList,
                                          final String stack)
        throws IOException {

    final String tileIdListJson = JsonUtils.MAPPER.writeValueAsString(tileIdList);
    final StringEntity stringEntity = new StringEntity(tileIdListJson, ContentType.APPLICATION_JSON);
    final URI uri = getUri(urls.getStackUrlString(stack) + "/tile-specs-with-ids");
    final String requestContext = "PUT " + uri;

    final HttpPut httpPut = new HttpPut(uri);
    httpPut.setEntity(stringEntity);

    final TypeReference<List<TileSpec>> typeReference =
            new TypeReference<List<TileSpec>>() {};
    final JsonUtils.GenericHelper<List<TileSpec>> helper =
            new JsonUtils.GenericHelper<>(typeReference);
    final JsonResponseHandler<List<TileSpec>> responseHandler =
            new JsonResponseHandler<>(requestContext, helper);

    LOG.info("getTileSpecsWithIds: submitting {}", requestContext);

    return httpClient.execute(httpPut, responseHandler);
}
 
Example #21
Source File: HCRequestFactoryTest.java    From log4j2-elasticsearch with Apache License 2.0 6 votes vote down vote up
@Test
public void createsPutRequest() throws IOException, URISyntaxException {

    // given
    HCRequestFactory factory = createDefaultTestObject();
    String expectedUrl = UUID.randomUUID().toString();
    Request request = createDefaultMockRequest(expectedUrl, "PUT");

    // when
    HttpUriRequest result = factory.create(expectedUrl, request);

    // then
    assertTrue(result instanceof HttpPut);
    assertEquals(result.getURI(), new URI(expectedUrl));

}
 
Example #22
Source File: UpdateCustomPageRequest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected String doExecute(final HttpClient httpClient) throws IOException, HttpException {
    final HttpPut updatePageRequest = new HttpPut(
            String.format(getURLBase() + PORTAL_UPDATE_PAGE_API, pageToUpdate.getId()));
    updatePageRequest.setHeader(API_TOKEN_HEADER, getAPITokenFromCookie());
    final EntityBuilder entityBuilder = EntityBuilder.create();
    entityBuilder.setContentType(ContentType.APPLICATION_JSON);
    if(pageToUpdate.getProcessDefinitionId() != null) {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\", \"processDefinitionId\" : \"%s\" }", uploadedFileToken,pageToUpdate.getProcessDefinitionId()));
    }else {
        entityBuilder.setText(String.format("{\"pageZip\" : \"%s\" }", uploadedFileToken));
    }
    updatePageRequest.setEntity(entityBuilder.build());
    final HttpResponse response = httpClient.execute(updatePageRequest);
    final int status = response.getStatusLine().getStatusCode();
    String responseContent = contentAsString(response);
    if (status != HttpURLConnection.HTTP_OK) {
        throw new HttpException(responseContent.isEmpty() ? String.format("Add custom page failed with status: %s. Open Engine log for more details.", status) : responseContent);
    }
    return responseContent;
}
 
Example #23
Source File: RdbmsMandatoryAccessControlGrantTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Test(description = "Change owner of an exchange by a user who has resources:grant scope")
public void testChangeOwnerOfExchangeByAdminUser() throws Exception {

    ChangeOwnerRequest request = new ChangeOwnerRequest().owner(user1Username);

    HttpPut httpPut = new HttpPut(apiBasePath + ExchangesApiDelegate.EXCHANGES_API_PATH
            + "/" + exchangeName + "/permissions/owner/");
    ClientHelper.setAuthHeader(httpPut, adminUsername, adminPassword);
    String value = objectMapper.writeValueAsString(request);
    StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
    httpPut.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPut);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_NO_CONTENT,
            "Incorrect status code");

}
 
Example #24
Source File: RESTSpewer.java    From extract with MIT License 6 votes vote down vote up
@Override
public void write(final TikaDocument tikaDocument) throws IOException {
	final HttpPut put = new HttpPut(uri.resolve(tikaDocument.getId()));
	final List<NameValuePair> params = new ArrayList<>();

	params.add(new BasicNameValuePair(fields.forId(), tikaDocument.getId()));
	params.add(new BasicNameValuePair(fields.forPath(), tikaDocument.getPath().toString()));
	params.add(new BasicNameValuePair(fields.forText(), toString(tikaDocument.getReader())));

	if (outputMetadata) {
		parametrizeMetadata(tikaDocument.getMetadata(), params);
	}

	put.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
	put(put);
}
 
Example #25
Source File: SiteToSiteRestApiClient.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public TransactionResultEntity extendTransaction(final String transactionUrl) throws IOException {
    logger.debug("Sending extendTransaction request to transactionUrl: {}", transactionUrl);

    final HttpPut put = createPut(transactionUrl);

    put.setHeader("Accept", "application/json");
    put.setHeader(HttpHeaders.PROTOCOL_VERSION, String.valueOf(transportProtocolVersionNegotiator.getVersion()));

    setHandshakeProperties(put);

    try (final CloseableHttpResponse response = getHttpClient().execute(put)) {
        final int responseCode = response.getStatusLine().getStatusCode();
        logger.debug("extendTransaction responseCode={}", responseCode);

        try (final InputStream content = response.getEntity().getContent()) {
            switch (responseCode) {
                case RESPONSE_CODE_OK:
                    return readResponse(content);
                default:
                    throw handleErrResponse(responseCode, content);
            }
        }
    }

}
 
Example #26
Source File: HttpResourceUploader.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void upload(Factory<InputStream> source, Long contentLength, URI destination) throws IOException {
    HttpPut method = new HttpPut(destination);
    final RepeatableInputStreamEntity entity = new RepeatableInputStreamEntity(source, contentLength, ContentType.APPLICATION_OCTET_STREAM);
    method.setEntity(entity);
    HttpResponse response = http.performHttpRequest(method);
    EntityUtils.consume(response.getEntity());
    if (!http.wasSuccessful(response)) {
        throw new IOException(String.format("Could not PUT '%s'. Received status code %s from server: %s",
                destination, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
    }

}
 
Example #27
Source File: CaseInstanceVariableResourceTest.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@CmmnDeployment(resources = { "org/flowable/cmmn/rest/service/api/repository/oneHumanTaskCase.cmmn" })
public void testUpdateLocalDateCaseVariable() throws Exception {

    LocalDate initial = LocalDate.parse("2020-01-18");
    LocalDate tenDaysLater = initial.plusDays(10);
    CaseInstance caseInstance = runtimeService.createCaseInstanceBuilder().caseDefinitionKey("oneHumanTaskCase")
            .variables(Collections.singletonMap("overlappingVariable", (Object) "caseValue")).start();
    runtimeService.setVariable(caseInstance.getId(), "myVar", initial);

    // Update variable
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("name", "myVar");
    requestNode.put("value", "2020-01-28");
    requestNode.put("type", "localDate");

    HttpPut httpPut = new HttpPut(
            SERVER_URL_PREFIX + CmmnRestUrls.createRelativeResourceUrl(CmmnRestUrls.URL_CASE_INSTANCE_VARIABLE, caseInstance.getId(), "myVar"));
    httpPut.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

    assertThatJson(runtimeService.getVariable(caseInstance.getId(), "myVar")).isEqualTo(tenDaysLater);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertThat(responseNode).isNotNull();
    assertThatJson(responseNode)
            .when(Option.IGNORING_EXTRA_FIELDS)
            .isEqualTo("{"
                    + "  value: '2020-01-28'"
                    + "}");
}
 
Example #28
Source File: HttpClientStackTest.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
public void testCreatePutRequest() throws Exception {
    TestRequest.Put request = new TestRequest.Put();
    assertEquals(request.getMethod(), Method.PUT);

    HttpUriRequest httpRequest = HttpClientStack.createHttpRequest(request, null);
    assertTrue(httpRequest instanceof HttpPut);
}
 
Example #29
Source File: RemoteHttpService.java    From datawave with Apache License 2.0 5 votes vote down vote up
protected <T> T executePutMethod(String uriSuffix, Consumer<URIBuilder> uriCustomizer, Consumer<HttpPut> requestCustomizer, IOFunction<T> resultConverter,
                Supplier<String> errorSupplier) throws URISyntaxException, IOException {
    URIBuilder builder = buildURI();
    builder.setPath(serviceURI() + uriSuffix);
    uriCustomizer.accept(builder);
    HttpPut putRequest = new HttpPut(builder.build());
    requestCustomizer.accept(putRequest);
    return execute(putRequest, resultConverter, errorSupplier);
}
 
Example #30
Source File: ProcessInstanceResourceTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
/**
 * Test suspending a single process instance.
 */
@Deployment(resources = { "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testActivateProcessInstance() throws Exception {
  ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("processOne", "myBusinessKey");
  runtimeService.suspendProcessInstanceById(processInstance.getId());

  ObjectNode requestNode = objectMapper.createObjectNode();
  requestNode.put("action", "activate");

  HttpPut httpPut = new HttpPut(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE, processInstance.getId()));
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);

  // Check engine id instance is suspended
  assertEquals(1, runtimeService.createProcessInstanceQuery().active().processInstanceId(processInstance.getId()).count());

  // Check resulting instance is suspended
  JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
  closeResponse(response);
  assertNotNull(responseNode);
  assertEquals(processInstance.getId(), responseNode.get("id").textValue());
  assertFalse(responseNode.get("suspended").booleanValue());

  // Activating again should result in conflict
  httpPut.setEntity(new StringEntity(requestNode.toString()));
  closeResponse(executeRequest(httpPut, HttpStatus.SC_CONFLICT));
}