Java Code Examples for org.apache.hc.core5.http.HttpStatus#SC_OK

The following examples show how to use org.apache.hc.core5.http.HttpStatus#SC_OK . 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: JenkinsPipelineManager.java    From testgrid with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new pipeline job in Jenkins server by calling its REST API.
 * @param configXml configuration file for the new job.
 * @param jobName name for the new job.
 * @return URL to check the status of the new job.
 */
public String createNewPipelineJob(String configXml, String jobName) throws TestGridException, IOException {
    Response response = Request
            .Post(ConfigurationContext.getProperty(
                    ConfigurationContext.ConfigurationProperties.JENKINS_HOST) + "/createItem?name=" + jobName)
            .addHeader(HttpHeaders.USER_AGENT, USER_AGENT)
            .addHeader(HttpHeaders.AUTHORIZATION, "Basic " +
                    ConfigurationContext.getProperty(
                            ConfigurationContext.ConfigurationProperties.JENKINS_USER_AUTH_KEY))
            .addHeader(Constants.JENKINS_CRUMB_HEADER_NAME, getCrumb())
            .addHeader(HttpHeaders.CONTENT_TYPE, "application/xml")
            .bodyString(configXml, ContentType.APPLICATION_XML)
            .execute();
    if (response.returnResponse().getCode() == HttpStatus.SC_OK) {
        return buildJobSpecificUrl(jobName);
    } else {
        logger.error("Jenkins server error for creating job " + jobName + " " +
                response.returnResponse().getCode());
        throw new TestGridException("Can not create new job in Jenkins. Received " +
                response.returnResponse().getCode() + " " +
                response.returnContent().asString() + ".");
    }
}
 
Example 2
Source File: Http5FileObject.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Override
protected InputStream doGetInputStream(final int bufferSize) throws Exception {
    final HttpGet getRequest = new HttpGet(getInternalURI());
    final ClassicHttpResponse httpResponse = executeHttpUriRequest(getRequest);
    final int status = httpResponse.getCode();

    if (status == HttpStatus.SC_NOT_FOUND) {
        throw new FileNotFoundException(getName());
    }

    if (status != HttpStatus.SC_OK) {
        throw new FileSystemException("vfs.provider.http/get.error", getName(), Integer.valueOf(status));
    }

    return new MonitoredHttpResponseContentInputStream(httpResponse, bufferSize);
}
 
Example 3
Source File: HttpUtils.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom()
            .setResponseTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
            .setCookieSpec(StandardCookieSpec.IGNORE)
            .build();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}
 
Example 4
Source File: HttpUtils.java    From drftpd with GNU General Public License v2.0 5 votes vote down vote up
public static String retrieveHttpAsString(String url) throws HttpException, IOException {
    RequestConfig requestConfig = RequestConfig.custom()
            .setResponseTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectTimeout(5000, TimeUnit.MILLISECONDS)
            .setConnectionRequestTimeout(5000, TimeUnit.MILLISECONDS)
            .setCookieSpec(StandardCookieSpec.IGNORE)
            .build();
    CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .setUserAgent(_userAgent)
            .build();
    HttpGet httpGet = new HttpGet(url);
    httpGet.setConfig(requestConfig);
    CloseableHttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
        final int statusCode = response.getCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new HttpException("Error " + statusCode + " for URL " + url);
        }
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
        return data;
    } catch (IOException e) {
        throw new IOException("Error for URL " + url, e);
    } finally {
        if (response != null) {
            response.close();
        }
        httpclient.close();
    }
}
 
Example 5
Source File: Hc5HttpServer.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Send a POST request to the Tool Server.
 * 
 * @param path Path on the tool server.
 * @param properties Request properties.
 * @param manager Response manager.
 * @throws APIException Exception thrown by the API.
 */
@Override
public void sendPost(
    String              path,
    Map<String, String> properties,
    ResponseManager     manager) throws APIException {

  int count = 0;
  int statusCode = HttpStatus.SC_SEE_OTHER;
  String url = baseUrl + path;
  while (count < MAX_ATTEMPTS) {

    // Wait if it's not the first attempt
    count++;
    if (count > 1) {
      waitBeforeRetrying(count);
    }

    // Perform the request
    try {
      final HttpUriRequest method = Hc5HttpUtils.createMethod(url,  properties, false);
      final Hc5HttpResponse response = httpClient.execute(method, new Hc5HttpResponseHandler());
      statusCode = response.status;
      if (statusCode == HttpStatus.SC_OK) {
        if (manager != null) {
          manager.manageResponse(response.inputStream);
        }
        return;
      }
    } catch (IOException e) {
      log.error("IOException (" + url + "): " + e.getMessage());
    }
  }
  throw new APIException("POST returned " + statusCode);
}
 
Example 6
Source File: Hc5HttpServer.java    From wpcleaner with Apache License 2.0 5 votes vote down vote up
/**
 * Send a GET request to the Tool Server.
 * 
 * @param path Path on the tool server.
 * @param manager Response manager.
 * @throws APIException Exception thrown by the API.
 */
@Override
public void sendGet(
    String          path,
    ResponseManager manager) throws APIException {

  int count = 0;
  int statusCode = HttpStatus.SC_SEE_OTHER;
  String url = baseUrl + path;
  while (count < MAX_ATTEMPTS) {

    // Wait if it's not the first attempt
    count++;
    if (count > 1) {
      waitBeforeRetrying(count);
    }

    // Perform the request
    try {
      final HttpUriRequest method = Hc5HttpUtils.createMethod(url, null, true);
      final Hc5HttpResponse response = httpClient.execute(method, new Hc5HttpResponseHandler());
      statusCode = response.status;
      if (statusCode == HttpStatus.SC_OK) {
        if (manager != null) {
          manager.manageResponse(response.inputStream);
        }
        return;
      }
    } catch (IOException e) {
      log.error("IOException (" + url + "): " + e.getMessage());
    }
  }
  throw new APIException("GET returned " + statusCode);
}
 
Example 7
Source File: StructurizrClient.java    From java with Apache License 2.0 5 votes vote down vote up
private boolean manageLockForWorkspace(long workspaceId, boolean lock) throws StructurizrClientException {
    if (workspaceId <= 0) {
        throw new IllegalArgumentException("The workspace ID must be a positive integer.");
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        HttpUriRequestBase httpRequest;

        if (lock) {
            log.info("Locking workspace with ID " + workspaceId);
            httpRequest = new HttpPut(url + WORKSPACE_PATH + workspaceId + "/lock?user=" + getUser() + "&agent=" + agent);
        } else {
            log.info("Unlocking workspace with ID " + workspaceId);
            httpRequest = new HttpDelete(url + WORKSPACE_PATH + workspaceId + "/lock?user=" + getUser() + "&agent=" + agent);
        }

        addHeaders(httpRequest, "", "");
        debugRequest(httpRequest, null);

        try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
            debugResponse(response);

            String responseText = EntityUtils.toString(response.getEntity());
            ApiResponse apiResponse = ApiResponse.parse(responseText);
            log.info(responseText);

            if (response.getCode() == HttpStatus.SC_OK) {
                return apiResponse.isSuccess();
            } else {
                throw new StructurizrClientException(apiResponse.getMessage());
            }
        }
    } catch (Exception e) {
        log.error(e);
        throw new StructurizrClientException(e);
    }
}
 
Example 8
Source File: Http5FileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@Override
protected FileType doGetType() throws Exception {
    lastHeadResponse = executeHttpUriRequest(new HttpHead(getInternalURI()));
    final int status = lastHeadResponse.getCode();

    if (status == HttpStatus.SC_OK
            || status == HttpStatus.SC_METHOD_NOT_ALLOWED /* method is not allowed, but resource exist */) {
        return FileType.FILE;
    } else if (status == HttpStatus.SC_NOT_FOUND || status == HttpStatus.SC_GONE) {
        return FileType.IMAGINARY;
    } else {
        throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
    }
}
 
Example 9
Source File: StructurizrClient.java    From java with Apache License 2.0 4 votes vote down vote up
/**
 * Gets the workspace with the given ID.
 *
 * @param workspaceId the workspace ID
 * @return a Workspace instance
 * @throws StructurizrClientException   if there are problems related to the network, authorization, JSON deserialization, etc
 */
public Workspace getWorkspace(long workspaceId) throws StructurizrClientException {
    if (workspaceId <= 0) {
        throw new IllegalArgumentException("The workspace ID must be a positive integer.");
    }

    try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
        log.info("Getting workspace with ID " + workspaceId);
        HttpGet httpGet = new HttpGet(url + WORKSPACE_PATH + workspaceId);
        addHeaders(httpGet, "", "");
        debugRequest(httpGet, null);

        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            debugResponse(response);

            String json = EntityUtils.toString(response.getEntity());
            if (response.getCode() == HttpStatus.SC_OK) {
                archiveWorkspace(workspaceId, json);

                if (encryptionStrategy == null) {
                    return new JsonReader().read(new StringReader(json));
                } else {
                    EncryptedWorkspace encryptedWorkspace = new EncryptedJsonReader().read(new StringReader(json));

                    if (encryptedWorkspace.getEncryptionStrategy() != null) {
                        encryptedWorkspace.getEncryptionStrategy().setPassphrase(encryptionStrategy.getPassphrase());
                        return encryptedWorkspace.getWorkspace();
                    } else {
                        // this workspace isn't encrypted, even though the client has an encryption strategy set
                        return new JsonReader().read(new StringReader(json));
                    }
                }
            } else {
                ApiResponse apiResponse = ApiResponse.parse(json);
                throw new StructurizrClientException(apiResponse.getMessage());
            }
        }
    } catch (Exception e) {
        log.error(e);
        throw new StructurizrClientException(e);
    }
}