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.wso2.carbon.registry.app.RemoteRegistry.java

public Collection get(String path, int start, int pageSize) throws RegistryException {
    AbderaClient abderaClient = new AbderaClient(abdera);
    ClientResponse clientResponse = abderaClient.get(
            baseURI + "/atom" + encodeURL(path) + "?start=" + start + "&pageLen=" + pageSize,
            getAuthorization());//from   www  . j a v  a 2 s .co m
    if (clientResponse.getType() == Response.ResponseType.CLIENT_ERROR
            || clientResponse.getType() == Response.ResponseType.SERVER_ERROR) {
        if (clientResponse.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
            abderaClient.teardown();
            throw new ResourceNotFoundException(path);
        }
        abderaClient.teardown();
        throw new RegistryException(clientResponse.getStatusText());
    }
    Element introspection = clientResponse.getDocument().getRoot();
    if (!(introspection instanceof Feed)) {
        abderaClient.teardown();
        throw new RegistryException("Got " + introspection.getQName() + " when expecting <feed>!");
    }
    CollectionImpl resource;
    // This is a collection
    Feed feed = (Feed) introspection;
    String state = feed.getSimpleExtension(new QName(APPConstants.NAMESPACE, APPConstants.NAMESPACE_STATE));
    if (state != null && state.equals("Deleted")) {
        abderaClient.teardown();
        throw new ResourceNotFoundException(path);
    }
    resource = createResourceFromFeed(feed);
    abderaClient.teardown();
    return resource;
}

From source file:com.netflix.genie.server.resources.ClusterConfigResource.java

/**
 * Delete all clusters from database./*from  w  w  w  .  j  ava2s.  c om*/
 *
 * @return All The deleted clusters
 * @throws GenieException For any error
 */
@DELETE
@ApiOperation(value = "Delete all clusters", notes = "Delete all available clusters and get them back.", response = Cluster.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public List<Cluster> deleteAllClusters() throws GenieException {
    LOG.info("called");
    return this.clusterConfigService.deleteAllClusters();
}

From source file:org.openremote.android.test.console.net.ORConnectionTest.java

/**
 * Test non-existent URL path behavior...
 *
 * @throws IOException if connection fails for any reason, see checkURLWithHTTPProtocol javadoc
 *///from w  w  w .j  a  v a 2 s  .c  om
public void testURLConnectionWithWrongURLPath() throws IOException {
    final String NOT_EXIST_TESTURL = "http://controller.openremote.org/test/controller/does/not/exist";

    HttpResponse response = ORConnection.checkURLWithHTTPProtocol(activity, ORHttpMethod.GET, NOT_EXIST_TESTURL,
            NO_HTTP_AUTH);

    assertNotNullResponse(response, NOT_EXIST_TESTURL);

    assertHttpReturnCode(response, HttpURLConnection.HTTP_NOT_FOUND);
}

From source file:com.netflix.genie.server.resources.JobResource.java

/**
 * Kill job based on given job ID./*  www . j  ava 2 s .  co  m*/
 *
 * @param id id for job to kill
 * @return The job that was killed
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete a job", notes = "Delete the job with the id specified.", response = Job.class)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Job killJob(@ApiParam(value = "Id of the job.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called for job id: " + id);
    return this.executionService.killJob(id);
}

From source file:com.netflix.genie.server.resources.CommandConfigResource.java

/**
 * Add new configuration files to a given command.
 *
 * @param id      The id of the command to add the configuration file to. Not
 *                null/empty/blank./*from  w w  w. j ava  2 s . c o  m*/
 * @param configs The configuration files to add. Not null/empty/blank.
 * @return The active configurations for this command.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new configuration files to a command", notes = "Add the supplied configuration files to the command with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> addConfigsForCommand(
        @ApiParam(value = "Id of the command to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to add.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and config " + configs);
    return this.commandConfigService.addConfigsForCommand(id, configs);
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.TopicResource.java

private Response saveTopicSource(String topicSource, String httpMethod, boolean entityIsNew) {

    logger.debug("Want to save a new topic {}", topicSource);

    try {// w ww  .jav a  2  s. c  om

        ImportConfiguration configuration = ImportConfiguration.topic().persist(PersistMode.PERSIST_ENTITY_TREE)
                .build();

        Topic topic = astroboaClient.getImportService().importTopic(topicSource, configuration);

        return ContentApiUtils.createResponseForPutOrPostOfACmsEntity(topic, httpMethod, topicSource,
                entityIsNew);

    } catch (CmsUnauthorizedAccessException e) {
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }
}

From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java

@Test
public void testRawHttpCalls() throws Exception {
    final Server jetty = createJettyServer();
    Context context = new Context();
    context.setContextPath("/foo");
    jetty.setHandler(context);/*w  w w  .j  a v a2 s .  c o m*/
    context.addFilter(new FilterHolder(AFilter.class), "/*", 0);
    context.addServlet(new ServletHolder(PingServlet.class), "/bar");
    try {
        jetty.start();
        URL nonAuthURL = new URL(getJettyURL() + "/foo/bar");
        URL authURL = new URL(getJettyURL() + "/foo/bar?authenticated=foo");

        // unauthenticated access to URL
        HttpURLConnection conn = (HttpURLConnection) nonAuthURL.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());

        // authenticated access to URL
        conn = (HttpURLConnection) authURL.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // unauthenticated access to get delegation token
        URL url = new URL(nonAuthURL.toExternalForm() + "?op=GETDELEGATIONTOKEN");
        conn = (HttpURLConnection) url.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());

        // authenticated access to get delegation token
        url = new URL(authURL.toExternalForm() + "&op=GETDELEGATIONTOKEN&renewer=foo");
        conn = (HttpURLConnection) url.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        ObjectMapper mapper = new ObjectMapper();
        Map map = mapper.readValue(conn.getInputStream(), Map.class);
        String dt = (String) ((Map) map.get("Token")).get("urlString");
        Assert.assertNotNull(dt);

        // delegation token access to URL
        url = new URL(nonAuthURL.toExternalForm() + "?delegation=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // delegation token and authenticated access to URL
        url = new URL(authURL.toExternalForm() + "&delegation=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // renewew delegation token, unauthenticated access to URL
        url = new URL(nonAuthURL.toExternalForm() + "?op=RENEWDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());

        // renewew delegation token, authenticated access to URL
        url = new URL(authURL.toExternalForm() + "&op=RENEWDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // renewew delegation token, authenticated access to URL, not renewer
        url = new URL(getJettyURL() + "/foo/bar?authenticated=bar&op=RENEWDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());

        // cancel delegation token, nonauthenticated access to URL
        url = new URL(nonAuthURL.toExternalForm() + "?op=CANCELDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // cancel canceled delegation token, nonauthenticated access to URL
        url = new URL(nonAuthURL.toExternalForm() + "?op=CANCELDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, conn.getResponseCode());

        // get new delegation token
        url = new URL(authURL.toExternalForm() + "&op=GETDELEGATIONTOKEN&renewer=foo");
        conn = (HttpURLConnection) url.openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        mapper = new ObjectMapper();
        map = mapper.readValue(conn.getInputStream(), Map.class);
        dt = (String) ((Map) map.get("Token")).get("urlString");
        Assert.assertNotNull(dt);

        // cancel delegation token, authenticated access to URL
        url = new URL(authURL.toExternalForm() + "&op=CANCELDELEGATIONTOKEN&token=" + dt);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("PUT");
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
    } finally {
        jetty.stop();
    }
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {//w  w w .  j  a va2s .c o  m
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public String getServerProtocol() throws IOException, RepositoryException, UnauthorizedException {
    checkServerURL();/*ww  w  .  j  ava  2s . c  o  m*/

    GetMethod method = new GetMethod(Protocol.getProtocolLocation(serverURL));
    setDoAuthentication(method);

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_OK) {
            return method.getResponseBodyAsString();
        } else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new UnauthorizedException();
        } else if (httpCode == HttpURLConnection.HTTP_NOT_FOUND) {
            // trying to contact a non-Sesame server?
            throw new RepositoryException("Failed to get server protocol; no such resource on this server");
        } else {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to get server protocol: " + errInfo);
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Add new configuration files to a given application.
 *
 * @param id      The id of the application to add the configuration file to. Not
 *                null/empty/blank./*from  www  .j  a v a2s. c  om*/
 * @param configs The configuration files to add. Not null/empty/blank.
 * @return The active configurations for this application.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/configs")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new configuration files to an application", notes = "Add the supplied configuration files to the application with the supplied id.", response = String.class, responseContainer = "List")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid ID supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Set<String> addConfigsToApplication(
        @ApiParam(value = "Id of the application to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The configuration files to add.", required = true) final Set<String> configs)
        throws GenieException {
    LOG.info("Called with id " + id + " and config " + configs);
    return this.applicationConfigService.addConfigsToApplication(id, configs);
}