org.apache.http.entity.ContentType Java Examples

The following examples show how to use org.apache.http.entity.ContentType. 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: HttpServer.java    From hsac-fitnesse-fixtures with Apache License 2.0 7 votes vote down vote up
protected Charset getCharSet(Headers heHeaders) {
    Charset charset = UTF8;
    String contentTypeHeader = heHeaders.getFirst(HTTP.CONTENT_TYPE);
    if (contentTypeHeader != null) {
        try {
            ContentType contentType = ContentType.parse(contentTypeHeader);
            Charset contentTypeCharset = contentType.getCharset();
            if (contentTypeCharset != null) {
                charset = contentTypeCharset;
            }
        } catch (ParseException | UnsupportedCharsetException e) {
            // ignore, use default charset UTF8
        }
    }
    return charset;
}
 
Example #2
Source File: PacmanTableAPI.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public static String httpGetMethod(String url) throws Exception {
    String json = null;
    // Some custom method to craete HTTP post object
    HttpGet post = new HttpGet(url);
    CloseableHttpClient httpClient = null;
    post.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());
    try {
        // Get http client
        httpClient = PacmanUtils.getCloseableHttpClient();

        // Execute HTTP method
        CloseableHttpResponse res = httpClient.execute(post);

        // Verify response
        if (res.getStatusLine().getStatusCode() == 200) {
            json = EntityUtils.toString(res.getEntity());
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
    return json;
}
 
Example #3
Source File: ApacheHttpClient4SignerTest.java    From oauth1-signer-java with MIT License 6 votes vote down vote up
@Test
public void testSign_ShouldAddOAuth1HeaderToPostRequest() throws Exception {

    // GIVEN
    PrivateKey signingKey = TestUtils.getTestSigningKey();
    String consumerKey = "Some key";
    HttpPost httpPost = new HttpPost("https://api.mastercard.com/service");
    httpPost.setEntity(new StringEntity( "{\"foo\":\"bår\"}", ContentType.APPLICATION_JSON)); // ContentType.APPLICATION_JSON implies UTF-8 encoding

    // WHEN
    ApacheHttpClient4Signer instanceUnderTest = new ApacheHttpClient4Signer(consumerKey, signingKey);
    instanceUnderTest.sign(httpPost);

    // THEN
    Header[] authorizationHeaders = httpPost.getHeaders("Authorization");
    String authorizationHeaderValue = authorizationHeaders[0].getValue();
    Assert.assertNotNull(authorizationHeaderValue);
}
 
Example #4
Source File: HttpUtils.java    From QVisual with Apache License 2.0 6 votes vote down vote up
public static String post(String url, String fileName, String json) {
    Try<String> uploadedFile = Try.of(() -> {
        HttpClient client = HttpClientBuilder.create().build();

        HttpEntity entity = MultipartEntityBuilder
                .create()
                .setCharset(UTF_8)
                .setMode(BROWSER_COMPATIBLE)
                .addBinaryBody("file", json.getBytes(UTF_8), ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), UTF_8), fileName)
                .build();

        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);

        HttpResponse response = client.execute(httpPost);
        return new BasicResponseHandler().handleResponse(response);
    }).onFailure(t -> logger.error("[POST json]", t));

    return (uploadedFile.isSuccess()) ? uploadedFile.get() : null;
}
 
Example #5
Source File: FavoritesHandler.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public int doPost(String[] parts, HttpServletRequest req,
		HttpServletResponse res, Session session)
		throws PortalHandlerException {
	if ((parts.length == 3) && (parts[1].equals(URL_FRAGMENT)))
	{
		try {
			UserFavorites favorites = UserFavorites.fromJSON(req.getParameter("userFavorites"));

			synchronized (session) {
				saveUserFavorites(session.getUserId(), favorites);
			}

			res.setContentType(ContentType.APPLICATION_JSON.toString());
			return END;
		} catch (Exception e) {
			throw new PortalHandlerException(e);
		}
	}
	return NEXT;
}
 
Example #6
Source File: TokenDemo.java    From ais-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * 驾驶证识别,使用Base64编码后的文件方式,使用Token认证方式访问服务
 * @param token token认证串
 * @param formFile 文件路径
 * @throws IOException
 */
public static void requestOcrDriverLicenseBase64(String token, String formFile) {

	// 1.构建驾驶证识别服务所需要的参数
	String url = "https://ais.cn-north-1.myhuaweicloud.com/v1.0/ocr/driver-license";
	Header[] headers = new Header[] {new BasicHeader("X-Auth-Token", token), new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
	try {
		byte[] fileData = FileUtils.readFileToByteArray(new File(formFile));
		String fileBase64Str = Base64.encodeBase64String(fileData);
		JSONObject json = new JSONObject();
		json.put("image", fileBase64Str);
		StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

		// 2.传入驾驶证识别服务对应的参数, 使用POST方法调用服务并解析输出识别结果
		HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
		System.out.println(response);
		String content = IOUtils.toString(response.getEntity().getContent());
		System.out.println(content);
	} catch (Exception e) {
		e.printStackTrace();
	}

}
 
Example #7
Source File: ProtocolTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Checks that the server accepts a direct POST with a content type of "application/sparql-update".
 */
@Test
public void testUpdateDirect_POST() throws Exception {
	String query = "delete where { <monkey:pod> ?p ?o }";
	String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL);

	CloseableHttpClient httpclient = HttpClients.createDefault();
	HttpPost post = new HttpPost(location);
	HttpEntity entity = new StringEntity(query, ContentType.create(Protocol.SPARQL_UPDATE_MIME_TYPE));
	post.setEntity(entity);

	CloseableHttpResponse response = httpclient.execute(post);

	System.out.println("Update Direct Post Status: " + response.getStatusLine());
	int statusCode = response.getStatusLine().getStatusCode();
	assertEquals(true, statusCode >= 200 && statusCode < 400);
}
 
Example #8
Source File: HttpClientService.java    From galaxy with Apache License 2.0 6 votes vote down vote up
/**
 * 提交json数据
 *
 * @param url
 * @param json
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
    // 创建http POST请求
    HttpPost httpPost = new HttpPost(url);
    httpPost.setConfig(this.requestConfig);

    if (json != null) {
        // 构造一个form表单式的实体
        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        // 将请求实体设置到httpPost对象中
        httpPost.setEntity(stringEntity);
    }

    CloseableHttpResponse response = null;
    try {
        // 执行请求
        response = this.httpClient.execute(httpPost);
        return new HttpResult(response.getStatusLine().getStatusCode(),
                EntityUtils.toString(response.getEntity(), "UTF-8"));
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
 
Example #9
Source File: InfluxDBUtil.java    From jumbune with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Create database in influxdb according to configuration provided
 * 
 * @param configuration
 * @throws Exception
 */
public static void createDatabase(InfluxDBConf configuration) throws Exception {
	if (configuration == null) {
		return;
	}
	StringBuffer url = new StringBuffer();
	url.append(HTTP).append(configuration.getHost().trim()).append(COLON)
			.append(configuration.getPort()).append(SLASH_QUERY);
	CloseableHttpClient httpClient = HttpClients.createDefault();
	HttpPost httpPost = new HttpPost(url.toString());
	httpPost.setEntity(new StringEntity(CREATE_DATABASE + configuration.getDatabase() + "\"",
			ContentType.APPLICATION_FORM_URLENCODED));
	httpClient.execute(httpPost);
	httpClient.close();
	createRetentionPolicy(configuration);
	updateRetentionPolicy(configuration);
}
 
Example #10
Source File: QueuesRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Parameters({"admin-username", "admin-password"})
@Test
public void testDeleteQueue(String username, String password) throws IOException {
    String queueName = "testDeleteQueue";

    // Create a queue to delete.
    QueueCreateRequest request = new QueueCreateRequest()
            .name(queueName).durable(false).autoDelete(false);

    HttpPost httpPost = new HttpPost(apiBasePath + "/queues");
    ClientHelper.setAuthHeader(httpPost, username, password);

    String value = objectMapper.writeValueAsString(request);
    StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);
    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);

    // Delete the queue.
    HttpDelete httpDelete = new HttpDelete(apiBasePath + QueuesApiDelegate.QUEUES_API_PATH + "/" + queueName);
    ClientHelper.setAuthHeader(httpDelete, username, password);
    response = client.execute(httpDelete);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK);
}
 
Example #11
Source File: MetricStoreImpl.java    From griffin with Apache License 2.0 6 votes vote down vote up
private HttpEntity getHttpEntityForSearch(String metricName, int from, int
    size, long tmst)
    throws JsonProcessingException {
    Map<String, Object> map = new HashMap<>();
    Map<String, Object> queryParam = new HashMap<>();
    Map<String, Object> termQuery = Collections.singletonMap("name.keyword",
        metricName);
    queryParam.put("filter", Collections.singletonMap("term", termQuery));
    Map<String, Object> sortParam = Collections
        .singletonMap("tmst", Collections.singletonMap("order",
            "desc"));
    map.put("query", Collections.singletonMap("bool", queryParam));
    map.put("sort", sortParam);
    map.put("from", from);
    map.put("size", size);
    return new NStringEntity(JsonUtil.toJson(map),
        ContentType.APPLICATION_JSON);
}
 
Example #12
Source File: Node.java    From WavesJ with MIT License 6 votes vote down vote up
private HttpUriRequest matcherRequest(ApiJson obj, boolean isMarket) throws JsonProcessingException {
    String endpoint = "/matcher/orderbook";
    if (obj instanceof Order) {
        if (isMarket)
            endpoint += "/market";
    } else if (obj instanceof DeleteOrder) {
        DeleteOrder d = (DeleteOrder) obj;
        endpoint += d.getAssetPair().getAmountAsset() + '/' + d.getAssetPair().getPriceAsset() + "/delete";
    } else if (obj instanceof CancelOrder) {
        CancelOrder co = (CancelOrder) obj;
        if (co.getAssetPair() == null) {
            endpoint += "/cancel";
        } else
            endpoint += "/" + co.getAssetPair().getAmountAsset() + '/' + co.getAssetPair().getPriceAsset() + "/cancel";
    } else {
        throw new IllegalArgumentException();
    }
    HttpPost request = new HttpPost(uri.resolve(endpoint));
    request.setEntity(new StringEntity(wavesJsonMapper.writeValueAsString(obj), ContentType.APPLICATION_JSON));
    return request;
}
 
Example #13
Source File: DefaultYoutubeTrackDetails.java    From lavaplayer with Apache License 2.0 6 votes vote down vote up
private List<YoutubeTrackFormat> loadTrackFormatsFromAdaptive(String adaptiveFormats) throws Exception {
  List<YoutubeTrackFormat> tracks = new ArrayList<>();

  for (String formatString : adaptiveFormats.split(",")) {
    Map<String, String> format = decodeUrlEncodedItems(formatString, false);

    tracks.add(new YoutubeTrackFormat(
        ContentType.parse(format.get("type")),
        Long.parseLong(format.get("bitrate")),
        Long.parseLong(format.get("clen")),
        format.get("url"),
        format.get("s"),
        format.getOrDefault("sp", DEFAULT_SIGNATURE_KEY)
    ));
  }

  return tracks;
}
 
Example #14
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public List<Map<String, Object>> deleteObjects(String bucketName, List<String> objectNameList,
    boolean enableTrash) throws GalaxyFDSClientException {
  Preconditions.checkNotNull(bucketName);
  Preconditions.checkNotNull(objectNameList);

  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, (SubResource[]) null);
  ContentType contentType = ContentType.APPLICATION_JSON;
  StringEntity requestEntity = getJsonStringEntity(objectNameList, contentType);
  HashMap<String, String> params = new HashMap<String, String>();
  params.put("deleteObjects", "");
  if (!enableTrash) {
    params.put("enableTrash", String.valueOf(enableTrash));
  }
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    contentType, null, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.DeleteObjects);

  List<Map<String, Object>> responseList = (List<Map<String, Object>>) fdsHttpClient
      .processResponse(response, List.class,
        "delete " + objectNameList.size() + " objects under bucket [" + bucketName + "]");
  return responseList;
}
 
Example #15
Source File: QueuesRestApiTest.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Parameters({"admin-username", "admin-password"})
@Test
public void testPositiveCreateQueue(String username, String password) throws IOException {
    String queueName = "testPositiveCreateQueue";
    QueueCreateRequest request = new QueueCreateRequest()
            .name(queueName).durable(false).autoDelete(false);

    HttpPost httpPost = new HttpPost(apiBasePath + "/queues");
    ClientHelper.setAuthHeader(httpPost, username, password);
    String value = objectMapper.writeValueAsString(request);
    StringEntity stringEntity = new StringEntity(value, ContentType.APPLICATION_JSON);
    httpPost.setEntity(stringEntity);

    CloseableHttpResponse response = client.execute(httpPost);

    Assert.assertEquals(response.getStatusLine().getStatusCode(), HttpStatus.SC_CREATED);
    Assert.assertTrue(response.getFirstHeader(HttpHeaders.LOCATION)
                    .getValue().contains("/queues/" + queueName),
                        "Incorrect location header");

    String body = responseHandler.handleResponse(response);
    QueueCreateResponse queueCreateResponse = objectMapper.readValue(body, QueueCreateResponse.class);

    Assert.assertFalse(queueCreateResponse.getMessage().isEmpty(), "Response body shouldn't be empty");

}
 
Example #16
Source File: InfluxDBClient.java    From metrics with Apache License 2.0 6 votes vote down vote up
public void flush() throws IOException {
  if (byteBuffer.position() == 0) {
    return;
  }
  byteBuffer.flip();
  HttpPost httpPost = new HttpPost(this.dbUri);
  httpPost.setEntity(
      new ByteArrayEntity(byteBuffer.array(), 0, byteBuffer.limit(), ContentType.DEFAULT_TEXT));
  try {
    CloseableHttpResponse response = httpClient.execute(httpPost);
    EntityUtils.consumeQuietly(response.getEntity());
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode / 100 != 2) {
      throw new IOException(
          "InfluxDB write failed: " + statusCode + " " + response.getStatusLine()
              .getReasonPhrase());
    }
  } finally {
    // Always clear the buffer. But this will lead to data loss in case of non 2xx response (i.e write operation failed)
    // received from the InfluxDB server. Ideally non 2xx server response should be rare but revisit this part
    // if data loss occurs frequently.
    byteBuffer.clear();
  }
}
 
Example #17
Source File: WatsonUserModeller.java    From talent-manager with Apache License 2.0 6 votes vote down vote up
private String makePOST(String base, String suffix, String content)
{
	try
	{
		URI uri = new URI(base + suffix).normalize();
		String profileJSON = executor.execute(Request.Post(uri)
   			    .setHeader("Accept", "application/json")
   			    .bodyString(content, ContentType.APPLICATION_JSON)
   			    ).returnContent().asString();
   		return profileJSON;
	} catch (Exception e)
	{
		e.printStackTrace();
	}
	return "An error occured on POST to " + base + suffix;
}
 
Example #18
Source File: RemoteTransformerClient.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
HttpEntity getRequestEntity(ContentReader reader, String sourceMimetype, String sourceExtension,
                                    String targetExtension, long timeoutMs, String[] args, StringJoiner sj)
{
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    ContentType contentType = ContentType.create(sourceMimetype);
    builder.addBinaryBody("file", reader.getContentInputStream(), contentType, "tmp."+sourceExtension);
    builder.addTextBody("targetExtension", targetExtension);
    sj.add("targetExtension" + '=' + targetExtension);
    for (int i=0; i< args.length; i+=2)
    {
        if (args[i+1] != null)
        {
            builder.addTextBody(args[i], args[i + 1]);

            sj.add(args[i] + '=' + args[i + 1]);
        }
    }

    if (timeoutMs > 0)
    {
        String timeoutMsString = Long.toString(timeoutMs);
        builder.addTextBody("timeout", timeoutMsString);
        sj.add("timeout=" + timeoutMsString);
    }
    return builder.build();
}
 
Example #19
Source File: MultiReadHttpServletRequestWrapper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
private Iterable<NameValuePair> decodeParams(String body) {
    String encoding = getRequest().getCharacterEncoding();
    if (StringUtils.isEmpty(encoding)) {
        encoding = Charset.defaultCharset().name();
    }
    List<NameValuePair> params = new ArrayList<>(
            URLEncodedUtils.parse(body, Charset.forName(encoding)));
    try {
        String cts = getContentType();
        if (cts != null) {
            ContentType ct = ContentType.parse(cts);
            if (ct.getMimeType().equals(ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
                List<NameValuePair> postParams = URLEncodedUtils.parse(
                        IOUtils.toString(getReader()), Charset.forName(encoding));
                CollectionUtils.addAll(params, postParams);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
    return params;
}
 
Example #20
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 #21
Source File: BaseClient.java    From galaxy-sdk-java with Apache License 2.0 6 votes vote down vote up
protected HttpUriRequest prepareRequestMethod(URI uri, HttpMethod method, ContentType contentType,
    HashMap<String, String> params, Map<String, List<Object>> headers, HttpEntity requestEntity)
    throws IOException {
  if (params != null) {
    URIBuilder builder = new URIBuilder(uri);
    for (Entry<String, String> param : params.entrySet()) {
      builder.addParameter(param.getKey(), param.getValue());
    }
    try {
      uri = builder.build();
    } catch (URISyntaxException e) {
      throw new IOException("Invalid param: " + params.toString(), e);
    }
  }

  Map<String, Object> h = prepareRequestHeader(uri, method, contentType);
  headers = mergeToHeaders(headers, h);
  return createHttpRequest(uri, method, headers, requestEntity);
}
 
Example #22
Source File: JWTAuthPluginIntegrationTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private Pair<String, Integer> post(String url, String json, String token) throws IOException {
  URL createUrl = new URL(url);
  HttpURLConnection con = (HttpURLConnection) createUrl.openConnection();
  con.setRequestMethod("POST");
  con.setRequestProperty(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
  if (token != null)
    con.setRequestProperty("Authorization", "Bearer " + token);

  con.setDoOutput(true);
  OutputStream os = con.getOutputStream();
  os.write(json.getBytes(StandardCharsets.UTF_8));
  os.flush();
  os.close();

  con.connect();
  BufferedReader br2 = new BufferedReader(new InputStreamReader((InputStream) con.getContent(), StandardCharsets.UTF_8));
  String result = br2.lines().collect(Collectors.joining("\n"));
  int code = con.getResponseCode();
  con.disconnect();
  return new Pair<>(result, code);
}
 
Example #23
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void setObjectAcl(String bucketName, String objectName, String versionId,
    AccessControlList acl) throws GalaxyFDSClientException {
  Preconditions.checkNotNull(acl);
  AccessControlPolicy acp = aclToAcp(acl);
  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName + "/" + objectName, SubResource.ACL);
  HashMap<String, String> params = new HashMap<String, String>();
  if (versionId != null) {
    params.put(VERSION_ID, versionId);
  }

  StringEntity requestEntity = getJsonStringEntity(acp, ContentType.APPLICATION_JSON);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    ContentType.APPLICATION_JSON, null, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.PutObjectACL);

  fdsHttpClient.processResponse(response, null, "set acl for object [" + objectName
      + "] with versionId [" + versionId + "] under bucket [" + bucketName + "]");
}
 
Example #24
Source File: TestCaldavHttpClient4.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testReportTasks() throws IOException {
    String buffer = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
            "<C:calendar-query xmlns:C=\"urn:ietf:params:xml:ns:caldav\" xmlns:D=\"DAV:\">" +
            "<D:prop>" +
            "<C:calendar-data/>" +
            "</D:prop>" +
            "<C:comp-filter name=\"VCALENDAR\">" +
            "<C:comp-filter name=\"VTODO\"/>" +
            "</C:comp-filter>" +
            "<C:filter>" +
            "</C:filter>" +
            "</C:calendar-query>";
    BaseDavRequest method = new BaseDavRequest(URI.create("/users/" + session.getEmail() + "/calendar/")) {
        @Override
        public String getMethod() {
            return DavMethods.METHOD_REPORT;
        }
    };
    method.setEntity(new StringEntity(buffer, ContentType.create("text/xml", "UTF-8")));

    httpClient.executeDavRequest(method);
}
 
Example #25
Source File: WebDriverFactory.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Boolean addGeckoDriverAddon(File addonLoc, String url) {
    try {
        HttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        Map<String, Object> addonInfo = new HashMap<>();
        addonInfo.put("temporary", true);
        addonInfo.put("path", addonLoc.getAbsolutePath());
        String json = new Gson().toJson(addonInfo);
        StringEntity requestEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
        post.setEntity(requestEntity);
        return client.execute(post).getStatusLine().getStatusCode() == 200;
    } catch (IOException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
    return false;
}
 
Example #26
Source File: GalaxyFDSClient.java    From galaxy-fds-sdk-java with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteBucketAcl(String bucketName, AccessControlList acl)
    throws GalaxyFDSClientException {
  Preconditions.checkNotNull(acl);

  URI uri = formatUri(fdsConfig.getBaseUri(), bucketName, SubResource.ACL);
  HashMap<String, String> params = new HashMap<String, String>();
  params.put("action", "delete");
  ContentType contentType = ContentType.APPLICATION_JSON;
  AccessControlPolicy acp = aclToAcp(acl);
  StringEntity requestEntity = getJsonStringEntity(acp, contentType);
  HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.PUT,
    contentType, null, params, null, requestEntity);

  HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest, Action.DeleteBucketACL);

  fdsHttpClient.processResponse(response, null, "delete bucket [" + bucketName + "] acl");
}
 
Example #27
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 #28
Source File: ElasticSearchUtil.java    From RCT with Apache License 2.0 6 votes vote down vote up
public static boolean postIndexDocument(String index, String type, String document) throws Exception {
	StringEntity entity = new StringEntity(document, ContentType.APPLICATION_JSON);
	String result = httpPost(getUrl() + "/" + index + "/" + type + "?refresh=true", entity);
	try {
		JSONObject json = JSONObject.parseObject(result);
		if (json.containsKey("_shards")) {
			JSONObject shards = json.getJSONObject("_shards");
			if (shards.getLongValue("failed") == 0) {
				return true;
			}
		}
	} catch (Exception e) {
		throw new Exception(result);
	}
	return false;
}
 
Example #29
Source File: RenderDataClient.java    From render with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sends the specified world coordinates to the server to be mapped to tiles.
 * Because tiles overlap, each coordinate can potentially be mapped to multiple tiles.
 * The result is a list of coordinate lists for all mapped tiles.
 *
 * For example,
 * <pre>
 *     Given:                 Result could be:
 *     [                      [
 *       { world: [1,2] },        [ { tileId: A, world: [1,2] }, { tileId: B, world: [1,2] } ],
 *       { world: [3,4] }         [ { tileId: C, world: [3,4] } ]
 *     ]                      ]
 * </pre>
 *
 * @param  worldCoordinates  world coordinates to be mapped to tiles.
 * @param  stack             name of stack.
 * @param  z                 z value for layer.
 *
 * @return list of coordinate lists.
 *
 * @throws IOException
 *   if the request fails for any reason.
 */
public List<List<TileCoordinates>> getTileIdsForCoordinates(final List<TileCoordinates> worldCoordinates,
                                                            final String stack,
                                                            final Double z)
        throws IOException {

    final String worldCoordinatesJson = JsonUtils.MAPPER.writeValueAsString(worldCoordinates);
    final StringEntity stringEntity = new StringEntity(worldCoordinatesJson, ContentType.APPLICATION_JSON);
    final URI uri = getUri(urls.getTileIdsForCoordinatesUrlString(stack, z));
    final String requestContext = "PUT " + uri;

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

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

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

    return httpClient.execute(httpPut, responseHandler);
}
 
Example #30
Source File: WS.java    From candybean with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Private helper method to abstract creating a POST/PUT request.
 * Side Effect: Adds the body to the request
 *
 * @param request     A PUT or POST request
 * @param body        Map of Key Value pairs
 * @param contentType The intended content type of the body
 */
protected static void addBodyToRequest(HttpEntityEnclosingRequestBase request, Map<String, Object> body, ContentType contentType) {
	if (body != null) {
		if (contentType == ContentType.MULTIPART_FORM_DATA) {
			MultipartEntityBuilder builder = MultipartEntityBuilder.create();
			for (Map.Entry<String, Object> entry : body.entrySet()) {
				builder.addTextBody(entry.getKey(), (String) entry.getValue());
			}
			request.setEntity(builder.build());
		} else {
			JSONObject jsonBody = new JSONObject(body);
			StringEntity strBody = new StringEntity(jsonBody.toJSONString(), ContentType.APPLICATION_JSON);
			request.setEntity(strBody);
		}
	}
}