org.apache.http.HttpStatus#SC_CREATED源码实例Demo

下面列出了org.apache.http.HttpStatus#SC_CREATED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: io   文件: AuthBatchTest.java
/**
 * 不正な認証情報を使用してすべてのユーザがwrite可能なコレクションに対して$batchをした場合処理が受付けられること.
 * batchの実行順
 * 1.POST(登録)
 * 2.GET(一覧取得)
 * 3.GET(取得)
 * 4.PUT(更新)
 * 5.DELETE(削除)
 */
@Test
public final void 不正な認証情報を使用してすべてのユーザがwrite可能なコレクションに対して$batchをした場合処理が受付けられること() {
    // 認証トークン取得
    String invalidToken = "invalid token";

    // ACL設定
    String path = String.format("%s/%s/%s", TEST_CELL1, BOX_NAME, COL_NAME);
    DavResourceUtils.setACLPrincipalAll(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK,
            path, "<D:write />", "");

    // READ→OK WRITE→403
    TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
            invalidToken, HttpStatus.SC_ACCEPTED);
    // 期待するレスポンスコード
    int[] expectedCodes = new int[] {HttpStatus.SC_CREATED,
            HttpStatus.SC_FORBIDDEN,
            HttpStatus.SC_FORBIDDEN,
            HttpStatus.SC_NO_CONTENT,
            HttpStatus.SC_NO_CONTENT };
    // レスポンスボディのチェック(ステータス)
    checkBatchResponseBody(res, expectedCodes);
}
 
源代码2 项目: pacbot   文件: PacHttpUtils.java
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error("URL: " + url + " Body: " + requestBody);
			throw new Exception(
					"unable to execute post request to " + url + " because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
源代码3 项目: io   文件: ODataBatchResource.java
/**
 * レスポンスコードの説明を取得する.
 * @return レスポンスコードの説明(例:OK, No Content)
 */
public String getResponseMessage() {
    String message = null;

    switch (this.responseCode) {
    case HttpStatus.SC_NO_CONTENT:
        message = "No Content";
        break;

    case HttpStatus.SC_CREATED:
        message = "Created";
        break;

    case HttpStatus.SC_OK:
        message = "OK";
        break;

    default:
        message = "";
        break;
    }

    return message;
}
 
源代码4 项目: gerrit-code-review-plugin   文件: Checkers.java
public CheckerInfo create(CheckerInput input) throws RestApiException {
  try {
    HttpPost request = new HttpPost(buildRequestUrl());
    String inputString =
        JsonBodyParser.createRequestBody(input, new TypeToken<CheckerInput>() {}.getType());
    request.setEntity(new StringEntity(inputString));
    request.setHeader("Content-type", "application/json");
    try (CloseableHttpResponse response = client.execute(request)) {
      if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
        return JsonBodyParser.parseResponse(
            EntityUtils.toString(response.getEntity()),
            new TypeToken<CheckerInfo>() {}.getType());
      }
      throw new RestApiException(
          String.format("Request returned status %s", response.getStatusLine().getStatusCode()));
    }
  } catch (Exception e) {
    throw new RestApiException("Could not create checker", e);
  }
}
 
源代码5 项目: io   文件: AuthBatchTest.java
/**
 * 不正な認証情報を使用してすべてのユーザがアクセス可能なコレクションに対して$batchをした場合処理が受付けられること.
 * batchの実行順
 * 1.POST(登録)
 * 2.GET(一覧取得)
 * 3.GET(取得)
 * 4.PUT(更新)
 * 5.DELETE(削除)
 */
@Test
public final void 不正な認証情報を使用してすべてのユーザがアクセス可能なコレクションに対して$batchをした場合処理が受付けられること() {

    // 認証トークン取得
    String invalidToken = "invalid token";

    // ACL設定
    String path = String.format("%s/%s/%s", TEST_CELL1, BOX_NAME, COL_NAME);
    DavResourceUtils.setACLPrivilegeAllForAllUser(TEST_CELL1, MASTER_TOKEN, HttpStatus.SC_OK, path, "none");

    // READとWRITE→全てOK
    TResponse res = UserDataUtils.batch(TEST_CELL1, BOX_NAME, COL_NAME, BOUNDARY, TEST_BODY,
            invalidToken, HttpStatus.SC_ACCEPTED);
    // 期待するレスポンスコード
    int[] expectedCodes = new int[] {HttpStatus.SC_CREATED,
            HttpStatus.SC_OK,
            HttpStatus.SC_OK,
            HttpStatus.SC_NO_CONTENT,
            HttpStatus.SC_NO_CONTENT };
    // レスポンスボディのチェック(ステータス)
    checkBatchResponseBody(res, expectedCodes);

}
 
源代码6 项目: nifi   文件: LivySessionController.java
private JSONObject readJSONObjectFromUrlPOST(String urlString, Map<String, String> headers, String payload) throws IOException, JSONException {
    HttpClient httpClient = openConnection();

    HttpPost request = new HttpPost(urlString);
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        request.addHeader(entry.getKey(), entry.getValue());
    }
    HttpEntity httpEntity = new StringEntity(payload);
    request.setEntity(httpEntity);
    HttpResponse response = httpClient.execute(request);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode() + " : " + response.getStatusLine().getReasonPhrase());
    }

    InputStream content = response.getEntity().getContent();
    return readAllIntoJSONObject(content);
}
 
源代码7 项目: zstack   文件: InventoryIndexManagerImpl.java
private void deleteIndex(String indexName) throws URISyntaxException, ClientProtocolException, IOException {
    if (indexName == null) {
        indexName = "_all";
    }

    final String name = indexName.toLowerCase();
    URI uri = makeURI(elasticSearchBaseUrl, name);
    final HttpDelete del = new HttpDelete(uri);
    ResponseHandler<Void> rspHandler = new ResponseHandler<Void>() {
        @Override
        public Void handleResponse(HttpResponse rsp) throws ClientProtocolException, IOException {
            if (rsp.getStatusLine().getStatusCode() != HttpStatus.SC_OK && rsp.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
                logger.warn(String.format("Failed to delete index[%s] , because: \nstatus line: %s\nbody: %s", del.getURI().toASCIIString(),
                        rsp.getStatusLine(), EntityUtils.toString(rsp.getEntity())));
            } else {
                logger.trace(String.format("Successfully delete index[%s]", name));
            }
            return null;
        }
    };
    httpClient.execute(del, rspHandler);
}
 
源代码8 项目: vividus   文件: HttpResponseTests.java
@ParameterizedTest
@ValueSource(ints = { HttpStatus.SC_OK, HttpStatus.SC_CREATED, HttpStatus.SC_BAD_REQUEST })
void testVerifyOneStatusCodeInRangeSuccess(Integer code)
{
    httpResponse.setStatusCode(code);
    HttpResponse actual = httpResponse.verifyStatusCodeInRange(HttpStatus.SC_OK, HttpStatus.SC_BAD_REQUEST);
    assertThat(actual, Matchers.equalTo(httpResponse));
}
 
源代码9 项目: carbon-apimgt   文件: HttpRequestUtil.java
private static String handleResponse(HttpResponse response, String methodName, boolean retry, int executionCount,
                                     int retryCount, String uri) throws OnPremiseGatewayException {
    switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK:
            return handleSuccessCase(response);

        case HttpStatus.SC_CREATED:
            return handleSuccessCase(response);

        case HttpStatus.SC_ACCEPTED:
            return handleSuccessCase(response);

        case HttpStatus.SC_NOT_FOUND:
            throw new OnPremiseGatewayException(NOT_FOUND_ERROR_MSG);

        case HttpStatus.SC_UNAUTHORIZED:
            throw new OnPremiseGatewayException(AUTH_ERROR_MSG);

        case HttpStatus.SC_FORBIDDEN:
            throw new OnPremiseGatewayException(AUTH_FORBIDDEN_ERROR_MSG);

        default:
            if (retry) {
                handleDefaultCaseWithRetry(executionCount, response, retryCount, methodName, uri);
            } else {
                throw new OnPremiseGatewayException(
                        methodName + " request failed for URI: " + uri + " with HTTP error code : " + response);
            }
    }
    return OnPremiseGatewayConstants.EMPTY_STRING;
}
 
源代码10 项目: keywhiz   文件: ClientsResource.java
/**
 * Create Client
 *
 * @param user                the admin user creating this client
 * @param createClientRequest the JSON client request used to formulate the Client
 * @return 200 if the client is created successfully, 409 if it already exists
 * <p>
 * description Creates a Client with the name from a valid client request. Used by Keywhiz CLI and
 * the web ui.
 * <p>
 * responseMessage 200 Successfully created Client
 * <p>
 * responseMessage 409 Client with given name already exists
 */
@Timed @ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createClient(@Auth User user,
    @Valid CreateClientRequestV2 createClientRequest) {

  logger.info("User '{}' creating client '{}'.", user, createClientRequest.name());

  long clientId;
  try {
    clientId = clientDAO.createClient(createClientRequest.name(), user.getName(),
        createClientRequest.description(), new URI(createClientRequest.spiffeId()));
  } catch (DataAccessException | URISyntaxException e) {
    logger.warn("Cannot create client {}: {}", createClientRequest.name(), e);
    throw new ConflictException("Conflict creating client.");
  }

  URI uri = UriBuilder.fromResource(ClientsResource.class).path("{clientId}").build(clientId);
  Response response = Response
      .created(uri)
      .entity(clientDetailResponseFromId(clientId))
      .build();
  if (response.getStatus() == HttpStatus.SC_CREATED) {
    auditLog.recordEvent(new Event(Instant.now(), EventTag.CLIENT_CREATE, user.getName(),
        createClientRequest.name()));
  }
  return response;
}
 
源代码11 项目: pacbot   文件: HttpUtil.java
/**
 * 
 * @param rest
 *            URL for POST method
 * @return String
 * @throws Exception
 */
public static String doHttpPost(final String url, final String requestBody) throws Exception {
	try {

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
		StringEntity jsonEntity = new StringEntity(requestBody);
		httppost.setEntity(jsonEntity);
		HttpResponse httpresponse = client.execute(httppost);
		int statusCode = httpresponse.getStatusLine().getStatusCode();
		if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
			return EntityUtils.toString(httpresponse.getEntity());
		} else {
			LOGGER.error(requestBody);
			throw new Exception(
					"unable to execute post request because " + httpresponse.getStatusLine().getReasonPhrase());
		}
	} catch (ParseException parseException) {
		parseException.printStackTrace();
		LOGGER.error("error closing issue" + parseException);
		throw parseException;
	} catch (Exception exception) {
		exception.printStackTrace();
		LOGGER.error("error closing issue" + exception.getMessage());
		throw exception;
	}
}
 
源代码12 项目: mycore   文件: MCRDataciteClient.java
public void mintDOI(final MCRDigitalObjectIdentifier doi, URI url) throws MCRPersistentIdentifierException {
    URI requestURI = getRequestURI("/doi");

    HttpPost post = new HttpPost(requestURI);

    try (CloseableHttpClient httpClient = getHttpClient()) {
        post.setEntity(new StringEntity(
            String.format(Locale.ENGLISH, DOI_REGISTER_REQUEST_TEMPLATE, doi.asString(), url.toString())));
        CloseableHttpResponse response = httpClient.execute(post);
        StatusLine statusLine = response.getStatusLine();
        switch (statusLine.getStatusCode()) {
            case HttpStatus.SC_CREATED:
                return;
            case HttpStatus.SC_BAD_REQUEST:
                throw new MCRDatacenterException(
                    getStatusString(response)); // invalid PREFIX or wrong format, but format is hard defined!
            case HttpStatus.SC_UNAUTHORIZED:
                throw new MCRDatacenterAuthenticationException();
            case HttpStatus.SC_PRECONDITION_FAILED:
                throw new MCRDatacenterException(String.format(Locale.ENGLISH,
                    "Metadata must be uploaded first! (%s)", getStatusString(response)));
            default:
                throw new MCRDatacenterException(String.format(Locale.ENGLISH,
                    "Datacenter-Error while minting doi: \"%s\" : %s", doi.asString(), getStatusString(response)));
        }
    } catch (IOException e) {
        throw new MCRDatacenterException("Unknown error while mint new doi", e);
    }
}
 
源代码13 项目: joynr   文件: BounceProxySystemTest.java
private String createChannel(String channelId, String trackingId) throws Exception {

        final String url = bounceProxyUrl + "channels/?ccid=" + channelId;
        logger.info("Creating channel at {}..." + url);

        HttpPost postCreateChannel = new HttpPost(url.trim());
        postCreateChannel.addHeader("X-Atmosphere-tracking-id", trackingId);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(postCreateChannel);
            logger.info("Returned {}", response.getStatusLine());

            int statusCode = response.getStatusLine().getStatusCode();
            switch (statusCode) {
            case HttpStatus.SC_CREATED:
            case HttpStatus.SC_OK:
                return response.getFirstHeader("Location").getValue();

            default:
                logger.error("Failed to create channel {}", channelId);
                printBody(response.getEntity());
                throw new RuntimeException("Could not proceed with messaging as channel could not be created");
            }
        } finally {
            if (response != null)
                response.close();
        }

    }
 
@Override
public JsonNode parseResponse(HttpResponse httpResponse) throws AppException {
	Transaction context = Transaction.getInstance();
	int statusCode = httpResponse.getStatusLine().getStatusCode();
	try {
		if(context.get(MODE).equals(MODE_CREATE_API_ACCESS) && statusCode == HttpStatus.SC_CREATED) {
			actualState.getApplications().add((ClientApplication)context.get("appName"));
			LOG.debug("Successfully created API-Access for application: '"+context.get("appName")+"'");
		} else if(context.get(MODE).equals(MODE_REMOVE_API_ACCESS)  && statusCode == HttpStatus.SC_NO_CONTENT) {
			actualState.getApplications().remove((ClientApplication)context.get("appName"));
			LOG.debug("Successfully removed API-Access from application: '"+context.get("appName")+"'");
		} else {
			LOG.error("Received status code: " + httpResponse.getStatusLine().getStatusCode());
			try {
				LOG.error("Received response: " + EntityUtils.toString(httpResponse.getEntity()));
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
			throw new AppException("Failure creating/deleting API-Access to/from application: '"+context.get("appName")+"'. Mode: '"+context.get(MODE)+"'", 
					ErrorCode.API_MANAGER_COMMUNICATION);
		}
	} finally {
		try {
			((CloseableHttpResponse)httpResponse).close();
		} catch (Exception ignore) { }
	}
	return null;
}
 
private boolean createdSuccessfully(Response connectorResponse) {
    return connectorResponse.getStatus() == HttpStatus.SC_CREATED || connectorResponse.getStatus() == HttpStatus.SC_OK;
}
 
源代码16 项目: io   文件: UserDataBatchWithNPTest.java
/**
 * $batchで既存のユーザデータからNavPro経由で同じ__idのユーザデータが登録できないこと.
 */
@Test
@SuppressWarnings("unchecked")
public final void $batchで既存のユーザデータからNavPro経由で同じ__idのユーザデータが登録できないこと() {
    try {
        JSONObject srcBody = new JSONObject();
        srcBody.put("__id", "srcKey");
        srcBody.put("Name", "key0001");
        super.createUserData(srcBody, HttpStatus.SC_CREATED, cellName, boxName, colName, "Sales");
        String path = "Sales('srcKey')/_Product";
        String body = START_BOUNDARY
                + retrievePostBody(path, "id0001")
                + START_BOUNDARY
                + retrievePostBody(path, "id0001")
                + END_BOUNDARY;
        TResponse response = Http.request("box/odatacol/batch.txt")
                .with("cell", cellName)
                .with("box", boxName)
                .with("collection", colName)
                .with("boundary", BOUNDARY)
                .with("token", DcCoreConfig.getMasterToken())
                .with("body", body)
                .returns()
                .debug()
                .statusCode(HttpStatus.SC_ACCEPTED);

        // レスポンスボディのチェック
        String expectedBody = START_BOUNDARY
                + retrievePostResBodyToSetODataCol("Product", "id0001", true)
                + START_BOUNDARY
                + retrieveChangeSetResErrorBody(HttpStatus.SC_CONFLICT) + END_BOUNDARY;
        checkBatchResponseBody(response, expectedBody);

        // リンク情報のチェック
        TResponse resList = UserDataUtils.listLink(cellName, boxName, colName, "Sales", "srcKey",
                "Product");
        ArrayList<String> expectedUriList = new ArrayList<String>();
        expectedUriList.add(UrlUtils.userdata(cellName, boxName, colName, "Product", "id0001"));
        ODataCommon.checkLinResponseBody(resList.bodyAsJson(), expectedUriList);

    } finally {
        ResourceUtils.deleteUserDataLinks("srcKey", "id0001", "Product", cellName, boxName, colName, "Sales", -1);
        ResourceUtils.deleteUserDataLinks("srcKey", "id0002", "Product", cellName, boxName, colName, "Sales", -1);
        deleteUserData(cellName, boxName, colName, "Product", "id0001", DcCoreConfig.getMasterToken(), -1);
        deleteUserData(cellName, boxName, colName, "Product", "id0002", DcCoreConfig.getMasterToken(), -1);
        deleteUserData(cellName, boxName, colName, "Sales", "srcKey", DcCoreConfig.getMasterToken(), -1);
    }
}
 
源代码17 项目: keywhiz   文件: SecretsResource.java
/**
 * Create Secret
 *
 * @param user    the admin user performing this operation
 * @param request the JSON client request used to formulate the Secret
 * @return 201 on success, 400 if a secret with the given name already exists
 * <p>
 * description Creates a Secret with the name from a valid secret request. Used by Keywhiz CLI and
 * the web ui.
 * <p>
 * responseMessage 201 Successfully created Secret
 * <p>
 * responseMessage 400 Secret with given name already exists
 */
@Timed @ExceptionMetered
@POST
@Consumes(APPLICATION_JSON)
public Response createSecret(@Auth User user, @Valid CreateSecretRequestV2 request) {

  logger.info("User '{}' creating secret '{}'.", user, request.name());

  Secret secret;
  try {
    SecretController.SecretBuilder builder =
        secretController.builder(request.name(), request.content(), user.getName(),
            request.expiry());

    if (request.description() != null) {
      builder.withDescription(request.description());
    }

    if (request.metadata() != null) {
      builder.withMetadata(request.metadata());
    }

    secret = builder.create();
  } catch (DataAccessException e) {
    logger.info(format("Cannot create secret %s", request.name()), e);
    throw new ConflictException(format("Cannot create secret %s.", request.name()));
  }

  URI uri =
      UriBuilder.fromResource(SecretsResource.class).path("{secretId}").build(secret.getId());
  Response response = Response
      .created(uri)
      .entity(secretDetailResponseFromId(secret.getId()))
      .build();

  if (response.getStatus() == HttpStatus.SC_CREATED) {
    Map<String, String> extraInfo = new HashMap<>();
    if (request.description() != null) {
      extraInfo.put("description", request.description());
    }
    if (request.metadata() != null) {
      extraInfo.put("metadata", request.metadata().toString());
    }
    extraInfo.put("expiry", Long.toString(request.expiry()));
    auditLog.recordEvent(
        new Event(Instant.now(), EventTag.SECRET_CREATE, user.getName(), request.name(),
            extraInfo));
  }
  // TODO (jessep): Should we also log failures?

  return response;
}
 
源代码18 项目: docker-java-api   文件: RtContainerTestCase.java
/**
 * Can create Exec.
 * @throws Exception If something goes wrong.
 */
@Test
public void createTest() throws Exception {
    final JsonObject json = Json.createObjectBuilder()
        .add("Cmd", Json.createArrayBuilder().add("date").build())
        .add("Tty", "true")
        .add("AttachStdin", "true")
        .build();

    RtContainer rtContainer = new RtContainer(
        Json.createObjectBuilder().add("Id", "123").build(),
        new AssertRequest(
            new Response(
                HttpStatus.SC_CREATED,
                Json.createObjectBuilder()
                    .add("Id", "01e1564097")
                    .build().toString()
            ),
            new Condition(
                "Method should be a POST",
                req -> req.getRequestLine().getMethod().equals("POST")
            ),
            new Condition(
                "Resource path must be /123/exec",
                req -> req.getRequestLine().getUri().endsWith("/123/exec")
            )
        ),
        URI.create("http://localhost:80/1.30/containers/123"),
        Mockito.mock(Docker.class)
    );
    when(rtContainer.docker().execs()).thenReturn(
        new RtExecs(
            new AssertRequest(
                new Response(
                    HttpStatus.SC_OK,
                    "{\"Id\": \"exec123\"}"
                ),
                new Condition(
                    "must send a GET request",
                    req -> "GET".equals(req.getRequestLine().getMethod())
                ),
                new Condition(
                    "resource URL should end with '/exec123/json'",
                    req -> req.getRequestLine()
                        .getUri().endsWith("/exec123/json")
                )
            ),
            URI.create("http://localhost/exec"),
            Mockito.mock(Docker.class)
        )
    );
    rtContainer.exec(json);
}
 
源代码19 项目: blueflood   文件: ElasticsearchRestHelper.java
public void index(final String urlFormat, final String bulkString) throws IOException {
    String tempUrl = String.format(urlFormat, getNextBaseUrl());
    HttpEntity entity = new NStringEntity(bulkString, ContentType.APPLICATION_JSON);
    int statusCode = 0;

    /*
    Here I am using Queue to keep a round-robin selection of next base url. If current base URL fails for
    whatever reason (with response == null), then in catch block, I am enqueueing the next base URL so that
    in next iteration call picks up the new URL. If URL works, queue will be empty and loop will break out.
    */
    Queue<String> callQ = new LinkedList<>();
    callQ.add(tempUrl);
    int callCount = 0;
    while(!callQ.isEmpty() && callCount < MAX_CALL_COUNT) {
        callCount++;
        String url = callQ.remove();
        logger.debug("Using url [{}]", url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeaders(getHeaders());
        httpPost.setEntity(entity);

        CloseableHttpResponse response = null;

        try {
            logger.debug("ElasticsearchRestHelper.index Thread name in use: [{}]", Thread.currentThread().getName());
            response = closeableHttpClient.execute(httpPost);

            statusCode = response.getStatusLine().getStatusCode();
            String str = EntityUtils.toString(response.getEntity());
            EntityUtils.consume(response.getEntity());

            if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED) {
                logger.error("index method failed with status code: {} and error: {}", statusCode, str);
            }
        }
        catch (Exception e) {
            if(response == null){
                logger.error("index method failed with message: {}", e.getMessage());
                url = String.format(urlFormat, getNextBaseUrl());
                callQ.add(url);
            }
            else {
                logger.error("index method failed with status code: {} and exception message: {}",
                        statusCode, e.getMessage());
            }
        } finally {
            if(response != null) {
                response.close();
            }
        }
    }

    if(statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED)
        throw new IOException("Elasticsearch indexing failed with status code: [" + statusCode + "]");
}
 
/**
 * Method to send the revoked token to the persistent storage
 *
 * @param revokedToken token to be revoked
 * @param properties persistent notifier properties read from the config
 */
@Override
public void sendMessageToPersistentStorage(String revokedToken, Properties properties) {
    //Variables related to Persistent Notifier
    String DEFAULT_PERSISTENT_NOTIFIER_HOSTNAME = "https://localhost:2379/v2/keys/jti/";
    String persistentNotifierHostname = properties
            .getProperty("hostname", DEFAULT_PERSISTENT_NOTIFIER_HOSTNAME);
    String persistentNotifierTTL = properties.getProperty("ttl", DEFAULT_TTL);
    String DEFAULT_PERSISTENT_NOTIFIER_USERNAME = "root";
    String persistentNotifierUsername = properties
            .getProperty("username", DEFAULT_PERSISTENT_NOTIFIER_USERNAME);
    String DEFAULT_PERSISTENT_NOTIFIER_PASSWORD = "root";
    String persistentNotifierPassword = properties
            .getProperty("password", DEFAULT_PERSISTENT_NOTIFIER_PASSWORD);
    String etcdEndpoint = persistentNotifierHostname + revokedToken;
    URL etcdEndpointURL = new URL(etcdEndpoint);
    String etcdEndpointProtocol = etcdEndpointURL.getProtocol();
    int etcdEndpointPort = etcdEndpointURL.getPort();
    HttpClient etcdEPClient = APIUtil.getHttpClient(etcdEndpointPort, etcdEndpointProtocol);
    HttpPut httpETCDPut = new HttpPut(etcdEndpoint);
    byte[] encodedAuth = Base64.encodeBase64((persistentNotifierUsername + ":" + persistentNotifierPassword).
            getBytes(StandardCharsets.UTF_8));
    String authHeader = "Basic " + new String(encodedAuth, StandardCharsets.UTF_8);
    httpETCDPut.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
    List<NameValuePair> etcdParams = new ArrayList<>(2);
    etcdParams.add(new BasicNameValuePair("value", "true"));
    etcdParams.add(new BasicNameValuePair("ttl", persistentNotifierTTL));

    //Send the revoked token to the persistent storage Server
    httpETCDPut.setEntity(new UrlEncodedFormEntity(etcdParams, StandardCharsets.UTF_8));
    HttpResponse etcdResponse;
    try {
        etcdResponse = etcdEPClient.execute(httpETCDPut);
        if (etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || etcdResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            if (log.isDebugEnabled()) {
                log.debug("Successfully submitted the request for revoked token. HTTP status :" + etcdResponse
                        .getStatusLine().getStatusCode());
            }
        } else {
            log.error("Sending revoked token to persistent storage failed. HTTP error code : " + etcdResponse
                    .getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Error while sending revoked token to the persistent storage :", e);
    }
}