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:Main.java

public static void main(String[] argv) throws Exception {
    HttpURLConnection.setFollowRedirects(false);
    HttpURLConnection con = (HttpURLConnection) new URL("http://www.google.coom").openConnection();
    con.setRequestMethod("HEAD");
    System.out.println(con.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND);
}

From source file:poisondog.net.http.HttpResponseTest.java

@Test
public void testResponseCode() throws Exception {
    HttpResponse response = new HttpResponse(HttpURLConnection.HTTP_OK);
    Assert.assertEquals(200, response.getResponseCode());
    response = new HttpResponse(HttpURLConnection.HTTP_NOT_FOUND);
    Assert.assertEquals(404, response.getResponseCode());
}

From source file:io.jare.tk.TkAppFallback.java

/**
 * Authenticated.//  w w  w  .j  ava  2 s  . c  o m
 * @param take Takes
 * @return Authenticated takes
 */
private static Take make(final Take take) {
    return new TkFallback(take,
            new FbChain(
                    new FbStatus(HttpURLConnection.HTTP_NOT_FOUND,
                            new RsWithStatus(new RsText("page not found"), HttpURLConnection.HTTP_NOT_FOUND)),
                    new FbStatus(HttpURLConnection.HTTP_BAD_REQUEST,
                            new RsWithStatus(new RsText("bad request"), HttpURLConnection.HTTP_BAD_REQUEST)),
                    req -> new Opt.Single<>(TkAppFallback.fatal(req))));
}

From source file:com.delaroystudios.weatherapp.utilities.OpenWeatherJsonUtils.java

/**
 * This method parses JSON from a web response and returns an array of Strings
 * describing the weather over various days from the forecast.
 * <p/>/*from   ww  w  . j a v a2 s . c  o m*/
 * Later on, we'll be parsing the JSON into structured data within the
 * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For
 * now, we just convert the JSON into human-readable strings.
 *
 * @param forecastJsonStr JSON response from server
 *
 * @return Array of Strings describing weather data
 *
 * @throws JSONException If JSON data cannot be properly parsed
 */
public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr)
        throws JSONException {

    /* Weather information. Each day's forecast info is an element of the "list" array */
    final String OWM_LIST = "list";

    /* All temperatures are children of the "temp" object */
    final String OWM_TEMPERATURE = "temp";

    /* Max temperature for the day */
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";

    final String OWM_MESSAGE_CODE = "cod";

    /* String array to hold each day's weather String */
    String[] parsedWeatherData = null;

    JSONObject forecastJson = new JSONObject(forecastJsonStr);

    /* Is there an error? */
    if (forecastJson.has(OWM_MESSAGE_CODE)) {
        int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);

        switch (errorCode) {
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            /* Location invalid */
            return null;
        default:
            /* Server probably down */
            return null;
        }
    }

    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    parsedWeatherData = new String[weatherArray.length()];

    long localDate = System.currentTimeMillis();
    long utcDate = WeatherDateUtils.getUTCDateFromLocal(localDate);
    long startDay = WeatherDateUtils.normalizeDate(utcDate);

    for (int i = 0; i < weatherArray.length(); i++) {
        String date;
        String highAndLow;

        /* These are the values that will be collected */
        long dateTimeMillis;
        double high;
        double low;
        String description;

        /* Get the JSON object representing the day */
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        /*
         * We ignore all the datetime values embedded in the JSON and assume that
         * the values are returned in-order by day (which is not guaranteed to be correct).
         */
        dateTimeMillis = startDay + WeatherDateUtils.DAY_IN_MILLIS * i;
        date = WeatherDateUtils.getFriendlyDateString(context, dateTimeMillis, false);

        /*
         * Description is in a child array called "weather", which is 1 element long.
         * That element also contains a weather code.
         */
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        /*
         * Temperatures are sent by Open Weather Map in a child object called "temp".
         *
         * Editor's Note: Try not to name variables "temp" when working with temperature.
         * It confuses everybody. Temp could easily mean any number of things, including
         * temperature, temporary and is just a bad variable name.
         */
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);
        highAndLow = WeatherUtils.formatHighLows(context, high, low);

        parsedWeatherData[i] = date + " - " + description + " - " + highAndLow;
    }

    return parsedWeatherData;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Check if specified dataset already exists on server
 * //from   ww  w  .  j  av  a  2 s . c o  m
 * @param dataSetName
 * @return boolean true if the dataset already exits, false if not
 * @throws IOException
 * @throws HttpException
 */
public static boolean chechIfExist(String dataSetName) throws IOException, HttpException {
    boolean exists = false;
    URL url = new URL(HOST + "/$/datasets/" + dataSetName);
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("GET");

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        exists = true;
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
    return exists;
}

From source file:com.ratebeer.android.api.command.SetEventAttendanceCommand.java

@Override
protected void makeRequest(ApiConnection apiConnection) throws ApiException {
    ApiConnection.ensureLogin(apiConnection, getUserSettings());
    apiConnection.post("http://www.ratebeer.com/eventprocess-attend.asp",
            Arrays.asList(new BasicNameValuePair("EventID", Integer.toString(eventId)),
                    new BasicNameValuePair("IsGoing", isGoing ? "1" : "0")),
            // Note that we get an HTTP $)$ response even when the request is successfull...
            HttpURLConnection.HTTP_NOT_FOUND);
}

From source file:org.jboss.test.web.test.RemoteClassloadingServiceUnitTestCase.java

/**
 * JBAS-4540, don't leak installation directory info
 * through the classloading service.//from ww w.  j  av a  2s.  c om
 */
public void testHttpRequestRevealInstallationDirectory() throws Exception {
    URL url = new URL(baseURL + "org.jboss.web.WebServer.class");
    HttpMethodBase request = HttpUtils.accessURL(url, null, HttpURLConnection.HTTP_NOT_FOUND);
    String statusText = request.getStatusText();

    if (statusText.indexOf(".jar") > 0)
        fail("Status text reveals installation directory information: " + statusText);
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.utils.GerritPluginChecker.java

/**
 * Given a status code, decode its status.
 * @param statusCode HTTP code// ww  w  . j  ava  2  s.c o  m
 * @param pluginName plugin that was checked.
 * @return true/false if installed or not.
 */
private static boolean decodeStatus(int statusCode, String pluginName) {
    switch (statusCode) {
    case HttpURLConnection.HTTP_OK:
        logger.info(Messages.PluginInstalled(pluginName));
        return true;
    case HttpURLConnection.HTTP_NOT_FOUND:
        logger.info(Messages.PluginNotInstalled(pluginName));
        return false;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        logger.warn(
                Messages.PluginHttpConnectionUnauthorized(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    case HttpURLConnection.HTTP_FORBIDDEN:
        logger.warn(Messages.PluginHttpConnectionForbidden(pluginName, Messages.HttpConnectionUnauthorized()));
        return false;
    default:
        logger.warn(Messages.PluginHttpConnectionGeneralError(pluginName,
                Messages.HttpConnectionError(statusCode)));
        return false;
    }
}

From source file:com.example.android.sunshine.utilities.OpenWeatherJsonUtils.java

/**
 * This method parses JSON from a web response and returns an array of Strings
 * describing the weather over various days from the forecast.
 * <p/>/*from   www .j a v a  2  s . c o  m*/
 * Later on, we'll be parsing the JSON into structured data within the
 * getFullWeatherDataFromJson function, leveraging the data we have stored in the JSON. For
 * now, we just convert the JSON into human-readable strings.
 *
 * @param forecastJsonStr JSON response from server
 *
 * @return Array of Strings describing weather data
 *
 * @throws JSONException If JSON data cannot be properly parsed
 */
public static String[] getSimpleWeatherStringsFromJson(Context context, String forecastJsonStr)
        throws JSONException {

    String[] parsedWeatherData;

    JSONObject forecastJson = new JSONObject(forecastJsonStr);

    /* Is there an error? */
    if (forecastJson.has(OWM_MESSAGE_CODE)) {
        int errorCode = forecastJson.getInt(OWM_MESSAGE_CODE);

        switch (errorCode) {
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            /* Location invalid */
            return null;
        default:
            /* Server probably down */
            return null;
        }
    }

    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    parsedWeatherData = new String[weatherArray.length()];

    long startDay = SunshineDateUtils.getNormalizedUtcDateForToday();

    for (int i = 0; i < weatherArray.length(); i++) {
        String date;
        String highAndLow;

        /* These are the values that will be collected */
        long dateTimeMillis;
        double high;
        double low;

        int weatherId;
        String description;

        /* Get the JSON object representing the day */
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        /*
         * We ignore all the datetime values embedded in the JSON and assume that
         * the values are returned in-order by day (which is not guaranteed to be correct).
         */
        dateTimeMillis = startDay + SunshineDateUtils.DAY_IN_MILLIS * i;
        date = SunshineDateUtils.getFriendlyDateString(context, dateTimeMillis, false);

        /*
         * Description is in a child array called "weather", which is 1 element long.
         * That element also contains a weather code.
         */
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);

        weatherId = weatherObject.getInt(OWM_WEATHER_ID);
        description = SunshineWeatherUtils.getStringForWeatherCondition(context, weatherId);

        /*
         * Temperatures are sent by Open Weather Map in a child object called "temp".
         *
         * Editor's Note: Try not to name variables "temp" when working with temperature.
         * It confuses everybody. Temp could easily mean any number of things, including
         * temperature, temporary and is just a bad variable name.
         */
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        high = temperatureObject.getDouble(OWM_MAX);
        low = temperatureObject.getDouble(OWM_MIN);
        highAndLow = SunshineWeatherUtils.formatHighLows(context, high, low);

        parsedWeatherData[i] = date + " - " + description + " - " + highAndLow;
    }

    return parsedWeatherData;
}

From source file:org.jboss.test.web.test.CustomErrorsUnitTestCase.java

/** Test that the custom 404 error page is seen
 * /*from   w  w w  .  j av a 2  s.c om*/
 * @throws Exception
 */
public void test404Error() throws Exception {
    log.info("+++ test404Error");
    int errorCode = HttpURLConnection.HTTP_NOT_FOUND;
    URL url = new URL(baseURLNoAuth + "error-producer/ErrorGeneratorServlet?errorCode=" + errorCode);
    HttpMethodBase request = HttpUtils.accessURL(url, "Realm", HttpURLConnection.HTTP_NOT_FOUND);
    Header errors = request.getResponseHeader("X-CustomErrorPage");
    log.info("X-CustomErrorPage: " + errors);
    assertTrue("X-CustomErrorPage(" + errors + ") is 404.jsp", errors.getValue().equals("404.jsp"));
}