Java Code Examples for org.apache.http.client.methods.CloseableHttpResponse#getStatusLine()

The following examples show how to use org.apache.http.client.methods.CloseableHttpResponse#getStatusLine() . 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: HttpRequestException.java    From caravan with Apache License 2.0 6 votes vote down vote up
public HttpRequestException(CloseableHttpResponse response) {
    super(toErrorMessage(response));

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return;

    _statusCode = statusLine.getStatusCode();
    _reasonPhrase = statusLine.getReasonPhrase();
    _protocolVersion = statusLine.getProtocolVersion();
    _responseHeaders = response.getAllHeaders();

    HttpEntity entity = response.getEntity();
    if (entity == null)
        return;

    try (InputStream is = entity.getContent();) {
        _responseBody = EntityUtils.toString(entity);
    } catch (Throwable ex) {

    }
}
 
Example 2
Source File: ActionResult.java    From curly with Apache License 2.0 6 votes vote down vote up
public void processHttpResponse(CloseableHttpResponse httpResponse, ResultType resultType) throws IOException {
    StatusLine status = httpResponse.getStatusLine();
    String statusKey = COMPLETED_SUCCESSFUL;
    boolean successfulResponseCode = false;
    if (status.getStatusCode() >= 200 && status.getStatusCode() < 400) {
        successfulResponseCode = true;
    } else {
        statusKey = COMPLETED_UNSUCCESSFUL;
    }
    String resultMessage = "";
    if (resultType == ResultType.HTML) {
        ParsedResponseMessage message = extractHtmlMessage(httpResponse).orElse(UNKNOWN_RESPONSE);
        if (message.type == RESULT_TYPE.FAIL) {
            successfulResponseCode = false;
            statusKey = COMPLETED_UNSUCCESSFUL;
        }
        resultMessage = status.getReasonPhrase() + " / " + message.message;
    } else {
        resultMessage = status.getReasonPhrase();
    }
    percentSuccess().unbind();
    percentSuccess().set(successfulResponseCode ? 1 : 0);
    invalidateBindings();
    setStatus(statusKey, status.getStatusCode(), resultMessage);
}
 
Example 3
Source File: HttpClientBasic.java    From JavaTutorial with Apache License 2.0 6 votes vote down vote up
private void processResponse(CloseableHttpResponse response) 
            throws UnsupportedOperationException, IOException {
        try {
            // 获取响应头
            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                _logger.info(header.getName() + ":" + header.getValue());
            }
            
            // 获取状态信息
            StatusLine sl =response.getStatusLine();
            _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", 
                    sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
            
            // 获取响应内容
            HttpEntity entity = response.getEntity();
            _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", 
                    null == entity.getContentType() ? "" : entity.getContentType().getValue(), 
                    entity.getContentLength(),
                    null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
            _logger.info(EntityUtils.toString(entity, _charset));
//            _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
        } finally {
            response.close();
        }
    }
 
Example 4
Source File: CrowdManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void handleHTTPError(CloseableHttpResponse response) throws RemoteException {
    final StatusLine statusLine = response.getStatusLine();
    final int status = statusLine.getStatusCode();
    final String statusText = statusLine.getReasonPhrase();
    final String body = response.getEntity().toString();

    StringBuilder strBuf = new StringBuilder();
    strBuf.append("Crowd returned HTTP error code:").append(status);
    strBuf.append(" - ").append(statusText);
    if (StringUtils.isNotBlank(body)) {
        strBuf.append("\n").append(body);
    }
    
    throw new RemoteException(strBuf.toString());
}
 
Example 5
Source File: MCRDataciteClient.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param doi the doi
 * @return the resolved metadata of the doi
 * @throws MCRDatacenterAuthenticationException if the authentication is wrong
 * @throws MCRIdentifierUnresolvableException if the doi is not valid or can not be resolved
 * @throws JDOMException if the metadata is empty or not a valid xml document
 * @throws MCRDatacenterException if there is something wrong with the communication with the datacenter
 */
public Document resolveMetadata(final MCRDigitalObjectIdentifier doi) throws MCRDatacenterAuthenticationException,
    MCRIdentifierUnresolvableException, JDOMException, MCRDatacenterException {
    URI requestURI = getRequestURI("/metadata/" + doi.asString());
    HttpGet get = new HttpGet(requestURI);
    try (CloseableHttpClient httpClient = getHttpClient()) {
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        switch (statusLine.getStatusCode()) {
            case HttpStatus.SC_OK:
                SAXBuilder builder = new SAXBuilder();
                return builder.build(entity.getContent());
            case HttpStatus.SC_UNAUTHORIZED:
                throw new MCRDatacenterAuthenticationException();
            case HttpStatus.SC_NO_CONTENT:
                throw new MCRIdentifierUnresolvableException(doi.asString(),
                    "The identifier " + doi.asString() + " is currently not resolvable");
            case HttpStatus.SC_NOT_FOUND:
                throw new MCRIdentifierUnresolvableException(doi.asString(),
                    "The identifier " + doi.asString() + " was not found!");
            case HttpStatus.SC_GONE:
                throw new MCRIdentifierUnresolvableException(doi.asString(),
                    "The identifier " + doi.asString() + " was deleted!");
            default:
                throw new MCRDatacenterException("Unknown return status: " + getStatusString(response));
        }
    } catch (IOException e) {
        throw new MCRDatacenterException("Error while resolving metadata!", e);
    }
}
 
Example 6
Source File: InfluxDBReporterTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadFailedServerError(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine,
    @Capturing Logger logger) throws IOException, InterruptedException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 500;
  }};

  MetricRegistry registry = new MetricRegistry();
  InfluxDBReporter reporter = InfluxDBReporter.builder()
      .withBaseUri(URI.create("http://localhost:8086"))
      .withDatabase("test")
      .build();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    logger.error(anyString, withInstanceOf(IOException.class));
  }};
}
 
Example 7
Source File: InfluxDBReporterTest.java    From metrics with Apache License 2.0 5 votes vote down vote up
@Test
public void testReporting(@Mocked CloseableHttpClient httpClient,
    @Mocked CloseableHttpResponse closeableHttpResponse, @Mocked StatusLine statusLine)
    throws InterruptedException, IOException {
  new Expectations() {{
    httpClient.execute((HttpUriRequest) any);
    result = closeableHttpResponse;
    closeableHttpResponse.getStatusLine();
    result = statusLine;
    statusLine.getStatusCode();
    result = 200;
  }};

  MetricRegistry registry = new MetricRegistry();
  InfluxDBReporter reporter = InfluxDBReporter.builder()
      .withBaseUri(URI.create("http://localhost:8086"))
      .withDatabase("test")
      .build();
  registry.addReporter(reporter);

  Counter counter = registry.counter("counter");
  counter.inc("tag", "value");

  Thread.sleep(3000);

  new Verifications() {{
    httpClient.execute((HttpUriRequest) any);
    times = 1;
  }};
}
 
Example 8
Source File: FileUploadServletTest.java    From selenium-grid-extensions with Apache License 2.0 5 votes vote down vote up
@Test
public void testDoPost() throws IOException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost("http://localhost:" + port + "/FileUploadServlet/");
    httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString());

    FileInputStream fileInputStream = new FileInputStream(zipArchive);
    InputStreamEntity entity = new InputStreamEntity(fileInputStream);
    httpPost.setEntity(entity);

    CloseableHttpResponse execute = httpClient.execute(httpPost);

    StatusLine statusLine = execute.getStatusLine();
    assertThat(statusLine.getStatusCode(), equalTo(200));

    try (
            InputStream content = execute.getEntity().getContent()) {
        String directory = IOUtils.toString(content, StandardCharsets.UTF_8);
        unzippedArchive = new File(directory);
        unzippedFile = new File(directory + "/" + ZIP_FILE_NAME);
    }

    assertThat(unzippedFile.exists(), is(true));

    try (FileInputStream unzippedFileStream = new FileInputStream(unzippedFile)) {
        String contents = IOUtils.toString(unzippedFileStream, StandardCharsets.UTF_8);
        assertThat(contents, is("test data"));
    }
}
 
Example 9
Source File: ElasticsearchAvailable.java    From spring-data-examples with Apache License 2.0 5 votes vote down vote up
private void checkServerRunning() {

		try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
			CloseableHttpResponse response = client.execute(new HttpHead(url));
			if (response != null && response.getStatusLine() != null) {
				Assumptions.assumeThat(response.getStatusLine().getStatusCode()).isEqualTo(200);
			}
		} catch (IOException e) {
			throw new AssumptionViolatedException(String.format("Elasticsearch Server seems to be down. %s", e.getMessage()));
		}
	}
 
Example 10
Source File: HttpUtils.java    From bce-sdk-java with Apache License 2.0 5 votes vote down vote up
public static void printResponse(CloseableHttpResponse response) {
    if (!HTTP_VERBOSE) {
        return;
    }
    System.out.println("\n<------------- ");
    StatusLine status = response.getStatusLine();
    System.out.println(status.getStatusCode() + " - "
            + status.getReasonPhrase());
    Header[] heads = response.getAllHeaders();
    for (Header h : heads) {
        System.out.println(h.getName() + " : " + h.getValue());
    }
}
 
Example 11
Source File: OpenTSDBHttpClient.java    From metrics with Apache License 2.0 5 votes vote down vote up
void flush() throws IOException {
  if (currentBatchSize < 1) {
    return;
  }

  // flush
  writer.write(']');
  writer.flush();
  HttpPost httpPost = new HttpPost(dbUri);
  httpPost.setEntity(new ByteArrayEntity(buffer.toByteArray(), ContentType.APPLICATION_JSON));
  final StatusLine status;
  CloseableHttpResponse response = null;
  try {
    response = httpClient.execute(httpPost);
    status = response.getStatusLine();
    // CLOVER:OFF
    // Just tracing.
    if (LOG.isTraceEnabled()) {
      LOG.trace("Response from OpenTSDB [{}] ",
          EntityUtils.toString(response.getEntity()));
    }
    // CLOVER:ON
  } finally {
    if (response != null) {
      EntityUtils.consumeQuietly(response.getEntity());
    }
    // reset our buffer and batch size
    currentBatchSize = 0;
    buffer.reset();
    writer.write('[');
  }
  if (status.getStatusCode() / 100 != 2) {
    throw new IllegalStateException(String.format(
        "Failed to write metrics to OpenTSDB '%d' - '%s'",
        status.getStatusCode(),
        status.getReasonPhrase()));
  }
}
 
Example 12
Source File: HttpRequestException.java    From caravan with Apache License 2.0 5 votes vote down vote up
private static String toErrorMessage(CloseableHttpResponse response) {
    NullArgumentChecker.DEFAULT.check(response, "response");

    StatusLine statusLine = response.getStatusLine();
    if (statusLine == null)
        return "Http request failed. status line is null.";

    return String.format("Http request failed. status code: %s, reason phrase: %s, protocol version: %s", statusLine.getStatusCode(),
            statusLine.getReasonPhrase(), statusLine.getProtocolVersion());
}
 
Example 13
Source File: OAuthClient.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
private static TokenResponse getTokenResponse(CloseableHttpResponse response)
        throws APIManagementException, IOException {
    int responseCode = response.getStatusLine().getStatusCode();

    if (!(responseCode == HttpStatus.SC_OK)) {
        throw new APIManagementException("Error while accessing the Token URL. "
                + "Found http status " + response.getStatusLine());
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(response
            .getEntity().getContent(), StandardCharsets.UTF_8));
    String inputLine;
    StringBuilder stringBuilder = new StringBuilder();

    while ((inputLine = reader.readLine()) != null) {
        stringBuilder.append(inputLine);
    }

    TokenResponse tokenResponse = new Gson().fromJson(stringBuilder.toString(), TokenResponse.class);
    long currentTimeInSeconds = System.currentTimeMillis() / 1000;
    long expiryTimeInSeconds = currentTimeInSeconds + Long.parseLong(tokenResponse.getExpiresIn());
    tokenResponse.setValidTill(expiryTimeInSeconds);

    if (log.isDebugEnabled()) {
        log.debug("Response: [status-code] " + responseCode + " [message] "
                + stringBuilder.toString());
    }
    return tokenResponse;
}
 
Example 14
Source File: ApacheCloudStackClient.java    From apache-cloudstack-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the request with the given {@link HttpContext}.
 */
protected String executeRequestGetResponseAsString(String urlRequest, CloseableHttpClient httpClient, HttpContext httpContext) {
    try {
        HttpRequestBase httpGetRequest = new HttpGet(urlRequest);
        CloseableHttpResponse response = httpClient.execute(httpGetRequest, httpContext);
        StatusLine requestStatus = response.getStatusLine();
        if (requestStatus.getStatusCode() == HttpStatus.SC_OK) {
            return getResponseAsString(response);
        }
        throw new ApacheCloudStackClientRequestRuntimeException(requestStatus.getStatusCode(), getResponseAsString(response), urlRequest.toString());
    } catch (IOException e) {
        LOGGER.error(String.format("Error while executing request [%s]", urlRequest));
        throw new ApacheCloudStackClientRuntimeException(e);
    }
}
 
Example 15
Source File: HttpClientUtil.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * 使用post方式提交参数
 *
 * @param url url
 * @param params         提交的参数已key,value的形式保存在map当中
 * @param socketTime 链接超时时间
 * @param connectTimeout 链接超时时间
 * @param charset 字符集
 * @return 返回值
 * @throws ClientProtocolException ClientProtocolException
 * @throws IOException IOException
 */
public static String post(String url, Map<String, String> params, int socketTime, int connectTimeout,
                          String charset) throws ClientProtocolException, IOException {
	CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
	RequestConfig requestConfig = RequestConfig.custom()
			.setSocketTimeout(socketTime <= 0 ? 120000 : socketTime)
			.setConnectTimeout(connectTimeout <= 0 ? 120000 : connectTimeout)
			.setConnectionRequestTimeout(connectTimeout <= 0 ? 120000 : connectTimeout)
			.build();
	HttpPost httpPost = new HttpPost(url);
	httpPost.setConfig(requestConfig);
	List<NameValuePair> nvps = new ArrayList<NameValuePair>();
	for (Map.Entry<String, String> entry : params.entrySet()) {
		nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
	}
	if (StringUtils.isEmpty(charset)) {
		charset = CHARSET;
	}
	httpPost.setEntity(new UrlEncodedFormEntity(nvps, charset));
	CloseableHttpResponse response1 = null;
	try {
		response1 = httpclient.execute(httpPost);
		HttpEntity entity1 = response1.getEntity();
		String responseBody = EntityUtils.toString(entity1, charset);
		EntityUtils.consume(entity1);
		StatusLine statusLine = response1.getStatusLine();
		int statusCode = statusLine.getStatusCode();
		logger.info("statusCode:{}", statusCode);
		if (statusCode != 200) {
			writeLog(statusCode, responseBody);
		}
		return responseBody;
	} finally {
		IOUtils.closeQuietly(response1);
	}
}
 
Example 16
Source File: MCRDataciteClient.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public List<MCRDigitalObjectIdentifier> getDOIList() throws MCRPersistentIdentifierException {
    URI requestURI = getRequestURI("/doi");

    HttpGet get = new HttpGet(requestURI);
    try (CloseableHttpClient httpClient = getHttpClient()) {
        CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        switch (statusLine.getStatusCode()) {
            case HttpStatus.SC_OK:
                try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
                    List<MCRDigitalObjectIdentifier> doiList = new ArrayList<>();
                    while (scanner.hasNextLine()) {
                        String line = scanner.nextLine();
                        Optional<MCRDigitalObjectIdentifier> parse = new MCRDOIParser().parse(line);
                        MCRDigitalObjectIdentifier doi = parse
                            .orElseThrow(() -> new MCRException("Could not parse DOI from Datacite!"));
                        doiList.add(doi);
                    }
                    return doiList;
                }
            case HttpStatus.SC_NO_CONTENT:
                return Collections.emptyList();
            default:
                throw new MCRDatacenterException(
                    String.format(Locale.ENGLISH, "Unknown error while resolving all doi’s \n %d - %s",
                        statusLine.getStatusCode(), statusLine.getReasonPhrase()));
        }
    } catch (IOException e) {
        throw new MCRDatacenterException("Unknown error while resolving all doi’s", e);
    }
}
 
Example 17
Source File: Msg91SmsProvider.java    From sunbird-lms-service with MIT License 4 votes vote down vote up
/**
 * This method is used to send SMS using Get method
 *
 * @param mobileNumber String
 * @param smsText String
 * @return boolean
 */
public boolean sendSmsGetMethod(String mobileNumber, String smsText) {
  CloseableHttpClient httpClient = null;
  try {
    httpClient = HttpClients.createDefault();
    String path = null;
    if (validateSettings(mobileNumber, smsText)) {

      String tempMobileNumber = removePlusFromMobileNumber(mobileNumber);

      logger.debug("Msg91SmsProvider - after removePlusFromMobileNumber " + tempMobileNumber);

      logger.debug("Inside GET");
      path =
          getCompletePath(
              baseUrl + getUrl,
              sender,
              smsRoute,
              tempMobileNumber,
              authKey,
              URLEncoder.encode(getDoubleEncodedSMS(smsText), "UTF-8"));

      logger.debug("Msg91SmsProvider -Executing request - " + path);

      HttpGet httpGet = new HttpGet(path);

      CloseableHttpResponse response = httpClient.execute(httpGet);
      StatusLine sl = response.getStatusLine();
      response.close();
      if (sl.getStatusCode() != 200) {
        logger.error(
            "SMS code for "
                + tempMobileNumber
                + " could not be sent: "
                + sl.getStatusCode()
                + " - "
                + sl.getReasonPhrase());
      }
      return sl.getStatusCode() == 200;

    } else {
      logger.debug("Msg91SmsProvider - Some mandatory parameters are empty!");
      return false;
    }
  } catch (IOException e) {
    logger.error(e);
    return false;
  } finally {
    closeHttpResource(httpClient);
  }
}
 
Example 18
Source File: TelemetryService.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
/**
 * log error http response to telemetry
 */
public void logHttpRequestTelemetryEvent(
    String eventName,
    HttpRequestBase request,
    int injectSocketTimeout,
    AtomicBoolean canceling,
    boolean withoutCookies,
    boolean includeRetryParameters,
    boolean includeRequestGuid,
    CloseableHttpResponse response,
    final Exception savedEx,
    String breakRetryReason,
    long retryTimeout,
    int retryCount,
    String sqlState,
    int errorCode)
{
  if (enabled)
  {
    TelemetryEvent.LogBuilder logBuilder = new TelemetryEvent.LogBuilder();
    JSONObject value = new JSONObject();
    value.put("request", request.toString());
    value.put("injectSocketTimeout", injectSocketTimeout);
    value.put("canceling", canceling == null ? "null" : canceling.get());
    value.put("withoutCookies", withoutCookies);
    value.put("includeRetryParameters", includeRetryParameters);
    value.put("includeRequestGuid", includeRequestGuid);
    value.put("breakRetryReason", breakRetryReason);
    value.put("retryTimeout", retryTimeout);
    value.put("retryCount", retryCount);
    value.put("sqlState", sqlState);
    value.put("errorCode", errorCode);
    int responseStatusCode = -1;
    if (response != null)
    {
      value.put("response", response.toString());
      value.put("responseStatusLine", response.getStatusLine().toString());
      if (response.getStatusLine() != null)
      {
        responseStatusCode = response.getStatusLine().getStatusCode();
        value.put("responseStatusCode", responseStatusCode);
      }
    }
    else
    {
      value.put("response", null);
    }
    if (savedEx != null)
    {
      value.put("exceptionMessage", savedEx.getLocalizedMessage());
      StringWriter sw = new StringWriter();
      savedEx.printStackTrace(new PrintWriter(sw));
      value.put("exceptionStackTrace", sw.toString());
    }
    TelemetryEvent log = logBuilder
        .withName(eventName)
        .withValue(value)
        .withTag("sqlState", sqlState)
        .withTag("errorCode", errorCode)
        .withTag("responseStatusCode", responseStatusCode)
        .build();
    this.report(log);
  }
}
 
Example 19
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void patch(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        String sidpid,
                        Long startdate,
                        Long enddate,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{
    System.out.println("Patch policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling update @ " + resourceLoc);

    PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
    pfpr.setStartDate(startdate);
    if (enddate != null)
        pfpr.setEndDate(enddate);
    pfpr.setVersion(version);
    pfpr.setStatus(status);
    pfpr.setNotes(notes);
    pfpr.setPolicy(policy);

    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(pfpr);

    ContentType mimetype = ContentType.create("application/merge-patch+json");
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch(resourceLoc);
    httpPatch.setEntity(body);
    String requestToHmac = httpPatch.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPatch.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPatch.addHeader("strongkey-content-sha256", contentSHA);
    httpPatch.addHeader("Content-Type", mimetype.getMimeType());
    httpPatch.addHeader("Date", currentDate);
    httpPatch.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpPatch);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during patch fido policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nPatch policy test complete.");
    System.out.println("******************************************");
}
 
Example 20
Source File: RestCreateFidoPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void create(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        Long startdate,
                        Long enddate,
                        String certificateProfileName,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{

    String apiversion = "2.0";

    CreateFidoPolicyRequest cfpr = new CreateFidoPolicyRequest();
    cfpr.setStartDate(startdate);
    if (enddate != null)
        cfpr.setEndDate(enddate);
    cfpr.setCertificateProfileName(certificateProfileName);
    cfpr.setVersion(version);
    cfpr.setStatus(status);
    cfpr.setNotes(notes);
    cfpr.setPolicy(policy);
    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(cfpr);

    ContentType mimetype = ContentType.APPLICATION_JSON;
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.CREATE_POLICY_ENDPOINT;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(resourceLoc);
    httpPost.setEntity(body);
    String requestToHmac = httpPost.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPost.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPost.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPost.addHeader("strongkey-content-sha256", contentSHA);
    httpPost.addHeader("Content-Type", mimetype.getMimeType());
    httpPost.addHeader("Date", currentDate);
    httpPost.addHeader("strongkey-api-version", apiversion);

    //  Make API rest call and get response from the server
    System.out.println("\nCalling create policy @ " + resourceLoc);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                System.out.println(" Response : " + result);
                break;
            case 401:
                System.out.println("Error during create policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during create policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during create policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }
    } finally {
        response.close();
    }

    System.out.println("Result of create policy: " + result);
}