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:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public String ping() {
    GetMethod method = createGetMethod(baseUrl + PING);
    try {//from   w ww.  j a va  2  s  .  com
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        assertResponseCodeOK(method, statusCode);
        return method.getResponseBodyAsString();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.sittinglittleduck.DirBuster.Worker.java

/** Run method of the thread */
public void run() {

    queue = manager.workQueue;/*from   ww  w  .j av a 2 s .  c om*/
    while (manager.hasWorkLeft()) {

        working = false;
        // code to make the worker pause, if the pause button has been presed

        // if the stop signal has been given stop the thread
        if (stop) {
            return;
        }

        // this pauses the thread
        synchronized (this) {
            while (pleaseWait) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    return;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        HttpMethodBase httpMethod = null;

        try {

            work = (WorkUnit) queue.take();
            working = true;
            url = work.getWork();
            int code = 0;

            String response = "";
            String rawResponse = "";

            httpMethod = createHttpMethod(work.getMethod(), url.toString());

            // if the work is a head request
            if (work.getMethod().equalsIgnoreCase("HEAD")) {
                code = makeRequest(httpMethod);
                httpMethod.releaseConnection();

            }
            // if we are doing a get request
            else if (work.getMethod().equalsIgnoreCase("GET")) {
                code = makeRequest(httpMethod);

                String rawHeader = getHeadersAsString(httpMethod);
                response = getResponseAsString(httpMethod);

                rawResponse = rawHeader + response;
                // clean the response

                if (Config.parseHTML && !work.getBaseCaseObj().isUseRegexInstead()) {
                    parseHtml(httpMethod, response);
                }

                response = FilterResponce.CleanResponce(response, work);

                Thread.sleep(10);
                httpMethod.releaseConnection();
            }

            // if we need to check the against the base case
            if (work.getMethod().equalsIgnoreCase("GET") && work.getBaseCaseObj().useContentAnalysisMode()) {
                if (code == HttpStatus.SC_OK) {
                    verifyResponseForValidRequests(code, response, rawResponse);
                } else if (code == HttpStatus.SC_NOT_FOUND || code == HttpStatus.SC_BAD_REQUEST) {
                    if (Config.debug) {
                        System.out
                                .println("DEBUG Worker[" + threadId + "]: " + code + " for: " + url.toString());
                    }
                } else {
                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }
            }
            /*
             * use the custom regex check instead
             */
            else if (work.getBaseCaseObj().isUseRegexInstead()) {
                Pattern regexFindFile = Pattern.compile(work.getBaseCaseObj().getRegex());

                Matcher m = regexFindFile.matcher(rawResponse);

                if (m.find()) {
                    // do nothing as we have a 404
                    if (Config.debug) {
                        System.out.println("DEBUG Worker[" + threadId + "]: Regex matched so it's a 404, "
                                + url.toString());
                    }

                } else {
                    if (Config.parseHTML) {
                        parseHtml(httpMethod, rawResponse);
                    }

                    notifyItemFound(code, response, rawResponse, work.getBaseCaseObj().getBaseCase());
                }

            }
            // just check the response code
            else {
                // if is not the fail code, a 404 or a 400 then we have a possible
                if (code != work.getBaseCaseObj().getFailCode() && verifyIfCodeIsValid(code)) {
                    if (work.getMethod().equalsIgnoreCase("HEAD")) {
                        httpMethod = createHttpMethod("GET", url.toString());
                        int newCode = makeRequest(httpMethod);

                        // in some cases the second get can return a different result, than the
                        // first head request!
                        if (newCode != code) {
                            manager.foundError(url,
                                    "Return code for first HEAD, is different to the second GET: " + code
                                            + " - " + newCode);
                        }

                        // build a string version of the headers
                        rawResponse = getHeadersAsString(httpMethod);

                        if (httpMethod.getResponseContentLength() > 0) {

                            String responseBodyAsString = getResponseAsString(httpMethod);
                            rawResponse = rawResponse + responseBodyAsString;

                            if (Config.parseHTML) {
                                parseHtml(httpMethod, responseBodyAsString);
                            }
                        }

                        httpMethod.releaseConnection();
                    }

                    if (work.isDir()) {
                        manager.foundDir(url, code, rawResponse, work.getBaseCaseObj());
                    } else {
                        manager.foundFile(url, code, rawResponse, work.getBaseCaseObj());
                    }
                }
            }

            manager.workDone();
            Thread.sleep(20);

        } catch (NoHttpResponseException e) {
            manager.foundError(url, "NoHttpResponseException " + e.getMessage());
            manager.workDone();
        } catch (ConnectTimeoutException e) {
            manager.foundError(url, "ConnectTimeoutException " + e.getMessage());
            manager.workDone();
        } catch (URIException e) {
            manager.foundError(url, "URIException " + e.getMessage());
            manager.workDone();
        } catch (IOException e) {

            manager.foundError(url, "IOException " + e.getMessage());
            manager.workDone();
        } catch (InterruptedException e) {
            // manager.foundError(url, "InterruptedException " + e.getMessage());
            manager.workDone();
            return;
        } catch (IllegalArgumentException e) {

            e.printStackTrace();
            manager.foundError(url, "IllegalArgumentException " + e.getMessage());
            manager.workDone();
        } finally {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        }
    }
}

From source file:com.thoughtworks.go.server.service.ScheduleServiceSecurityTest.java

@Test
public void shouldReturnAppropriateHttpResultIfThePipelineAndStageNameAreInvalid() throws Exception {
    configHelper.addSecurityWithAdminConfig();
    configHelper.setOperatePermissionForGroup("defaultGroup", "jez");
    Username jez = new Username(new CaseInsensitiveString("jez"));
    HttpLocalizedOperationResult operationResult = new HttpLocalizedOperationResult();
    Stage resultStage = scheduleService.cancelAndTriggerRelevantStages("invalid-pipeline", "inavlid-stage", jez,
            operationResult);/*from   w  ww .  j a va2s.co  m*/

    assertThat(resultStage, is(nullValue()));
    assertThat(operationResult.isSuccessful(), is(false));
    assertThat(operationResult.httpCode(), is(HttpStatus.SC_NOT_FOUND));
}

From source file:edu.unc.lib.dl.cdr.sword.server.managers.MediaResourceManagerImpl.java

@Override
public MediaResource getMediaResourceRepresentation(String uri, Map<String, String> accept,
        AuthCredentials auth, SwordConfiguration config)
        throws SwordError, SwordServerException, SwordAuthException {

    log.debug("Retrieving media resource representation for " + uri);

    DatastreamPID targetPID = (DatastreamPID) extractPID(uri, SwordConfigurationImpl.EDIT_MEDIA_PATH + "/");

    Datastream datastream = Datastream.getDatastream(targetPID.getDatastream());
    if (datastream == null)
        datastream = virtualDatastreamMap.get(targetPID.getDatastream());

    if (datastream == null)
        throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                "Media representations other than those of datastreams are not currently supported");

    HttpClient client = new HttpClient();

    UsernamePasswordCredentials cred = new UsernamePasswordCredentials(accessClient.getUsername(),
            accessClient.getPassword());
    client.getState().setCredentials(new AuthScope(null, 443), cred);
    client.getState().setCredentials(new AuthScope(null, 80), cred);

    GetMethod method = new GetMethod(fedoraPath + "/objects/" + targetPID.getPid() + "/datastreams/"
            + datastream.getName() + "/content");

    InputStream inputStream = null;
    String mimeType = null;// ww w . j ava 2s . c o  m
    String lastModified = null;

    try {
        method.setDoAuthentication(true);
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            StringBuffer query = new StringBuffer();
            query.append("select $mimeType $lastModified from <%1$s>")
                    .append(" where <%2$s> <%3$s> $mimeType and <%2$s> <%4$s> $lastModified").append(";");
            String formatted = String.format(query.toString(),
                    tripleStoreQueryService.getResourceIndexModelUri(),
                    targetPID.getURI() + "/" + datastream.getName(),
                    ContentModelHelper.FedoraProperty.mimeType.getURI().toString(),
                    ContentModelHelper.FedoraProperty.lastModifiedDate.getURI().toString());
            List<List<String>> datastreamResults = tripleStoreQueryService.queryResourceIndex(formatted);
            if (datastreamResults.size() > 0) {
                mimeType = datastreamResults.get(0).get(0);
                lastModified = datastreamResults.get(0).get(1);
            }
            inputStream = new MethodAwareInputStream(method);
        } else if (method.getStatusCode() >= 500) {
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION, method.getStatusCode(),
                    "Failed to retrieve " + targetPID.getPid() + ": " + method.getStatusLine().toString());
        } else if (method.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new SwordError(ErrorURIRegistry.RESOURCE_NOT_FOUND, 404,
                    "Object " + targetPID.getPid() + " could not be found.");
        }
    } catch (HttpException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    } catch (IOException e) {
        throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                "An exception occurred while attempting to retrieve " + targetPID.getPid());
    }

    // For the ACL virtual datastream, transform RELS-EXT into accessControl tag
    if ("ACL".equals(targetPID.getDatastream())) {
        try {
            log.debug("Converting response XML to ACL format");
            SAXBuilder saxBuilder = new SAXBuilder();
            Document relsExt = saxBuilder.build(inputStream);
            XMLOutputter outputter = new XMLOutputter();
            Element accessElement = AccessControlTransformationUtil.rdfToACL(relsExt.getRootElement());
            inputStream.close();
            inputStream = new ByteArrayInputStream(outputter.outputString(accessElement).getBytes());
        } catch (Exception e) {
            log.debug("Failed to parse response from " + targetPID.getDatastreamURI() + " into ACL format", e);
            throw new SwordError(ErrorURIRegistry.RETRIEVAL_EXCEPTION,
                    "An exception occurred while attempting to retrieve " + targetPID.getPid());
        }
    }

    MediaResource resource = new MediaResource(inputStream, mimeType, null, true);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    Date lastModifiedDate;
    try {
        lastModifiedDate = formatter.parse(lastModified);
        resource.setLastModified(lastModifiedDate);
    } catch (ParseException e) {
        log.error("Unable to set last modified date for " + uri, e);
    }

    return resource;
}

From source file:com.google.collide.server.fe.WebFE.java

/**
 * Routes HTTP requests to the Collide web server.
 *///from  w  w w .ja  va2s . co m
@Override
public void handle(HttpServerRequest req) {
    String path = req.path;
    if (path.equals("/")) {

        // This is a request for the client. Serve it.
        authAndWriteHostPage(req);
    } else if (path.contains("..")) {

        // This is an attempt to escape the directory jail. Deny it.
        sendStatusCode(req, 404);
    } else if (path.startsWith(WEBROOT_PATH) && (webRootPrefix != null)) {

        // This is a request for content in the directory the user started the server in.
        req.response.sendFile(webRootPrefix + path.substring(WEBROOT_PATH.length()));
    } else if (path.startsWith(BUNDLED_STATIC_FILES_PATH) && (bundledStaticFilesPrefix != null)) {

        // This is a request for static content bundled with the client.
        req.response.sendFile(bundledStaticFilesPrefix + path.substring(BUNDLED_STATIC_FILES_PATH.length()));
    } else if (path.startsWith(AUTH_PATH)) {

        // This is an attempt to install the session cookie.
        writeSessionCookie(req);
    } else {

        // Otherwise, we don't know what you are looking for.
        sendStatusCode(req, HttpStatus.SC_NOT_FOUND);
    }
}

From source file:com.owncloud.android.operations.RemoveRemoteEncryptedFileOperation.java

/**
 * Performs the remove operation.// w w  w  . j a v  a 2  s .  c om
 */
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result;
    DeleteMethod delete = null;
    String token = null;
    DecryptedFolderMetadata metadata;

    String privateKey = arbitraryDataProvider.getValue(account.name, EncryptionUtils.PRIVATE_KEY);

    // unlock

    try {
        // Lock folder
        LockFileOperation lockFileOperation = new LockFileOperation(parentId);
        RemoteOperationResult lockFileOperationResult = lockFileOperation.execute(client, true);

        if (lockFileOperationResult.isSuccess()) {
            token = (String) lockFileOperationResult.getData().get(0);
        } else if (lockFileOperationResult.getHttpCode() == HttpStatus.SC_FORBIDDEN) {
            throw new RemoteOperationFailedException("Forbidden! Please try again later.)");
        } else {
            throw new RemoteOperationFailedException("Unknown error!");
        }

        // refresh metadata
        GetMetadataOperation getMetadataOperation = new GetMetadataOperation(parentId);
        RemoteOperationResult getMetadataOperationResult = getMetadataOperation.execute(client, true);

        if (getMetadataOperationResult.isSuccess()) {
            // decrypt metadata
            String serializedEncryptedMetadata = (String) getMetadataOperationResult.getData().get(0);

            EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils
                    .deserializeJSON(serializedEncryptedMetadata, new TypeToken<EncryptedFolderMetadata>() {
                    });

            metadata = EncryptionUtils.decryptFolderMetaData(encryptedFolderMetadata, privateKey);
        } else {
            throw new RemoteOperationFailedException("No Metadata found!");
        }

        // delete file remote
        delete = new DeleteMethod(client.getWebdavUri() + WebdavUtils.encodePath(remotePath));
        int status = client.executeMethod(delete, REMOVE_READ_TIMEOUT, REMOVE_CONNECTION_TIMEOUT);

        delete.getResponseBodyAsString(); // exhaust the response, although not interesting
        result = new RemoteOperationResult(delete.succeeded() || status == HttpStatus.SC_NOT_FOUND, delete);
        Log_OC.i(TAG, "Remove " + remotePath + ": " + result.getLogMessage());

        // remove file from metadata
        metadata.getFiles().remove(fileName);

        EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.encryptFolderMetadata(metadata,
                privateKey);
        String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);

        // upload metadata
        UpdateMetadataOperation storeMetadataOperation = new UpdateMetadataOperation(parentId,
                serializedFolderMetadata, token);
        RemoteOperationResult uploadMetadataOperationResult = storeMetadataOperation.execute(client, true);

        if (!uploadMetadataOperationResult.isSuccess()) {
            throw new RemoteOperationFailedException("Metadata not uploaded!");
        }

        // return success
        return result;
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Remove " + remotePath + ": " + result.getLogMessage(), e);

    } finally {
        if (delete != null) {
            delete.releaseConnection();
        }

        // unlock file
        if (token != null) {
            UnlockFileOperation unlockFileOperation = new UnlockFileOperation(parentId, token);
            RemoteOperationResult unlockFileOperationResult = unlockFileOperation.execute(client, true);

            if (!unlockFileOperationResult.isSuccess()) {
                Log_OC.e(TAG, "Failed to unlock " + parentId);
            }
        }
    }

    return result;
}

From source file:com.thoughtworks.go.server.service.PipelinePauseServiceTest.java

@Test
public void shouldPopulateHttpResult404WhenPipelineIsNotFoundForUnpause() throws Exception {
    HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
    when(goConfigFileDao.load()).thenReturn(new BasicCruiseConfig());

    pipelinePauseService.unpause(INVALID_PIPELINE, VALID_USER, result);

    assertThat(result.isSuccessful(), is(false));
    assertThat(result.httpCode(), is(HttpStatus.SC_NOT_FOUND));
    verify(pipelineDao, never()).unpause(INVALID_PIPELINE);
}

From source file:com.cubeia.backoffice.operator.client.OperatorServiceClientHTTP.java

protected InputStream execute(HttpMethodBase method) throws IOException {
    try {//from  w  w  w.  java2  s.  c om
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        assertResponseCodeOK(method, statusCode);
        return method.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new IOException("Exception executing http method at " + method.getURI(), e);
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public AuthenticationResponse authenticate(Long operatorId, String username, String password) {
    PostMethod method = new PostMethod(baseUrl + AUTHENTICATE);
    AuthenticationRequest request = new AuthenticationRequest();
    request.setOperatorId(operatorId);/*from w w w .j a  v  a 2s .c o  m*/
    request.setUserName(username);
    request.setPassword(password);

    try {
        String data = serialize(request);
        method.setRequestEntity(new StringRequestEntity(data, "application/json", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return null;
        }
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            AuthenticationResponse response = new AuthenticationResponse();
            response.setAuthenticated(false);
            return response;

        } else if (statusCode == HttpStatus.SC_OK) {
            InputStream body = method.getResponseBodyAsStream();
            return parseJson(body, AuthenticationResponse.class);

        } else {
            throw new RuntimeException("Failed to authenticate user, RESPONSE CODE: " + statusCode);
        }

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:jetbrains.buildServer.symbols.DownloadSymbolsControllerTest.java

@Test
public void request_pdb_guid_toLowerCase() throws Exception {
    myFixture.getServerSettings().setPerProjectPermissionsEnabled(true);
    SUser user = myFixture.getUserModel().getGuestUser();
    user.addRole(RoleScope.projectScope(myProject.getProjectId()), getProjectDevRole());
    assertTrue(/*  w  w w  . java 2 s  .  com*/
            user.isPermissionGrantedForProject(myProject.getProjectId(), Permission.VIEW_BUILD_RUNTIME_DATA));

    final File artDirectory = createTempDir();
    assertTrue(new File(artDirectory, "foo").createNewFile());
    ;

    myBuildType.setArtifactPaths(artDirectory.getAbsolutePath());
    RunningBuildEx build = startBuild();
    finishBuild(build, false);

    final String fileSignature = "8EF4E863187C45E78F4632152CC82FEB";
    final String guid = "8EF4E863187C45E78F4632152CC82FE";
    final String fileName = "secur32.pdb";
    final String filePath = "foo/secur32.pdb";

    myBuildMetadataStorage.addEntry(build.getBuildId(), filePath, guid.toLowerCase());
    myRequest.setRequestURI("mock", String.format("/app/symbols/%s/%s/%s", fileName, fileSignature, fileName));

    doGet();

    assertEquals(HttpStatus.SC_NOT_FOUND, myResponse.getStatus());
    assertEquals("Symbol file not found", myResponse.getStatusText());
}