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.infoscoop.web.MultiRssServlet.java

private void mergeRssAnd2JSON(HttpServletRequest request, HttpServletResponse response, String uid,
        String widgetId, int pageSize, NodeList urlList) throws Exception {

    try {// w  ww.j  a  va 2s. c  om
        RssJsonResultBuilder resultBuilder = new SortedRssJsonResultBuilder(pageSize);

        String dateTimeFormat = request.getHeader("X-IS-DATETIMEFORMAT");
        if (dateTimeFormat != null) {
            dateTimeFormat = URLDecoder.decode(dateTimeFormat, "UTF-8");
        }
        String freshTime = request.getHeader("X-IS-FRESHTIME");
        String maxCountString = request.getHeader("X-IS-RSSMAXCOUNT");
        int maxCount = 1000;
        if (maxCountString != null) {
            try {
                int paramMaxCount = Integer.parseInt(maxCountString);
                if (paramMaxCount >= 0) {
                    maxCount = paramMaxCount;
                }
            } catch (NumberFormatException e) {
                log.warn("rssmaxcount \"" + maxCountString + "\" isn't integer value.");
            }
        }

        // Norrowing
        String titleFilter = request.getHeader("X-IS-TITLEFILTER");
        if (titleFilter != null)
            titleFilter = URLDecoder.decode(titleFilter, "UTF-8");
        String creatorFilter = request.getHeader("X-IS-CREATORFILTER");
        if (creatorFilter != null)
            creatorFilter = URLDecoder.decode(creatorFilter, "UTF-8");
        String categoryFilter = request.getHeader("X-IS-CATEGORYFILTER");
        if (categoryFilter != null)
            categoryFilter = URLDecoder.decode(categoryFilter, "UTF-8");

        int DEFAULT_TIMEOUT = 15 * 1000;

        boolean modified = false;
        Map cacheHeaders = new HashMap();
        Map errorMap = new HashMap();
        List siteCacheHeaders = new ArrayList();
        for (int i = 0; i < urlList.getLength(); i++) {
            Element rssEl = (Element) urlList.item(i);
            String url = rssEl.getAttribute("url");

            ProxyRequest proxyRequest = new ProxyRequest(url, "NoOperation");
            proxyRequest.setLocales(request.getLocales());
            proxyRequest.setPortalUid(uid);

            int timeout = request.getIntHeader("MSDPortal-Timeout") - 1000;
            proxyRequest.setTimeout((timeout > 0) ? timeout : DEFAULT_TIMEOUT);
            //proxyRequest.setTimeout(timeout);

            proxyRequest.addIgnoreHeader("user-agent");
            proxyRequest.addIgnoreHeader("X-IS-DATETIMEFORMAT");
            proxyRequest.addIgnoreHeader("X-IS-FRESHTIME");
            proxyRequest.addIgnoreHeader("X-IS-REFRESH");
            proxyRequest.addIgnoreHeader("X-IS-RSSMAXCOUNT");
            proxyRequest.addIgnoreHeader("X-IS-PAGESIZE");

            Enumeration headers = request.getHeaderNames();
            while (headers.hasMoreElements()) {
                String headerName = (String) headers.nextElement();
                proxyRequest.putRequestHeader(headerName, request.getHeader(headerName));
            }

            NodeList rssChildNodes = rssEl.getElementsByTagName("header");
            for (int j = 0; j < rssChildNodes.getLength(); j++) {
                Element header = (Element) rssChildNodes.item(j);
                if (header.getFirstChild() != null) {
                    String name = header.getAttribute("name");
                    String value = header.getFirstChild().getNodeValue();
                    if (name == null || name.trim().length() == 0 || value == null
                            || value.trim().length() == 0)
                        continue;

                    proxyRequest.putRequestHeader(name, value);
                }
            }

            int statusCode = 0;
            String methodType = rssEl.getAttribute("method");
            try {
                if ("post".equals(methodType)) {
                    statusCode = proxyRequest.executePost();
                } else {
                    statusCode = proxyRequest.executeGet();
                }
            } catch (SocketTimeoutException ex) {
                log.error("url: [" + url + "] socket timeout.", ex);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_TIMEOUT));
            } catch (ConnectTimeoutException ex) {
                log.error("url: [" + url + "] connection timeout.", ex);
                errorMap.put(url, new Integer(500));
            } catch (SocketException ex) {
                log.error("url: [" + url + "] socket error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (IOException ex) {
                log.error("url: [" + url + "] I/O error.", ex);
                errorMap.put(url, new Integer(HttpStatus.SC_NOT_FOUND));
            } catch (Exception ex) {
                log.error("url: [" + url + "]" + ex.getMessage(), ex);
                errorMap.put(url, new Integer(500));
            }

            BufferedInputStream bis = null;
            if (errorMap.containsKey(url)) {
                // nothing

            } else if (statusCode == 204) {
                log.warn("url:[" + url + "] is no content #" + statusCode);
                modified = true;
            } else if (statusCode == 304) {
                log.warn("url:[" + url + "] is not modified #" + statusCode);
            } else if (statusCode != 200) {
                log.error("url:[" + url + "] had error status code #" + statusCode);
                errorMap.put(url, new Integer(statusCode));
            } else {
                log.info("url:[" + url + "] is succed #" + statusCode);

                try {
                    modified = true;

                    bis = new BufferedInputStream(proxyRequest.getResponseBody());

                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte[] buf = new byte[10240];
                    int c;
                    while ((c = bis.read(buf)) != -1) {
                        baos.write(buf, 0, c);
                        baos.flush();
                    }
                    bis.close();

                    byte[] data = baos.toByteArray();
                    baos.close();

                    //RssCacheDAO.newInstance().insertCache(uid, widgetId+url, -1,data );

                    Map responseHeaders = proxyRequest.getResponseHeaders();
                    String lastModifiedName = "Last-Modified".toLowerCase();
                    if (responseHeaders.containsKey(lastModifiedName)) {
                        siteCacheHeaders.add(lastModifiedName);
                        siteCacheHeaders.add(responseHeaders.get(lastModifiedName));
                    }

                    String etagName = "ETag".toLowerCase();
                    if (responseHeaders.containsKey(etagName)) {
                        siteCacheHeaders.add(etagName);
                        siteCacheHeaders.add(responseHeaders.get(etagName));
                    }

                    if (siteCacheHeaders.size() > 0) {
                        cacheHeaders.put(url, siteCacheHeaders.toArray());
                        siteCacheHeaders.clear();
                    }

                    bis = new BufferedInputStream(new ByteArrayInputStream(data));
                } catch (IOException ex) {
                    log.error("rss reading " + url + " is failed.", ex);
                    cacheHeaders.remove(url);
                    errorMap.put(url, new Integer(500));

                    bis.close();
                    bis = null;
                }
            }

            if (bis == null)
                continue;

            RssHandler handler;

            boolean isAtom = RssFilter.isAtom(bis);

            XMLFilter.skipEmptyLine(bis);
            if (isAtom) {
                handler = new AtomHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            } else {
                handler = new RssHandler(resultBuilder, dateTimeFormat, freshTime, maxCount, titleFilter,
                        creatorFilter, categoryFilter, i);
            }

            try {
                XMLReader reader = factory.newSAXParser().getXMLReader();
                reader.setEntityResolver(NoOpEntityResolver.getInstance());
                reader.setContentHandler(handler);
                reader.parse(new InputSource(bis));
            } catch (SAXException e) {
                log.info("Parsing rss " + url + " is failed.", e);
                cacheHeaders.remove(url);
                errorMap.put(url, new Integer(HttpStatusCode.MSD_SC_CONTENT_PARSE_ERROR));
            }
        }

        if (!modified && errorMap.isEmpty()) {
            log.warn("multi rss is not modified.");
            response.setStatus(304);

            return;
        } else {
            try {
                long freshTimeLong = new Date().getTime();
                if (freshTime != null)
                    freshTimeLong = Long.parseLong(freshTime.trim());
                setOldData(resultBuilder, uid, widgetId, freshTimeLong, titleFilter, creatorFilter,
                        categoryFilter);

            } catch (NumberFormatException e) {
                log.error("", e);
            }

            //}

            int pageCount = resultBuilder.getPageCount();
            // We create the result cash by all means.
            //if( pageCount > 1 ) {
            for (int pageNum = 0; pageNum < pageCount; pageNum++) {
                RssCacheDAO.newInstance().insertCache(uid, widgetId, pageNum, resultBuilder.getResult(pageNum));
            }
            //}
        }

        response.addHeader("Content-Type", "text/plain; charset=UTF-8");

        String result = resultBuilder.getResult();

        if (!errorMap.isEmpty()) {
            JSONObject errors = new JSONObject(errorMap);
            result = "{errors:" + errors.toString() + "," + result.substring(result.indexOf("{") + 1);
        }
        if (!cacheHeaders.isEmpty()) {
            StringBuffer cacheHeadersBuf = new StringBuffer();
            cacheHeadersBuf.append("cacheHeaders : {");
            for (Iterator keys = cacheHeaders.keySet().iterator(); keys.hasNext();) {
                String url = (String) keys.next();
                Object[] headers = (Object[]) cacheHeaders.get(url);

                cacheHeadersBuf.append("\"").append(url).append("\" : {");
                for (int i = 0; i < headers.length; i += 2) {
                    cacheHeadersBuf.append("\"").append(headers[i]).append("\"");
                    cacheHeadersBuf.append(" : '").append(headers[i + 1]).append("'");
                    if (i + 2 < headers.length)
                        cacheHeadersBuf.append(",");
                }
                cacheHeadersBuf.append("}");
                if (keys.hasNext())
                    cacheHeadersBuf.append(",");
            }
            cacheHeadersBuf.append("}");

            result = "{" + cacheHeadersBuf.toString() + "," + result.substring(result.indexOf("{") + 1);
        }

        response.setContentLength(result.getBytes("UTF-8").length);

        OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
        try {
            out.write(result);

            out.flush();
        } catch (SocketException ex) {
            // ignore client abort exception
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }
    } catch (Exception e) {
        log.error("unexpected error occurred.", e);
        response.sendError(500, e.getMessage());
    }

}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldAcceptHttpConnexionAndReturnNotFoundResource() throws Exception {
    createAndLaunchLiveReloadServer(true);
    // operation/*w  ww  .j  av  a  2 s  . co m*/
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(unknowDocumentLocation);
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_NOT_FOUND);
}

From source file:org.jboss.tools.livereload.internal.server.jetty.LiveReloadServerTestCase.java

@Test
public void shouldNotInjectLiveReloadScriptInUnknownHtmlPage() throws Exception {
    createAndLaunchLiveReloadServer(false);
    // operation//from  w ww.j  a va 2  s  .  c  o m
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(unknowDocumentLocation);
    method.addRequestHeader("Accept", "text/css");
    int status = client.executeMethod(method);
    // verification
    assertThat(status).isEqualTo(HttpStatus.SC_NOT_FOUND);
}

From source file:org.jetbrains.tfsIntegration.exceptions.TfsExceptionManager.java

public static TfsException createHttpTransportErrorException(int errorCode, AxisFault axisFault) {
    switch (errorCode) {
    case HttpStatus.SC_UNAUTHORIZED:
        return new UnauthorizedException(axisFault);
    case HttpStatus.SC_BAD_GATEWAY:
        return new HostNotFoundException(axisFault);
    case HttpStatus.SC_NOT_FOUND:
        return new HostNotApplicableException(axisFault);
    case HttpStatus.SC_FORBIDDEN:
        return new ForbiddenException(axisFault);
    case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
        return new TfsException(TFSBundle.message("proxy.auth.failed"));
    default:/*from  w  w  w .  j  a  v  a 2 s .  c o  m*/
        return new ConnectionFailedException(axisFault, errorCode);
    }
}

From source file:org.jfrog.bamboo.admin.ArtifactoryConfigServlet.java

/**
 * Requires to be provided with a server ID (param name is serverId).<br> If given with the parameter
 * "deployableRepos=true", it will return the list of deployable repositories for the server with the given ID.<br>
 * If no other parameter is provided, the server configuration of the given ID will be returned.<br> All successful
 * responses are returned in JSON format.
 *///  w ww.j  a  va  2s .com
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String serverIdValue = req.getParameter("serverId");
    if (StringUtils.isBlank(serverIdValue)) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a server ID.");
        log.error("Unable to retrieve server configuration information. No server ID was provided.");
        return;
    }

    long serverId;
    try {
        serverId = Long.parseLong(serverIdValue);
    } catch (NumberFormatException e) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a valid long-type server ID.");
        log.error("Unable to retrieve server configuration information. An invalid server ID was provided ("
                + serverIdValue + ").");
        return;
    }

    ServerConfig serverConfig = serverConfigManager.getServerConfigById(serverId);
    if (serverConfig == null) {
        resp.sendError(HttpStatus.SC_NOT_FOUND,
                "Could not find an Artifactory server configuration with the ID " + serverId + ".");
        log.error("Unable to retrieve server configuration. No configuration was found with the ID " + serverId
                + ".");
        return;
    }

    String deployableReposValue = req.getParameter("deployableRepos");
    String resolvingReposValue = req.getParameter("resolvingRepos");
    if (StringUtils.isNotBlank(deployableReposValue) && Boolean.valueOf(deployableReposValue)) {
        List<String> deployableRepoList = serverConfigManager.getDeployableRepos(serverId, req, resp);
        returnJsonObject(resp, deployableRepoList);
    } else if (StringUtils.isNotBlank(resolvingReposValue) && Boolean.valueOf(resolvingReposValue)) {
        List<String> resolvingRepoList = serverConfigManager.getResolvingRepos(serverId, req, resp);
        returnJsonObject(resp, resolvingRepoList);
    } else {
        returnJsonObject(resp, serverConfig);
    }
}

From source file:org.jfrog.bamboo.admin.BuildServlet.java

/**
 * Requires to be provided with a build key (param name is buildKey).<br> Returns the full name of the build with
 * the given key./*from   ww  w .  j  a  v  a  2  s.c  o m*/
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String buildKeyValue = req.getParameter(ConstantValues.BUILD_SERVLET_KEY_PARAM);
    if (StringUtils.isBlank(buildKeyValue)) {
        resp.sendError(HttpStatus.SC_BAD_REQUEST, "Please provide a build key.");
        log.error("Unable to retrieve build information. No build key was provided.");
        return;
    }

    Plan plan = planManager.getPlanByKey(buildKeyValue);

    if (plan == null) {
        resp.sendError(HttpStatus.SC_NOT_FOUND, "Could not find plan with the key " + buildKeyValue + ".");
        log.error(
                "Unable to retrieve build information. No plan was found with the key " + buildKeyValue + ".");
        return;
    }

    PrintWriter writer = null;
    try {
        writer = resp.getWriter();
        writer.write(plan.getName());
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:org.jfrog.bamboo.builder.BaseBuildInfoHelper.java

/**
 * Executes the given HTTP method//from  w w  w  . jav  a  2  s .co  m
 *
 * @param requestUrl Full request URL
 * @param getMethod  HTTP GET method
 */
private void executeMethod(String requestUrl, GetMethod getMethod) throws IOException {
    int responseCode = httpClient.executeMethod(getMethod);
    if (responseCode == HttpStatus.SC_NOT_FOUND) {
        throw new IOException("Unable to find requested resource: " + requestUrl);
    } else if (responseCode != HttpStatus.SC_OK) {
        throw new IOException("Failed to retrieve requested resource: " + requestUrl + ". Response code: "
                + responseCode + ", Message: " + getMethod.getStatusText());
    }
}

From source file:org.jfrog.bamboo.builder.BuilderDependencyHelper.java

private void downloadDependencies(String dependencyBaseUrl, File builderDependencyDir, String dependencyKey)
        throws IOException {
    HttpClient client = new HttpClient();
    String dependencyFileName = PluginProperties.getPluginProperty(dependencyKey);
    String dependencyUrl = dependencyBaseUrl + dependencyFileName;
    GetMethod getMethod = new GetMethod(dependencyUrl);

    InputStream responseBodyAsStream = null;
    FileOutputStream fileOutputStream = null;

    try {/*from   w w  w  .  j a v a 2  s .co  m*/
        int responseStatus = client.executeMethod(getMethod);
        if (responseStatus == HttpStatus.SC_NOT_FOUND) {
            throw new IOException("Unable to find required dependency: " + dependencyUrl);
        } else if (responseStatus != HttpStatus.SC_OK) {
            throw new IOException("Error while requesting required dependency: " + dependencyUrl + ". Status: "
                    + responseStatus + ", Message: " + getMethod.getStatusText());
        }

        responseBodyAsStream = getMethod.getResponseBodyAsStream();
        if (responseBodyAsStream == null) {
            throw new IOException(
                    "Requested dependency: " + dependencyUrl + ", but received a null response stream.");
        }

        File file = new File(builderDependencyDir, dependencyFileName);
        if (!file.isFile()) {
            fileOutputStream = new FileOutputStream(file);
            IOUtils.copy(responseBodyAsStream, fileOutputStream);
        }
    } finally {
        getMethod.releaseConnection();
        IOUtils.closeQuietly(responseBodyAsStream);
        IOUtils.closeQuietly(fileOutputStream);
    }
}

From source file:org.kaloz.datafeed.processor.infrastructure.acl.ProcessorConverter.java

public InstrumentPriceResponseMessage toInstrumentPriceResponseMessage(
        Optional<InstrumentPrice> priceOptional) {

    InstrumentPriceResponseMessage instrumentPriceResponseMessage = new InstrumentPriceResponseMessage();
    if (priceOptional.isPresent()) {
        InstrumentPrice instrumentPrice = priceOptional.get();
        instrumentPriceResponseMessage.setPrice(getInstrumentPriceResource(instrumentPrice));
    } else {//from w  w w  .  java  2  s .com
        instrumentPriceResponseMessage.setErrorCode(HttpStatus.SC_NOT_FOUND);
    }

    return instrumentPriceResponseMessage;
}

From source file:org.kaloz.datafeed.processor.infrastructure.acl.ProcessorConverterTest.java

@Test
public void testToInstrumentPriceResponseMessageNotFound() throws ParseException {

    Optional<InstrumentPrice> instrumentPriceOptional = Optional.absent();

    InstrumentPriceResponseMessage result = obj.toInstrumentPriceResponseMessage(instrumentPriceOptional);

    assertNotNull(result);//from ww  w .  ja va2  s.  c  o  m

    assertNull(result.getPrice());
    assertEquals(HttpStatus.SC_NOT_FOUND, result.getErrorCode(), 0);
}