Example usage for java.net HttpURLConnection HTTP_NOT_FOUND

List of usage examples for java.net HttpURLConnection HTTP_NOT_FOUND

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_NOT_FOUND.

Prototype

int HTTP_NOT_FOUND

To view the source code for java.net HttpURLConnection HTTP_NOT_FOUND.

Click Source Link

Document

HTTP Status-Code 404: Not Found.

Usage

From source file:org.sonar.batch.repository.DefaultProjectRepositoriesLoader.java

private static boolean shouldThrow(Exception e) {
    for (Throwable t : Throwables.getCausalChain(e)) {
        if (t instanceof HttpException) {
            HttpException http = (HttpException) t;
            return http.code() != HttpURLConnection.HTTP_NOT_FOUND;
        }/*from  ww w .  ja  v a2s. com*/
        if (t instanceof MessageException) {
            return true;
        }
    }

    return false;
}

From source file:poisondog.vfs.http.HttpMission.java

@Override
public Integer execute(HttpMethod method) throws FileNotFoundException, IOException {
    if (!mUsername.isEmpty()) {
        mClient.setHttpClient(create(mUsername, mPassword));
    }//from   w ww.java  2 s .  c  om
    mClient.getHttpConnectionManager().getParams().setSoTimeout(20000);

    int status = mClient.executeMethod(method);
    if (status == HttpURLConnection.HTTP_NOT_FOUND || status == HttpURLConnection.HTTP_GONE) {
        throw new FileNotFoundException();
    }
    return status;
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from/*from w  ww  .  j  av  a2s.  c  o m*/
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotFoundGetTTL() throws IOException {
    try {/*from  ww  w.  j a  v  a2 s .  c  o  m*/
        streamClient.getTTL(TestUtils.NOT_FOUND_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getStatusCode());
    }
}

From source file:org.apache.myfaces.custom.skin.webapp.CachingStyleSheetLoader.java

/**
 * Loads the stylesheet only if the file has been modified or
 * the cache has expired.//from w w w.ja  v  a 2 s . c  om
 */
public void loadStyleSheet(HttpServletRequest req, HttpServletResponse resp, ServletConfig config)
        throws IOException {
    File file = getFile(req, config);
    if (file != null && file.exists()) {
        if (isFileModified(file, req)) {
            long lastModified = file.lastModified();
            defineCaching(req, resp, lastModified);
            writeFile(file, resp);
        } else {
            resp.setStatus(HttpURLConnection.HTTP_NOT_MODIFIED);
            return;
        }
    } else {
        String requestURI = req.getRequestURI();
        String filename = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        log.error("The resource " + filename + " was not found.");

        resp.setStatus(HttpURLConnection.HTTP_NOT_FOUND, filename);
        return;
    }
}

From source file:org.betaconceptframework.astroboa.resourceapi.locator.RepositoryLocator.java

@Path("{repositoryId}")
public ResourceLocator connectToAstroboaRepository(@HeaderParam("Authorization") String authorization,
        @PathParam("repositoryId") String repositoryId, @Context ServletContext servletContext) {

    if (StringUtils.isBlank(repositoryId)) {
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }//  w  w  w .  j av  a2s. c o  m

    try {

        AstroboaClient astroboaClient = null;

        long start = System.currentTimeMillis();

        if (authorization != null) {

            String cacheKey = authorization + repositoryId;

            astroboaClient = AstroboaClientCache.Instance.get(cacheKey);

            if (astroboaClient == null) {
                String encodedUsernamePass = authorization.substring(5);
                String usernamePass = Base64.base64Decode(encodedUsernamePass);

                String[] usernamePassSplitted = usernamePass.split(":");

                if (usernamePassSplitted.length == 2) {
                    astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION);
                    AstroboaCredentials credentials = new AstroboaCredentials(usernamePassSplitted[0],
                            usernamePassSplitted[1]);
                    astroboaClient.login(repositoryId, credentials);

                    astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, cacheKey);

                } else {
                    logger.error(
                            "provided authorization in header (BASIC AUTH) cannot be decoded to username and password. Encoded Authorization String found in header is: "
                                    + authorization);
                    throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
                }
            }
        } else { // login as anonymous

            final String anonymousCacheKey = repositoryId + IdentityPrincipal.ANONYMOUS;

            astroboaClient = AstroboaClientCache.Instance.get(anonymousCacheKey);

            if (astroboaClient == null) {

                astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION);

                String permanentKey = retrievePermanentKeyForAnonymousUser(repositoryId, servletContext);

                astroboaClient.loginAsAnonymous(repositoryId, permanentKey);

                astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, anonymousCacheKey);

            }
        }

        logger.debug("Retrieve/Create astroboa repository client {} in  {}",
                System.identityHashCode(astroboaClient),
                DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));

        return new ResourceLocator(astroboaClient);

    } catch (CmsInvalidPasswordException e) {
        logger.error("Login to Astroboa Repository was not successfull");
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("A problem occured while connecting repository client to Astroboa Repository", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }
}

From source file:org.apparatus_templi.web.handler.SettingsHandler.java

@Override
public void handle(HttpExchange exchange) throws IOException {
    Log.d(TAG, "received request from " + exchange.getRemoteAddress() + " " + exchange.getRequestMethod()
            + ": '" + exchange.getRequestURI() + "'");
    com.sun.net.httpserver.Headers headers = exchange.getResponseHeaders();
    headers.add("Content-Type", "text/html");

    byte[] response = getResponse();
    if (response != null) {
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
        exchange.getResponseBody().write(response);
    } else {// w ww  . ja  v  a  2  s.  c  o  m
        response = PageGenerator.get404ErrorPage("index.html").getBytes();
        exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, response.length);
        exchange.getResponseBody().write(response);
    }
    exchange.close();
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void approach(String username, String carName) {

    String servlet = "Approach";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("carName", carName));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_ACCEPTED, GodotMessage.Core.DRIVER_UPDATED);
    mMessageMap.append(HttpURLConnection.HTTP_CREATED, GodotMessage.Core.MESSAGE_SENT);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Core.CAR_NOT_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();//from ww w  . j a va2  s.c  o m

}

From source file:org.hyperic.hq.plugin.apache.ApacheStatusCollector.java

public void collect() {
    super.collect();
    //ApacheServerDetector will auto-configure for localhost:80/server-status
    //if GET /server-status returns 404, assume httpd itself is available
    MetricValue value = getResult().getMetricValue(ATTR_RESPONSE_CODE);
    if ((value != null) && (value.getValue() == HttpURLConnection.HTTP_NOT_FOUND)) {
        setAvailability(true);/* w  ww .ja  v  a2 s. c  om*/
        String path = getProperties().getProperty(PROP_PATH);
        log.warn(METHOD_GET + " " + path + ": " + getMessage());
    }
}

From source file:com.example.appengine.UrlFetchServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    String id = req.getParameter("id");
    String text = req.getParameter("text");

    if (id == null || text == null || id == "" || text == "") {
        req.setAttribute("error", "invalid input");
        req.getRequestDispatcher("/main.jsp").forward(req, resp);
        return;//from  ww w  . ja v a2s .  c  o m
    }

    JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text);

    // [START complex]
    URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
    writer.close();

    int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
    if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
        req.setAttribute("error", "");
        StringBuffer response = new StringBuffer();
        String line;

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        req.setAttribute("response", response.toString());
    } else {
        req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    // [END complex]
    req.getRequestDispatcher("/main.jsp").forward(req, resp);
}