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.zaproxy.zap.extension.ascanrulesBeta.BackupFileDisclosure.java

@Override
public void scan() {
    if (log.isDebugEnabled()) {
        log.debug("Attacking at Attack Strength: " + this.getAttackStrength());
        log.debug("Checking [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                + getBaseMsg().getRequestHeader().getURI() + "], for Backup File Disclosure");
    }//from  w ww. j av a 2  s.c o  m

    try {
        URI uri = this.getBaseMsg().getRequestHeader().getURI();
        String filename = uri.getName();

        int statusCode = this.getBaseMsg().getResponseHeader().getStatusCode();
        if (log.isDebugEnabled())
            log.debug("About to look for a backup for '" + uri.getURI() + "', which returned " + statusCode);

        // is it worth looking for a copy of the file?
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            if (log.isDebugEnabled())
                log.debug("The original file request was not successfuly retrieved (status = " + statusCode
                        + "), so there is not much point in looking for a backup of a non-existent file!");
            return;
        }
        if (filename != null && filename.length() > 0) {
            // there is a file name at the end of the path, so look for a backup file for the
            // file
            findBackupFile(this.getBaseMsg());
        } else {
            if (log.isDebugEnabled()) {
                log.debug(
                        "The URI has no filename component, so there is not much point in looking for a corresponding backup file!");
            }
        }
    } catch (Exception e) {
        log.error("Error scanning a request for Backup File Disclosure: " + e.getMessage(), e);
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.BackupFileDisclosure.java

/**
 * attempts to find a backup file for the given file
 *
 * @param uri the URI of a file//from  ww w.j ava  2s .c o  m
 * @return
 */
private void findBackupFile(HttpMessage originalMessage) throws Exception {

    try {
        boolean gives404s = true;
        boolean parentgives404s = true;
        byte[] nonexistparentmsgdata = null;

        URI originalURI = originalMessage.getRequestHeader().getURI();

        // request a file in the same directory to see how it handles "File not found". Using a
        // 404? Something else?
        String temppath = originalURI.getPath();
        if (temppath == null)
            temppath = "";
        int slashposition = temppath.lastIndexOf("/");
        if (slashposition < 0) {
            // WTF? there was no slash in the path..
            throw new Exception("The message has a path with a malformed path component");
        }
        String filename = originalMessage.getRequestHeader().getURI().getName();

        String randomfilename = RandomStringUtils.random(filename.length(),
                "abcdefghijklmoopqrstuvwxyz9123456789");
        String randomfilepath = temppath.substring(0, slashposition) + "/" + randomfilename;

        if (log.isDebugEnabled())
            log.debug("Trying non-existent file: " + randomfilepath);
        HttpMessage nonexistfilemsg = new HttpMessage(
                new URI(originalURI.getScheme(), originalURI.getAuthority(), randomfilepath, null, null));
        try {
            nonexistfilemsg.setCookieParams(originalMessage.getCookieParams());
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Could not set the cookies from the base request:" + e);
        }
        sendAndReceive(nonexistfilemsg, false);
        byte[] nonexistfilemsgdata = nonexistfilemsg.getResponseBody().getBytes();
        // does the server give a 404 for a non-existent file?
        if (nonexistfilemsg.getResponseHeader().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
            gives404s = false;
            if (log.isDebugEnabled())
                log.debug("The server does not return a 404 status for a non-existent path: "
                        + nonexistfilemsg.getRequestHeader().getURI().getURI());
        } else {
            gives404s = true;
            if (log.isDebugEnabled())
                log.debug("The server gives a 404 status for a non-existent path: "
                        + nonexistfilemsg.getRequestHeader().getURI().getURI());
        }

        // now request a different (and non-existent) parent directory,
        // to see whether a non-existent parent folder causes a 404
        String[] pathbreak = temppath.split("/");
        HttpMessage nonexistparentmsg = null;
        if (pathbreak.length > 2) { // the file has a parent folder that is not the root folder (ie, there is
            // a parent folder to mess with)
            String[] temppathbreak = pathbreak;
            String parentfoldername = pathbreak[pathbreak.length - 2];
            String randomparentfoldername = RandomStringUtils.random(parentfoldername.length(),
                    "abcdefghijklmoopqrstuvwxyz9123456789");

            // replace the parent folder name with the random one, and build it back into a
            // string
            temppathbreak[pathbreak.length - 2] = randomparentfoldername;
            String randomparentpath = StringUtils.join(temppathbreak, "/");

            if (log.isDebugEnabled())
                log.debug("Trying non-existent parent path: " + randomparentpath);
            nonexistparentmsg = new HttpMessage(
                    new URI(originalURI.getScheme(), originalURI.getAuthority(), randomparentpath, null, null));
            try {
                nonexistparentmsg.setCookieParams(originalMessage.getCookieParams());
            } catch (Exception e) {
                if (log.isDebugEnabled())
                    log.debug("Could not set the cookies from the base request:" + e);
            }
            sendAndReceive(nonexistparentmsg, false);
            nonexistparentmsgdata = nonexistparentmsg.getResponseBody().getBytes();
            // does the server give a 404 for a non-existent parent folder?
            if (nonexistparentmsg.getResponseHeader().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
                parentgives404s = false;
                if (log.isDebugEnabled())
                    log.debug("The server does not return a 404 status for a non-existent parent path: "
                            + nonexistparentmsg.getRequestHeader().getURI().getURI());
            } else {
                parentgives404s = true;
                if (log.isDebugEnabled())
                    log.debug("The server gives a 404 status for a non-existent parent path: "
                            + nonexistparentmsg.getRequestHeader().getURI().getURI());
            }
        }

        String actualfilename = originalURI.getName();
        String actualfileExtension = null;
        String path = originalURI.getPath();
        if (path == null)
            path = "";

        // record the position of the various injection points, always relative to the full path
        int positionExtensionInjection = 0;
        int positionFileSuffixInjection = 0;
        if (actualfilename.contains(".")) {
            positionExtensionInjection = path.lastIndexOf(".");
            positionFileSuffixInjection = positionExtensionInjection;
            actualfileExtension = actualfilename.substring(actualfilename.lastIndexOf("."));
        } else {
            positionExtensionInjection = path.length();
            positionFileSuffixInjection = path.length();
            actualfileExtension = "";
        }
        int positionFilePrefixInjection = path.lastIndexOf("/") + 1;
        int positionDirectorySuffixInjection = path.lastIndexOf("/");
        int positionDirectoryPrefixInjection = 0;
        if (positionDirectorySuffixInjection >= 0)
            positionDirectoryPrefixInjection = path.substring(0, positionDirectorySuffixInjection)
                    .lastIndexOf("/") + 1;

        // the set of files we will try, in the order of insertion
        Set<URI> candidateBackupFileURIs = new LinkedHashSet<URI>();
        Set<URI> candidateBackupFileChangedFolderURIs = new LinkedHashSet<URI>(); // for a changed parent folder name, which we need to handle
        // separately

        log.debug("The path is " + path);

        // for each file extension to try (both appending, and replacing)
        int counted = 0;
        for (String fileExtensionToTry : fileExtensions) {
            // to append, inject the file extension at the end of the path
            String candidateBackupFilePath = path + fileExtensionToTry;
            log.debug("File Extension (append): '" + candidateBackupFilePath + "'");
            candidateBackupFileURIs.add(new URI(originalURI.getScheme(), originalURI.getAuthority(),
                    candidateBackupFilePath, null, null));

            // to replace the extension, append the file extension at positionExtensionInjection
            candidateBackupFilePath = path.substring(0, positionExtensionInjection) + fileExtensionToTry;
            log.debug("File Extension (replace): '" + candidateBackupFilePath + "'");
            candidateBackupFileURIs.add(new URI(originalURI.getScheme(), originalURI.getAuthority(),
                    candidateBackupFilePath, null, null));

            // to switch the extension (if there was one), append the file extension at
            // positionExtensionInjection
            if (!actualfileExtension.equals("") && doSwitchFileExtension) {
                candidateBackupFilePath = path.substring(0, positionExtensionInjection) + fileExtensionToTry
                        + actualfileExtension;
                log.debug("File Extension (switch): '" + candidateBackupFilePath + "'");
                candidateBackupFileURIs.add(new URI(originalURI.getScheme(), originalURI.getAuthority(),
                        candidateBackupFilePath, null, null));
            }
            counted++;
            if (counted > numExtensionsToTry) {
                break; // out of the loop.
            }
        }

        // for each file suffix to try
        counted = 0;
        for (String fileSuffixToTry : fileSuffixes) {
            // inject the file suffix at positionFileSuffixInjection
            String candidateBackupFilePath = path.substring(0, positionFileSuffixInjection) + fileSuffixToTry
                    + (positionFileSuffixInjection >= path.length() ? ""
                            : path.substring(positionFileSuffixInjection));
            log.debug("File Suffix (insert): '" + candidateBackupFilePath + "'");
            candidateBackupFileURIs.add(new URI(originalURI.getScheme(), originalURI.getAuthority(),
                    candidateBackupFilePath, null, null));
            counted++;
            if (counted > numSuffixesToTry) {
                break; // out of the loop.
            }
        }

        // for each file prefix to try
        counted = 0;
        for (String filePrefixToTry : filePrefixes) {
            // inject the file prefix at positionFilePrefixInjection
            String candidateBackupFilePath = path.substring(0, positionFilePrefixInjection) + filePrefixToTry
                    + (positionFilePrefixInjection >= path.length() ? ""
                            : path.substring(positionFilePrefixInjection));
            log.debug("File Prefix (insert): '" + candidateBackupFilePath + "'");
            candidateBackupFileURIs.add(new URI(originalURI.getScheme(), originalURI.getAuthority(),
                    candidateBackupFilePath, null, null));
            counted++;
            if (counted > numPrefixesToTry) {
                break; // out of the loop.
            }
        }

        // for each directory suffix/prefix to try (using the file prefixes/suffixes - or
        // whatever the plural of prefix/suffix is)
        counted = 0;
        if (pathbreak.length > 2) {
            // if there is a a parent folder to play with
            for (String fileSuffixToTry : fileSuffixes) {
                // inject the directory suffix at positionDirectorySuffixInjection
                String candidateBackupFilePath = path.substring(0, positionDirectorySuffixInjection)
                        + fileSuffixToTry + (positionDirectorySuffixInjection >= path.length() ? ""
                                : path.substring(positionDirectorySuffixInjection));
                log.debug("Directory Suffix (insert): '" + candidateBackupFilePath + "'");
                candidateBackupFileChangedFolderURIs.add(new URI(originalURI.getScheme(),
                        originalURI.getAuthority(), candidateBackupFilePath, null, null));
                counted++;
                if (counted > numSuffixesToTry) {
                    break; // out of the loop.
                }
            }
            for (String filePrefixToTry : filePrefixes) {
                // inject the directory prefix at positionDirectorySuffixInjection
                String candidateBackupFilePath = path.substring(0, positionDirectoryPrefixInjection)
                        + filePrefixToTry + (positionDirectoryPrefixInjection >= path.length() ? ""
                                : path.substring(positionDirectoryPrefixInjection));
                log.debug("Directory Suffix (insert): '" + candidateBackupFilePath + "'");
                candidateBackupFileChangedFolderURIs.add(new URI(originalURI.getScheme(),
                        originalURI.getAuthority(), candidateBackupFilePath, null, null));
                counted++;
                if (counted > numSuffixesToTry) {
                    break; // out of the loop.
                }
            }
        }

        // now we have a set of candidate URIs appropriate to the attack strength chosen by the
        // user
        // try each candidate URI in turn.
        for (URI candidateBackupFileURI : candidateBackupFileURIs) {
            byte[] disclosedData = {};
            if (log.isDebugEnabled())
                log.debug("Trying possible backup file path: " + candidateBackupFileURI.getURI());
            HttpMessage requestmsg = new HttpMessage(candidateBackupFileURI);
            try {
                requestmsg.setCookieParams(originalMessage.getCookieParams());
            } catch (Exception e) {
                if (log.isDebugEnabled())
                    log.debug("Could not set the cookies from the base request:" + e);
            }
            // Do not follow redirects. They're evil. Yep.
            sendAndReceive(requestmsg, false);
            disclosedData = requestmsg.getResponseBody().getBytes();
            int requestStatusCode = requestmsg.getResponseHeader().getStatusCode();

            // just to complicate things.. I have a test case which for the random file, does
            // NOT give a 404 (so gives404s == false)
            // but for a "Copy of" file, actually gives a 404 (for some unknown reason). We need
            // to handle this case.
            if (!isEmptyResponse(disclosedData) && ((gives404s && requestStatusCode != HttpStatus.SC_NOT_FOUND)
                    || ((!gives404s) && nonexistfilemsg.getResponseHeader().getStatusCode() != requestStatusCode
                            && (!Arrays.equals(disclosedData, nonexistfilemsgdata))))) {
                bingo(Alert.RISK_MEDIUM, Alert.CONFIDENCE_MEDIUM,
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.name"),
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.desc"),
                        requestmsg.getRequestHeader().getURI().getURI(), // originalMessage.getRequestHeader().getURI().getURI(),
                        null, // parameter being attacked: none.
                        candidateBackupFileURI.getURI(), // attack
                        originalMessage.getRequestHeader().getURI().getURI(), // new String (disclosedData),  //extrainfo
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.soln"),
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.evidence", originalURI,
                                candidateBackupFileURI.getURI()),
                        requestmsg // originalMessage
                );
            }

            if (isStop()) {
                if (log.isDebugEnabled())
                    log.debug("The scanner was stopped in response to a user request");
                return;
            }
        }

        // now try the changed parent folders (if any)
        // the logic here needs to check using the parent 404 logic, and the output for a
        // non-existent parent folder.
        for (URI candidateBackupFileURI : candidateBackupFileChangedFolderURIs) {
            byte[] disclosedData = {};
            if (log.isDebugEnabled())
                log.debug("Trying possible backup file path (with changed parent folder): "
                        + candidateBackupFileURI.getURI());
            HttpMessage requestmsg = new HttpMessage(candidateBackupFileURI);
            try {
                requestmsg.setCookieParams(originalMessage.getCookieParams());
            } catch (Exception e) {
                if (log.isDebugEnabled())
                    log.debug("Could not set the cookies from the base request:" + e);
            }
            // Do not follow redirects. They're evil. Yep.
            sendAndReceive(requestmsg, false);
            disclosedData = requestmsg.getResponseBody().getBytes();
            int requestStatusCode = requestmsg.getResponseHeader().getStatusCode();
            // If the response is empty it's probably not really a backup

            if (!isEmptyResponse(disclosedData)
                    && ((parentgives404s && requestStatusCode != HttpStatus.SC_NOT_FOUND) || ((!parentgives404s)
                            && nonexistparentmsg.getResponseHeader().getStatusCode() != requestStatusCode
                            && (!Arrays.equals(disclosedData, nonexistparentmsgdata))))) {
                bingo(Alert.RISK_MEDIUM, Alert.CONFIDENCE_MEDIUM,
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.name"),
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.desc"),
                        requestmsg.getRequestHeader().getURI().getURI(), // originalMessage.getRequestHeader().getURI().getURI(),
                        null, // parameter being attacked: none.
                        candidateBackupFileURI.getURI(), // attack
                        originalMessage.getRequestHeader().getURI().getURI(), // new String (disclosedData),  //extrainfo
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.soln"),
                        Constant.messages.getString("ascanbeta.backupfiledisclosure.evidence", originalURI,
                                candidateBackupFileURI.getURI()),
                        requestmsg // originalMessage
                );
            }

            if (isStop()) {
                if (log.isDebugEnabled())
                    log.debug("The scanner was stopped in response to a user request");
                return;
            }
        }

    } catch (Exception e) {
        log.error("Some error occurred when looking for a backup file for '"
                + originalMessage.getRequestHeader().getURI(), e);
        return;
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.SourceCodeDisclosureCVE20121823.java

@Override
public void scan() {
    try {/*from   w w w  . jav a  2  s .c  o  m*/

        if (!getBaseMsg().getResponseHeader().isText()) {
            return; // Ignore images, pdfs, etc.
        }
        if (getAlertThreshold() != AlertThreshold.LOW && getBaseMsg().getResponseHeader().isJavaScript()) {
            return;
        }
        // at Low or Medium strength, do not attack URLs which returned "Not Found"
        AttackStrength attackStrength = getAttackStrength();
        if ((attackStrength == AttackStrength.LOW || attackStrength == AttackStrength.MEDIUM)
                && (getBaseMsg().getResponseHeader().getStatusCode() == HttpStatus.SC_NOT_FOUND))
            return;

        URI originalURI = getBaseMsg().getRequestHeader().getURI();

        // construct a new URL based on the original URL, but without any of the original
        // parameters
        String attackParam = "?-s";
        URI attackURI = createAttackUri(originalURI, attackParam);
        if (attackURI == null) {
            return;
        }
        // and send it as a GET, unauthorised.
        HttpMessage attackmsg = new HttpMessage(attackURI);
        sendAndReceive(attackmsg, false); // do not follow redirects

        if (attackmsg.getResponseHeader().getStatusCode() == HttpStatus.SC_OK) {
            // double-check: does the response contain HTML encoded PHP?
            // Ignore the case where it contains encoded HTML for now, since thats not a source
            // code disclosure anyway
            // (HTML is always sent back to the web browser)
            String responseBody = new String(attackmsg.getResponseBody().getBytes());
            String responseBodyDecoded = new Source(responseBody).getRenderer().toString();

            Matcher matcher1 = PHP_PATTERN1.matcher(responseBodyDecoded);
            Matcher matcher2 = PHP_PATTERN2.matcher(responseBodyDecoded);
            boolean match1 = matcher1.matches();
            boolean match2 = matcher2.matches();

            if ((!responseBody.equals(responseBodyDecoded)) && (match1 || match2)) {

                if (log.isDebugEnabled()) {
                    log.debug("Source Code Disclosure alert for: " + originalURI.getURI());
                }

                String sourceCode = null;
                if (match1) {
                    sourceCode = matcher1.group(1);
                } else {
                    sourceCode = matcher2.group(1);
                }

                // bingo.
                bingo(Alert.RISK_HIGH, Alert.CONFIDENCE_MEDIUM,
                        Constant.messages.getString("ascanbeta.sourcecodedisclosurecve-2012-1823.name"),
                        Constant.messages.getString("ascanbeta.sourcecodedisclosurecve-2012-1823.desc"), null, // originalMessage.getRequestHeader().getURI().getURI(),
                        null, // parameter being attacked: none.
                        "", // attack: none (it's not a parameter being attacked)
                        sourceCode, // extrainfo
                        Constant.messages.getString("ascanbeta.sourcecodedisclosurecve-2012-1823.soln"), "", // evidence, highlighted in the message  (cannot use the source code
                        // here, since it is encoded in the message response, and so will
                        // not match up)
                        attackmsg // raise the alert on the attack message
                );
            }
        }
    } catch (Exception e) {
        log.error("Error scanning a Host for Source Code Disclosure via CVE-2012-1823: " + e.getMessage(), e);
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.SourceCodeDisclosureSVN.java

@Override
public void scan() {
    // at Low or Medium strength, do not attack URLs which returned "Not Found"
    AttackStrength attackStrength = getAttackStrength();
    if ((attackStrength == AttackStrength.LOW || attackStrength == AttackStrength.MEDIUM)
            && (getBaseMsg().getResponseHeader().getStatusCode() == HttpStatus.SC_NOT_FOUND))
        return;//from   ww  w .j a  va2 s .co m

    // scan the node itself (ie, at URL level, rather than at parameter level)
    if (log.isDebugEnabled()) {
        log.debug("Attacking at Attack Strength: " + this.getAttackStrength());
        log.debug("Checking [" + getBaseMsg().getRequestHeader().getMethod() + "] ["
                + getBaseMsg().getRequestHeader().getURI()
                + "], for Source Code Disclosure using SVN meta-data");
    }

    try {
        URI uri = this.getBaseMsg().getRequestHeader().getURI();
        String filename = uri.getName();

        if (filename != null && filename.length() > 0) {
            // there is a file name at the end of the path.

            // Look for SVN metadata that can be exploited to give us the source code.
            if (findSourceCodeSVN(this.getBaseMsg())) {
                // found one. no need to try other methods, so bale out.
                return;
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug(
                        "The URI has no filename component, so there is not much point in looking for corresponding source code!");
            }
        }
    } catch (Exception e) {
        log.error("Error scanning a request for SVN based Source Code Disclosure: " + e.getMessage(), e);
    }
}

From source file:org.zaproxy.zap.extension.pscanrules.ApplicationErrorScanner.java

/**
 * Perform the passive scanning of application errors inside the response
 * content/*from  www  . ja  v  a2s .c o m*/
 *
 * @param msg the message that need to be checked
 * @param id the id of the session
 * @param source the source code of the response
 */
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {

    // First check if it's an INTERNAL SERVER ERROR
    int status = msg.getResponseHeader().getStatusCode();
    if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        // We found it!
        // The AS raise an Internal Error
        // so a possible disclosure can be found
        raiseAlert(msg, id, EVIDENCE_INTERNAL_SERVER_ERROR);

    } else if (status != HttpStatus.SC_NOT_FOUND) {
        String evidence = matcher.findInContent(msg.getResponseBody().toString());
        if (evidence != null) {
            // We found it!
            // There exists a positive match of an
            // application error occurrence
            raiseAlert(msg, id, evidence);
        }
    }
}

From source file:org.zenoss.zep.rest.EventsResourceIT.java

@Test
public void testUpdateEventSummary() throws ZepException, IOException {
    List<String> uuids = new ArrayList<String>(100);
    for (int i = 0; i < 100; i++) {
        uuids.add(createSummaryNew(EventSummaryDaoImplIT.createUniqueEvent()).getUuid());
    }/*from  www  .  j av  a  2 s  . co  m*/

    // Update first 50
    EventStatus status = EventStatus.STATUS_ACKNOWLEDGED;
    String ackUuid = UUID.randomUUID().toString();
    String ackName = "testuser123";

    EventQuery.Builder queryBuilder = EventQuery.newBuilder();
    queryBuilder.setEventFilter(EventFilter.newBuilder().addAllUuid(uuids).build());
    EventQuery query = queryBuilder.build();
    RestResponse restResponse = client.postProtobuf(EVENTS_URI + "/search", query);
    assertEquals(HttpStatus.SC_CREATED, restResponse.getResponseCode());
    String location = restResponse.getHeaders().get("location").get(0);
    String query_uuid = location.substring(location.lastIndexOf('/') + 1);

    final EventSummaryUpdate updateFields = EventSummaryUpdate.newBuilder().setCurrentUserUuid(ackUuid)
            .setCurrentUserName(ackName).setStatus(status).build();
    EventSummaryUpdateRequest.Builder reqBuilder = EventSummaryUpdateRequest.newBuilder();
    reqBuilder.setLimit(50);
    reqBuilder.setUpdateFields(updateFields);
    EventSummaryUpdateRequest req = reqBuilder.build();
    restResponse.getResponse().getEntity().consumeContent();

    restResponse = client.putProtobuf(location, req);
    EventSummaryUpdateResponse response = (EventSummaryUpdateResponse) restResponse.getMessage();
    assertEquals(EventSummaryUpdateRequest.newBuilder(req).setOffset(50).setEventQueryUuid(query_uuid).build(),
            response.getNextRequest());
    assertEquals(uuids.size(), response.getTotal());
    assertEquals(50, response.getUpdated());

    // Repeat request for last 50
    restResponse = client.putProtobuf(location, response.getNextRequest());
    EventSummaryUpdateResponse newResponse = (EventSummaryUpdateResponse) restResponse.getMessage();
    assertFalse(newResponse.hasNextRequest());
    assertEquals(50, response.getUpdated());
    assertEquals(uuids.size(), response.getTotal());

    assertEquals(HttpStatus.SC_NO_CONTENT, client.delete(location).getResponseCode());
    assertEquals(HttpStatus.SC_NOT_FOUND, client.getProtobuf(location).getResponseCode());

    // Verify updates hit the database
    List<EventSummary> summaries = summaryDao.findByUuids(uuids);
    assertEquals(uuids.size(), summaries.size());
    for (EventSummary summary : summaries) {
        assertEquals(status, summary.getStatus());
        assertEquals(ackUuid, summary.getCurrentUserUuid());
        assertEquals(ackName, summary.getCurrentUserName());
    }
}

From source file:org.zenoss.zep.rest.EventsResourceIT.java

@Test
public void testUpdateEventSummaryExclusions() throws ZepException, IOException {
    long firstSeen = System.currentTimeMillis();
    TimestampRange firstSeenRange = TimestampRange.newBuilder().setStartTime(firstSeen).setEndTime(firstSeen)
            .build();//w w  w. ja v a 2s  .  com
    Set<String> uuids = new HashSet<String>();
    Map<String, EventSummary> excludedUuids = new HashMap<String, EventSummary>();
    for (int i = 0; i < 5; i++) {
        Event event = Event.newBuilder(EventSummaryDaoImplIT.createUniqueEvent()).setCreatedTime(firstSeen)
                .build();
        EventSummary summary = createSummaryNew(event);
        if ((i % 2) == 0) {
            uuids.add(summary.getUuid());
        } else {
            excludedUuids.put(summary.getUuid(), summary);
        }
    }

    EventQuery.Builder queryBuilder = EventQuery.newBuilder();
    queryBuilder.setEventFilter(EventFilter.newBuilder().addFirstSeen(firstSeenRange).build());
    queryBuilder.setExclusionFilter(EventFilter.newBuilder().addAllUuid(excludedUuids.keySet()).build());
    EventQuery query = queryBuilder.build();
    RestResponse restResponse = client.postProtobuf(EVENTS_URI + "/search", query);
    assertEquals(HttpStatus.SC_CREATED, restResponse.getResponseCode());
    String location = restResponse.getHeaders().get("location").get(0);
    restResponse.getResponse().getEntity().consumeContent();

    // Update first 10
    EventStatus status = EventStatus.STATUS_ACKNOWLEDGED;
    String ackUuid = UUID.randomUUID().toString();
    String ackName = "testuser123";

    final EventSummaryUpdate updateFields = EventSummaryUpdate.newBuilder().setCurrentUserUuid(ackUuid)
            .setCurrentUserName(ackName).setStatus(status).build();
    EventSummaryUpdateRequest.Builder reqBuilder = EventSummaryUpdateRequest.newBuilder();
    reqBuilder.setLimit(10);
    reqBuilder.setUpdateFields(updateFields);
    EventSummaryUpdateRequest req = reqBuilder.build();

    EventSummaryUpdateResponse response = (EventSummaryUpdateResponse) client.putProtobuf(location, req)
            .getMessage();
    assertFalse(response.hasNextRequest());
    assertEquals(uuids.size(), response.getUpdated());
    assertEquals(uuids.size(), response.getTotal());

    assertEquals(HttpStatus.SC_NO_CONTENT, client.delete(location).getResponseCode());
    assertEquals(HttpStatus.SC_NOT_FOUND, client.getProtobuf(location).getResponseCode());

    // Verify updates hit the database
    List<String> allUuids = new ArrayList<String>();
    allUuids.addAll(uuids);
    allUuids.addAll(excludedUuids.keySet());
    List<EventSummary> summaries = summaryDao.findByUuids(allUuids);
    assertEquals(allUuids.size(), summaries.size());
    for (EventSummary summary : summaries) {
        if (uuids.contains(summary.getUuid())) {
            assertEquals(status, summary.getStatus());
            assertEquals(ackUuid, summary.getCurrentUserUuid());
            assertEquals(ackName, summary.getCurrentUserName());
        } else {
            // Excluded UUIDs shouldn't have changed
            assertEquals(excludedUuids.get(summary.getUuid()), summary);
        }
    }
}

From source file:pl.nask.hsn2.connector.CuckooRESTConnector.java

public final void deleteTaskData(long cuckooTaskId) {
    try (CuckooConnection connection = connect(cuckooURL + DELETE_TASK + cuckooTaskId)) {
        int status = connection.getResultStatusCode();
        switch (status) {
        case HttpStatus.SC_OK:
            LOGGER.info("Cuckoo: task data deleted: " + cuckooTaskId);
            break;
        case HttpStatus.SC_NOT_FOUND:
            LOGGER.warn("Cuckoo: error deleting task data, task not found: " + cuckooTaskId);
            break;
        case HttpStatus.SC_INTERNAL_SERVER_ERROR:
            LOGGER.warn("Cuckoo: error deleting task data, could not delete task data: " + cuckooTaskId);
            break;
        default:/*from   w w  w  .  j  av a  2s .co  m*/
            LOGGER.warn("Cuckoo: error deleting task data (unknown status code: " + status + "), task: "
                    + cuckooTaskId);
        }
    } catch (CuckooException e) {
        LOGGER.warn("Cuckoo: error deleting task data: " + e.getMessage() + ", task: " + cuckooTaskId, e);
    } catch (IOException e) {
        LOGGER.warn("Error closing connection while deleting task data for task: " + cuckooTaskId, e);
    }
}

From source file:slash.navigation.rest.HttpRequest.java

public boolean isNotFound() throws IOException {
    return getResult() == HttpStatus.SC_NOT_FOUND;
}

From source file:terrastore.integration.IntegrationTest.java

@Test
public void testGetNotFound() throws Exception {
    String bucket = UUID.randomUUID().toString();

    GetMethod getValue = makeGetMethod(NODE1_PORT, bucket + "/value");
    HTTP_CLIENT.executeMethod(getValue);
    assertEquals(HttpStatus.SC_NOT_FOUND, getValue.getStatusCode());
}