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

The following examples show how to use org.apache.hc.core5.http.HttpStatus. These examples are extracted from open source projects. 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 Project: testgrid   Source File: JenkinsPipelineManager.java    License: 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 Project: testgrid   Source File: InfrastructureAdderService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This has the implementation of the REST API for fetching all the infrastructure parameters.
 *
 * @return A list of infrastructure parameters.
 */
@GET
public Response getInfrastructureParameters() {
    try {
        InfrastructureParameterUOW infrastructureParameterUOW = new InfrastructureParameterUOW();
        List<InfrastructureParameter> infrastructureParameters = infrastructureParameterUOW
                .getInfrastructureParameters();

        return Response.status(Response.Status.CREATED).entity(infrastructureParameters).build();
    } catch (TestGridDAOException e) {
        String msg =
                "Error occurred while loading infrastructure parameters.";
        logger.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().
                        setMessage(msg).
                        setCode(HttpStatus.SC_SERVER_ERROR).build()).build();
    }
}
 
Example 3
Source Project: testgrid   Source File: InfrastructureAdderService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This has the implementation of the REST API for adding a new infrastructure combination.
 *
 * @param infrastructureParameter The {@link InfrastructureParameter} with name, type, properties, and testgrid
 *                                readiness.
 * @return the persisted InfrastructureParameter that includes additional details such as the id.
 */
@POST
public Response addInfrastructureParameter(InfrastructureParameter infrastructureParameter) {
    try {
        InfrastructureParameterUOW infrastructureParameterUOW = new InfrastructureParameterUOW();
        infrastructureParameter = infrastructureParameterUOW
                .persistInfrastructureParameter(infrastructureParameter);
        logger.info("Added new infrastructure Parameter: " + infrastructureParameter);

        return Response.status(Response.Status.CREATED).entity(infrastructureParameter).build();
    } catch (TestGridDAOException e) {
        String msg =
                "Error occurred while adding new infrastructure parameter : '" + infrastructureParameter + "'.";
        logger.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().
                        setMessage(msg).
                        setCode(HttpStatus.SC_SERVER_ERROR).build()).build();
    }
}
 
Example 4
Source Project: testgrid   Source File: TestPlanService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This has the implementation of the REST API for creating a new Test plan.
 *
 * @param testPlanRequest {@link TestPlanRequest} that includes the repository and other necessary detials
 *                        to create new test plan.
 * @return A list of available TestPlans.
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createTestPlan(TestPlanRequest testPlanRequest) {
    try {
        String configXml = jenkinsJobConfigurationProvider.getConfiguration(testPlanRequest);
        String jobSpecificUrl = jenkinsPipelineManager.
                createNewPipelineJob(configXml, testPlanRequest.getTestPlanName());
        persistAsYamlFile(testPlanRequest);
        return Response.status(Response.Status.CREATED).
                entity(jobSpecificUrl).type(MediaType.TEXT_PLAIN).build();
    } catch (TestGridException | IOException e) {
        String msg = "Error occurred while creating new test plan named : '" +
                     testPlanRequest.getTestPlanName() + "'.";
        logger.error(msg, e);
        return Response.serverError().entity(
                new ErrorResponse.ErrorResponseBuilder().
                        setMessage(msg).
                        setCode(HttpStatus.SC_SERVER_ERROR).
                        setDescription(e.getMessage()).build()).build();
    }
}
 
Example 5
Source Project: commons-vfs   Source File: Http5FileObject.java    License: 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 6
Source Project: n2o-framework   Source File: DemoIntegrationAT.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Проверка отдачи статики
 */
@Test
@Order(1)
public void checkStaticContent() throws IOException {
    HttpUriRequest request = new HttpGet("http://localhost:" + port + "/index.html");
    HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request);
    assertThat(httpResponse.getCode(), equalTo(HttpStatus.SC_OK));
}
 
Example 7
Source Project: mts   Source File: HttpLoaderServer.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void sendResponse( ClassicHttpResponse response,HttpContext context, HttpRequest request)throws HttpException, IOException
{

    response.setCode(HttpStatus.SC_OK);
    File file = new File("D:/XMLloader/testPileHttp/test/fileTestHttp.txt");
    //FileEntity body = new FileEntity(file, "text/html");
    HttpEntity body = new StringEntity("");
    response.setEntity(body);
}
 
Example 8
Source Project: drftpd   Source File: HttpUtils.java    License: 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 9
Source Project: drftpd   Source File: HttpUtils.java    License: 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 10
Source Project: wpcleaner   Source File: Hc5HttpServer.java    License: 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 11
Source Project: wpcleaner   Source File: Hc5HttpServer.java    License: 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 12
Source Project: java   Source File: StructurizrClient.java    License: 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 13
Source Project: commons-vfs   Source File: Http5FileObject.java    License: 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 14
Source Project: java   Source File: StructurizrClient.java    License: 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);
    }
}
 
Example 15
Source Project: docker-java   Source File: HijackingHttpRequestExecutor.java    License: Apache License 2.0 4 votes vote down vote up
private ClassicHttpResponse executeHijacked(
    ClassicHttpRequest request,
    HttpClientConnection conn,
    HttpContext context,
    InputStream hijackedInput
) throws HttpException, IOException {
    try {
        context.setAttribute(HttpCoreContext.SSL_SESSION, conn.getSSLSession());
        context.setAttribute(HttpCoreContext.CONNECTION_ENDPOINT, conn.getEndpointDetails());
        final ProtocolVersion transportVersion = request.getVersion();
        if (transportVersion != null) {
            context.setProtocolVersion(transportVersion);
        }

        conn.sendRequestHeader(request);
        conn.sendRequestEntity(request);
        conn.flush();

        ClassicHttpResponse response = conn.receiveResponseHeader();
        if (response.getCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
            conn.terminateRequest(request);
            throw new ProtocolException("Expected 101 Switching Protocols, got: " + new StatusLine(response));
        }

        Thread thread = new Thread(() -> {
            try {
                BasicClassicHttpRequest fakeRequest = new BasicClassicHttpRequest("POST", "/");
                fakeRequest.setHeader(HttpHeaders.CONTENT_LENGTH, Long.MAX_VALUE);
                fakeRequest.setEntity(new HijackedEntity(hijackedInput));
                conn.sendRequestEntity(fakeRequest);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        thread.setName("docker-java-httpclient5-hijacking-stream-" + System.identityHashCode(request));
        thread.setDaemon(true);
        thread.start();

        // 101 -> 200
        response.setCode(200);
        conn.receiveResponseEntity(response);
        return response;

    } catch (final HttpException | IOException | RuntimeException ex) {
        Closer.closeQuietly(conn);
        throw ex;
    }
}