Example usage for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND

List of usage examples for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND.

Prototype

int SC_NOT_FOUND

To view the source code for org.apache.commons.httpclient HttpStatus SC_NOT_FOUND.

Click Source Link

Document

<tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.sonatype.nexus.integrationtests.nexus176.Nexus176DeployToInvalidRepoIT.java

@Test
public void deploySnapshotWithPomUsingRest() throws Exception {

    Gav gav = new Gav(this.getTestId(), "uploadWithGav", "1.0.0-SNAPSHOT", null, "xml", 0, new Date().getTime(),
            "Simple Test Artifact", false, null, false, null);

    // file to deploy
    File fileToDeploy = this.getTestFile(gav.getArtifactId() + "." + gav.getExtension());

    File pomFile = this.getTestFile("pom.xml");

    // the Restlet Client does not support multipart forms: http://restlet.tigris.org/issues/show_bug.cgi?id=71

    // url to upload to
    String uploadURL = this.getBaseNexusUrl() + "service/local/artifact/maven/content";

    int status = getDeployUtils().deployUsingPomWithRest(uploadURL, TEST_RELEASE_REPO, fileToDeploy, pomFile,
            null, null);/*from w  w w  .  j a  va2 s  .  com*/

    if (status != HttpStatus.SC_NOT_FOUND) {
        Assert.fail("Upload attempt should have returned a 400, it returned:  " + status);
    }

    boolean fileWasUploaded = true;
    try {
        // download it
        downloadArtifact(gav, "./target/downloaded-jars");
    } catch (FileNotFoundException e) {
        fileWasUploaded = false;
    }

    Assert.assertFalse("The file was uploaded and it should not have been.", fileWasUploaded);

}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
public AbstractStorageItem retrieveItem(ProxyRepository repository, ResourceStoreRequest request,
        String baseUrl) throws ItemNotFoundException, RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(baseUrl, request.getRequestPath());

    HttpMethod method;/*  w w  w .  jav a2s . com*/

    method = new GetMethod(remoteURL.toString());

    int response = executeMethod(repository, request, method, remoteURL);

    if (response == HttpStatus.SC_OK) {
        if (method.getPath().endsWith("/")) {
            // this is a collection and not a file!
            // httpClient will follow redirections, and the getPath()
            // _should_
            // give us URL with ending "/"
            method.releaseConnection();

            throw new RemoteItemNotFoundException(request, repository, "remoteIsCollection",
                    remoteURL.toString());
        }

        GetMethod get = (GetMethod) method;

        InputStream is;

        try {
            is = get.getResponseBodyAsStream();
            if (get.getResponseHeader("Content-Encoding") != null
                    && "gzip".equals(get.getResponseHeader("Content-Encoding").getValue())) {
                is = new GZIPInputStream(is);
            }

            String mimeType;

            if (method.getResponseHeader("content-type") != null) {
                mimeType = method.getResponseHeader("content-type").getValue();
            } else {
                mimeType = getMimeSupport().guessMimeTypeFromPath(repository.getMimeRulesSource(),
                        request.getRequestPath());
            }

            DefaultStorageFileItem httpItem = new DefaultStorageFileItem(repository, request, true, true,
                    new PreparedContentLocator(new HttpClientInputStream(get, is), mimeType));

            if (get.getResponseContentLength() != -1) {
                // FILE
                httpItem.setLength(get.getResponseContentLength());
            }

            httpItem.setRemoteUrl(remoteURL.toString());

            httpItem.setModified(makeDateFromHeader(method.getResponseHeader("last-modified")));

            httpItem.setCreated(httpItem.getModified());

            httpItem.getItemContext().putAll(request.getRequestContext());

            return httpItem;
        } catch (IOException ex) {
            method.releaseConnection();

            throw new RemoteStorageException("IO Error during response stream handling [repositoryId=\""
                    + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\""
                    + remoteURL.toString() + "\"]!", ex);
        } catch (RuntimeException ex) {
            method.releaseConnection();

            throw ex;
        }
    } else {
        method.releaseConnection();

        if (response == HttpStatus.SC_NOT_FOUND) {
            throw new RemoteItemNotFoundException(request, repository, "NotFound", remoteURL.toString());
        } else {
            throw new RemoteStorageException("The method execution returned result code " + response
                    + " (expected 200). [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString() + "\"]");
        }
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.CommonsHttpClientRemoteStorage.java

@Override
protected boolean checkRemoteAvailability(long newerThen, ProxyRepository repository,
        ResourceStoreRequest request, boolean isStrict) throws RemoteStorageException {
    URL remoteURL = getAbsoluteUrlFromBase(repository, request);

    HttpMethodBase method = new HeadMethod(remoteURL.toString());

    int response = HttpStatus.SC_BAD_REQUEST;

    // artifactory hack, it pukes on HEAD so we will try with GET if HEAD fails
    boolean doGet = false;

    try {/*  ww  w.  j a  v  a  2  s.  c o  m*/
        response = executeMethod(repository, request, method, remoteURL);
    } catch (RemoteStorageException e) {
        // If HEAD failed, attempt a GET. Some repos may not support HEAD method
        doGet = true;

        getLogger().debug("HEAD method failed, will attempt GET.  Exception: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();

        // HEAD returned error, but not exception, try GET before failing
        if (!doGet && response != HttpStatus.SC_OK) {
            doGet = true;

            getLogger().debug("HEAD method failed, will attempt GET.  Status: " + response);
        }
    }

    if (doGet) {
        // create a GET
        method = new GetMethod(remoteURL.toString());

        try {
            // execute it
            response = executeMethod(repository, request, method, remoteURL);
        } finally {
            // and release it immediately
            method.releaseConnection();
        }
    }

    // if we are not strict and remote is S3
    if (!isStrict && isRemotePeerAmazonS3Storage(repository)) {
        // if we are relaxed, we will accept any HTTP response code below 500. This means anyway the HTTP
        // transaction succeeded. This method was never really detecting that the remoteUrl really denotes a root of
        // repository (how could we do that?)
        // this "relaxed" check will help us to "pass" S3 remote storage.
        return response >= HttpStatus.SC_OK && response <= HttpStatus.SC_INTERNAL_SERVER_ERROR;
    } else {
        // non relaxed check is strict, and will select only the OK response
        if (response == HttpStatus.SC_OK) {
            // we have it
            // we have newer if this below is true
            return makeDateFromHeader(method.getResponseHeader("last-modified")) > newerThen;
        } else if ((response >= HttpStatus.SC_MULTIPLE_CHOICES && response < HttpStatus.SC_BAD_REQUEST)
                || response == HttpStatus.SC_NOT_FOUND) {
            return false;
        } else {
            throw new RemoteStorageException("Unexpected response code while executing " + method.getName()
                    + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\""
                    + request.getRequestPath() + "\", remoteUrl=\"" + remoteURL.toString()
                    + "\"]. Expected: \"SUCCESS (200)\". Received: " + response + " : "
                    + HttpStatus.getStatusText(response));
        }
    }
}

From source file:org.wso2.appserver.integration.tests.webapp.virtualhost.DeployWebappsWithSameNameTestCase.java

@Test(dependsOnMethods = { "testInvokeWebApplications" })
public void testDeleteWebApplications() throws Exception {
    webAppAdminClient.deleteWebAppFile(webAppFileName, vhostName1);
    webAppAdminClient.deleteWebAppFile(webAppFileName, vhostName2);
    assertTrue(WebAppDeploymentUtil.isWebApplicationUnDeployed(backendURL, sessionCookie, webAppName),
            "Web Application unDeployment failed");

    GetMethod getRequest1 = getHttpRequest(vhostName1);
    int statusCode1 = getRequest1.getStatusCode();

    GetMethod getRequest2 = getHttpRequest(vhostName2);
    int statusCode2 = getRequest2.getStatusCode();
    Assert.assertEquals(statusCode1, HttpStatus.SC_NOT_FOUND, "Response code mismatch. Client request "
            + "got a response even after web app 1 is undeployed. Status code: " + statusCode1);
    Assert.assertEquals(statusCode2, HttpStatus.SC_NOT_FOUND, "Response code mismatch. Client request"
            + "got a response even after web app 2 is undeployed. Status code: " + statusCode2);
}

From source file:org.wso2.as.platform.tests.sample.WebAppDepSyncTestCase.java

@Test(groups = "wso2.as", description = "Validating undeployment on all worker nodes", dependsOnMethods = "org.wso2.as.platform.tests.sample.WebAppDepSyncTestCase.testWebApplicationUndeploymentOnManager", timeOut = 120000)
public void testWebApplicationUndeploymentOnWorkers() throws Exception {

    // Requests are sent directly to worker nodes after undeploying web app in manager node
    log.info(" ----- Validating web application undeployment via worker node-1 : " + webAppURLLocalWorker1);

    HttpResponse worker1Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker1, null);

    long currentTime = System.currentTimeMillis();

    while (((System.currentTimeMillis() - currentTime) < DEP_SYNC_TIME_OUT)) {

        if (worker1Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                || worker1Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            break;
        }//from  ww w .ja  va 2  s  .  c  o m

        try {
            Thread.sleep(DEP_SYNC_RETRY_PERIOD);
        } catch (InterruptedException e) {
            //ignored the exception here since it will exit the execution
        }
        worker1Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker1, null);
    }

    log.info(" ----- ResponseCode received worker node-1 : " + worker1Response.getResponseCode());

    // Validate dep sync undeployment on worker node within DEP_SYNC_TIME_OUT
    // After undeployment, HTTP response should be either HTTP 404 or HTTP 302
    assertTrue(
            worker1Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                    || worker1Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY,
            "Undeploying web app from all nodes failed");

    log.info(" ----- Validating web application undeployment via worker node-2 : " + webAppURLLocalWorker2);

    HttpResponse worker2Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker2, null);

    // Reset currentTime for worker node 2
    currentTime = System.currentTimeMillis();

    while (((System.currentTimeMillis() - currentTime) < DEP_SYNC_TIME_OUT)) {

        if (worker2Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                || worker2Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            break;
        }

        try {
            Thread.sleep(DEP_SYNC_RETRY_PERIOD);
        } catch (InterruptedException e) {
            //ignored the exception here since it will exit the execution
        }
        worker2Response = HttpRequestUtil.sendGetRequest(webAppURLLocalWorker2, null);
    }

    log.info(" ----- ResponseCode received worker node-2 : " + worker2Response.getResponseCode());

    // Validate dep sync undeployment on worker node within DEP_SYNC_TIME_OUT
    // After undeployment, HTTP response should be either HTTP 404 or HTTP 302
    assertTrue(
            worker2Response.getResponseCode() == HttpStatus.SC_NOT_FOUND
                    || worker2Response.getResponseCode() == HttpStatus.SC_MOVED_TEMPORARILY,
            "Undeploying web app from all nodes failed");

}

From source file:org.wso2.bps.integration.common.clients.bpmn.ActivitiRestClient.java

/**
 * Method is used to acquire deployment details using the deployment ID
 *
 * @param deploymentID Deployment ID of the BPMN Package
 * @throws java.io.IOException//from w  w  w  .  j  av  a  2s .c om
 * @throws org.json.JSONException
 * @returns String Array with status, deploymentID and Name
 */
public String[] getDeploymentInfoById(String deploymentID) throws Exception {

    String url = serviceURL + "repository/deployments/" + deploymentID;
    HttpHost target = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response = httpClient.execute(httpget);
    String status = response.getStatusLine().toString();
    String responseData = EntityUtils.toString(response.getEntity());
    JSONObject jsonResponseObject = new JSONObject(responseData);
    if (status.contains(Integer.toString(HttpStatus.SC_CREATED))
            || status.contains(Integer.toString(HttpStatus.SC_OK))) {
        String ID = jsonResponseObject.getString("id");
        String name = jsonResponseObject.getString("name");
        return new String[] { status, ID, name };
    } else if (status.contains(Integer.toString(HttpStatus.SC_NOT_FOUND))) {
        throw new RestClientException(NOT_AVAILABLE);
    } else {
        throw new RestClientException("Cannot find deployment");
    }
}

From source file:org.wso2.carbon.appfactory.git.repository.provider.SCMManagerBasedGITRepositoryProvider.java

/**
 * {@inheritDoc}/* ww w . j  a  va  2  s. c om*/
 */
@Override
public String getAppRepositoryURL(String applicationKey, String tenantDomain) throws RepositoryMgtException {
    HttpClient client = getClient();
    GetMethod get = new GetMethod(getServerURL() + REST_BASE_URI + REST_GET_REPOSITORY_URI + applicationKey);
    get.setDoAuthentication(true);
    get.addRequestHeader("Content-Type", "application/xml;charset=UTF-8");
    String repository = null;
    try {
        client.executeMethod(get);
        if (get.getStatusCode() == HttpStatus.SC_OK) {
            repository = getRepositoryFromStream(get.getResponseBodyAsStream()).getUrl();
        } else if (get.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            if (log.isDebugEnabled()) {
                log.debug("Repository is not found " + applicationKey);
            }
        } else {
            String msg = "Repository action is failed for " + applicationKey + " server returned status "
                    + get.getStatusText();
            log.error(msg);
            throw new RepositoryMgtException(msg);
        }
    } catch (IOException e) {
        String msg = "Error while invoking the service";
        log.error(msg, e);
        throw new RepositoryMgtException(msg, e);
    } finally {
        HttpConnectionManager manager = client.getHttpConnectionManager();
        if (manager instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) manager).shutdown();
        }
    }
    return repository;
}

From source file:org.wso2.carbon.appfactory.jenkins.deploy.JenkinsArtifactDeployer.java

/**
 * This method is used to build the specified job
 * build parameters are set in such a way that it does not execute any post build actions
 *
 * @param jobName// w w w  . ja  va 2 s .  c o  m
 *            job that we need to build
 * @param buildUrl
 *            url used to trigger the build
 * @throws AppFactoryException
 */
protected void triggerBuild(String jobName, String buildUrl, NameValuePair[] queryParameters)
        throws AppFactoryException {
    PostMethod buildMethod = new PostMethod(buildUrl);
    buildMethod.setDoAuthentication(true);
    if (queryParameters != null) {
        buildMethod.setQueryString(queryParameters);
    }
    HttpClient httpClient = new HttpClient();
    httpClient.getState().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(getAdminUsername(), getServerAdminPassword()));
    httpClient.getParams().setAuthenticationPreemptive(true);
    int httpStatusCode = -1;
    try {
        httpStatusCode = httpClient.executeMethod(buildMethod);

    } catch (Exception ex) {
        String errorMsg = String.format("Unable to start the build on job : %s", jobName);
        log.error(errorMsg);
        throw new AppFactoryException(errorMsg, ex);
    } finally {
        buildMethod.releaseConnection();
    }

    if (HttpStatus.SC_FORBIDDEN == httpStatusCode) {
        final String errorMsg = "Unable to start a build for job [".concat(jobName)
                .concat("] due to invalid credentials.").concat("Jenkins returned, http status : [")
                .concat(String.valueOf(httpStatusCode)).concat("]");
        log.error(errorMsg);
        throw new AppFactoryException(errorMsg);
    }

    if (HttpStatus.SC_NOT_FOUND == httpStatusCode) {
        final String errorMsg = "Unable to find the job [" + jobName + "Jenkins returned, " + "http status : ["
                + httpStatusCode + "]";
        log.error(errorMsg);
        throw new AppFactoryException(errorMsg);
    }
}

From source file:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.java

/**
 * Check whether domain is available/*from  ww  w  . j ava2  s.co m*/
 *
 * @param stage  mapping stage
 * @param domain e.g: some.organization1.org this doesn't require the protocol such as http/https
 * @param appType application type
 * @return true if domain is available
 */
private boolean isDomainAvailable(String stage, String domain, String appType) throws AppFactoryException {
    boolean isAvailable;
    String validateSubscriptionDomainEndPoint = DomainMappingUtils.getDomainAvailableEndPoint(stage, domain,
            appType);

    DomainMappingResponse response;
    try {
        // sending GET request for with domain.
        // if the requested domain is mapped it will send a response with 200 OK , else 404 Not found
        response = DomainMappingUtils.sendGetRequest(stage, validateSubscriptionDomainEndPoint);
    } catch (AppFactoryException e) {
        log.error("Error occurred while checking domain availability from Stratos side for domain:" + domain,
                e);
        throw new AppFactoryException(
                String.format(DomainMappingUtils.AF_DOMAIN_AVAILABILITY_ERROR_MSG, domain));
    }

    if (response.statusCode == HttpStatus.SC_NOT_FOUND) { // there is no existing mapping found for requested domain
        isAvailable = true;
    } else if (response.statusCode == HttpStatus.SC_OK) {
        isAvailable = false;
    } else {
        log.error(
                "Error occurred while checking availability for domain:" + domain + " Stratos response status: "
                        + response.statusCode + " Stratos Response message: " + response.getResponse());
        throw new AppFactoryException(
                String.format(DomainMappingUtils.AF_DOMAIN_AVAILABILITY_ERROR_MSG, domain));
    }
    return isAvailable;
}

From source file:org.wso2.carbon.appfactory.s4.integration.StratosRestClient.java

public boolean isApplicationCreated(String applicationId) throws AppFactoryException {
    ServerResponse response = MutualAuthHttpClient.sendGetRequest(
            this.stratosManagerURL + APPLICATIONS_REST_END_POINT + "/" + applicationId, username);
    if (response.getStatusCode() == HttpStatus.SC_OK) {
        String applicationInfoJson = response.getResponse();
        if (log.isDebugEnabled()) {
            log.debug("Stratos application information : " + applicationInfoJson);
        }//www. ja  va 2  s.  c o m
        return true;
    } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
        return false;
    } else {
        String errorMsg = "Error occured while getting while checking isApplicationCreated for ID : "
                + applicationId + "HTTP Status code : " + response.getStatusCode() + " server response : "
                + response.getResponse();
        log.error(errorMsg);
        throw new AppFactoryException(errorMsg);
    }
}