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.betaconceptframework.astroboa.resourceapi.resource.DefinitionResource.java

private Response getDefinitionInternal(String propertyPath, Output output, String callback,
        boolean prettyPrint) {

    try {//ww w. j  a v  a2s. co m

        if (StringUtils.isBlank(propertyPath)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        DefinitionService definitionService = astroboaClient.getDefinitionService();

        StringBuilder definitionAsXMLOrJSONorXSD = new StringBuilder();

        switch (output) {
        case XML: {

            String xml = definitionService.getCmsDefinition(propertyPath, ResourceRepresentationType.XML,
                    prettyPrint);

            if (StringUtils.isBlank(xml)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }

            if (StringUtils.isBlank(callback)) {
                definitionAsXMLOrJSONorXSD.append(xml);
            } else {
                ContentApiUtils.generateXMLP(definitionAsXMLOrJSONorXSD, xml, callback);
            }
            break;
        }
        case JSON:

            String json = definitionService.getCmsDefinition(propertyPath, ResourceRepresentationType.JSON,
                    prettyPrint);

            if (StringUtils.isBlank(json)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }

            if (StringUtils.isBlank(callback)) {
                definitionAsXMLOrJSONorXSD.append(json);
            } else {
                ContentApiUtils.generateJSONP(definitionAsXMLOrJSONorXSD, json, callback);
            }
            break;
        case XSD:

            String xsd = definitionService.getCmsDefinition(propertyPath, ResourceRepresentationType.XSD,
                    prettyPrint);

            if (StringUtils.isBlank(xsd)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }

            definitionAsXMLOrJSONorXSD.append(xsd);

            if (StringUtils.isNotBlank(callback)) {
                logger.warn("Callback {} is ignored in {} output", callback, output);
            }
            break;
        }

        return ContentApiUtils.createResponse(definitionAsXMLOrJSONorXSD, output, callback, null);

    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Definition For property path: " + propertyPath, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }
}

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

/**
 * Delete a command./*from   ww w. j  av a  2s . c  o m*/
 *
 * @param id unique id for configuration to delete
 * @return The deleted configuration
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete an comamnd", notes = "Delete an command with the supplied id.", response = Command.class)
@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 Command deleteCommand(
        @ApiParam(value = "Id of the command to delete.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called to delete command with id " + id);
    return this.commandConfigService.deleteCommand(id);
}

From source file:org.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewerForContentSummary.java

@Test
public void testGetContentSummaryResponseCode() throws Exception {
    try (WebImageViewer viewer = new WebImageViewer(NetUtils.createSocketAddr("localhost:0"))) {
        viewer.initServer(originalFsimage.getAbsolutePath());
        int port = viewer.getPort();
        URL url = new URL("http://localhost:" + port + "/webhdfs/v1/dir123/?op=GETCONTENTSUMMARY");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();/*ww  w .  j a  v a2  s. c  o  m*/
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, connection.getResponseCode());
    }
}

From source file:org.eclipse.orion.server.tests.servlets.site.SiteTest.java

@Test
/**/*from w  w  w.j  a va  2 s.c  o  m*/
 * Try to access site created by another user, verify that we can't.
 */
public void testDisallowedAccess() throws SAXException, JSONException, IOException, URISyntaxException {
    createUser("alice", "alice");
    createUser("bob", "bob");

    // Alice: Create site
    final String name = "A site to delete";
    final String workspaceId = workspaceObject.getString(ProtocolConstants.KEY_ID);
    WebResponse createResp = createSite(name, workspaceId, null, null, "alice");
    JSONObject site = new JSONObject(createResp.getText());
    String location = site.getString(ProtocolConstants.HEADER_LOCATION);

    // Alice: Get site
    WebRequest getReq = getRetrieveSiteRequest(location, "alice");
    WebResponse getResp = webConversation.getResponse(getReq);
    assertEquals(HttpURLConnection.HTTP_OK, getResp.getResponseCode());

    // Bob: Attempt to get Alice's site
    getReq = getRetrieveSiteRequest(location, "bob");
    getResp = webConversation.getResponse(getReq);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getResp.getResponseCode());
}

From source file:org.jvnet.hudson.plugins.m2release.nexus.StageClient.java

public boolean checkStageForGAV(Stage stage, String group, String artifact, String version)
        throws StageException {
    // do we always know the version???
    // to browse an open repo
    // /service/local/repositories/${stageID}/content/...
    // the stage repos are not listed via a call to
    // /service/local/repositories/ but are in existence!
    boolean found = false;
    try {/*from ww  w  .j  av a2 s  .co m*/
        URL url;
        if (version == null) {
            url = new URL(nexusURL.toString() + "/service/local/repositories/" + stage.getStageID()
                    + "/content/" + group.replace('.', '/') + '/' + artifact + "/?isLocal");
        } else {
            url = new URL(nexusURL.toString() + "/service/local/repositories/" + stage.getStageID()
                    + "/content/" + group.replace('.', '/') + '/' + artifact + '/' + version + "/?isLocal");
        }
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        addAuthHeader(conn);
        conn.setRequestMethod("HEAD");
        int response = conn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // we found our baby - may be a different version but we don't
            // always have that to hand (if Maven did the auto numbering)
            found = true;
        } else if (response == HttpURLConnection.HTTP_NOT_FOUND) {
            // not this repo
        } else {
            log.warn("Server returned HTTP status {} when we only expected a 200 or 404.",
                    Integer.toString(response));
        }
        conn.disconnect();
    } catch (IOException ex) {
        throw createStageExceptionForIOException(nexusURL, ex);
    }
    return found;
}

From source file:org.pixmob.freemobile.netstat.SyncService.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<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {//from www . j a  v  a 2  s  .  c  o  m
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // 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("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", 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", "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);
        } 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(), SyncService.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", 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.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

/**
 * {@inheritDoc}/*  w  w  w . ja v  a2  s  .c o  m*/
 * <p>
 * The result object will include a <em>no-cache</em> directive.
 */
@Override
public void getAll(final String tenantId, final String deviceId,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(resultHandler);

    final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
    if (credentialsForTenant == null) {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
    } else {
        final JsonArray matchingCredentials = new JsonArray();
        // iterate over all credentials per auth-id in order to find credentials matching the given device
        for (final JsonArray credentialsForAuthId : credentialsForTenant.values()) {
            findCredentialsForDevice(credentialsForAuthId, deviceId, matchingCredentials);
        }
        if (matchingCredentials.isEmpty()) {
            resultHandler
                    .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
        } else {
            final JsonObject result = new JsonObject()
                    .put(CredentialsConstants.FIELD_CREDENTIALS_TOTAL, matchingCredentials.size())
                    .put(CredentialsConstants.CREDENTIALS_ENDPOINT, matchingCredentials);
            resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_OK,
                    result, CacheDirective.noCacheDirective())));
        }
    }
}

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

/**
 * Delete an application configuration from database.
 *
 * @param id unique id of configuration to delete
 * @return The deleted application configuration
 * @throws GenieException For any error/*ww  w. jav a2  s  .c o  m*/
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete an application", notes = "Delete an application with the supplied id.", response = Application.class)
@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 Application deleteApplication(
        @ApiParam(value = "Id of the application to delete.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Delete an application with id " + id);
    return this.applicationConfigService.deleteApplication(id);
}

From source file:org.eclipse.oomph.setup.internal.core.util.ECFURIHandlerImpl.java

@Override
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
    if (TEST_IO_EXCEPTION) {
        File folder = new File(CACHE_FOLDER.toFileString());
        if (folder.isDirectory()) {
            System.out.println("Deleting cache folder: " + folder);
            IOUtil.deleteBestEffort(folder);
        }//ww w. ja v a2s  .co  m

        throw new IOException("Simulated network problem");
    }

    CacheHandling cacheHandling = getCacheHandling(options);
    URIConverter uriConverter = getURIConverter(options);
    URI cacheURI = getCacheFile(uri);
    String eTag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getETag(uriConverter, cacheURI);
    String expectedETag = cacheHandling == CacheHandling.CACHE_IGNORE ? null : getExpectedETag(uri);
    if (expectedETag != null || cacheHandling == CacheHandling.CACHE_ONLY
            || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING) {
        if (cacheHandling == CacheHandling.CACHE_ONLY
                || cacheHandling == CacheHandling.CACHE_WITHOUT_ETAG_CHECKING ? eTag != null
                        : expectedETag.equals(eTag)) {
            try {
                setExpectedETag(uri, expectedETag);
                return uriConverter.createInputStream(cacheURI, options);
            } catch (IOException ex) {
                // Perhaps another JVM is busy writing this file.
                // Proceed as if it doesn't exit.
            }
        }
    }

    String username;
    String password;

    String uriString = uri.toString();
    Proxy proxy = ProxySetupHelper.getProxy(uriString);
    if (proxy != null) {
        username = proxy.getUsername();
        password = proxy.getPassword();
    } else {
        username = null;
        password = null;
    }

    IContainer container = createContainer();

    AuthorizationHandler authorizatonHandler = getAuthorizatonHandler(options);
    Authorization authorization = getAuthorizaton(options);
    int triedReauthorization = 0;
    for (int i = 0;; ++i) {
        IRetrieveFileTransferContainerAdapter fileTransfer = container
                .getAdapter(IRetrieveFileTransferContainerAdapter.class);

        if (proxy != null) {
            fileTransfer.setProxy(proxy);

            if (username != null) {
                fileTransfer.setConnectContextForAuthentication(
                        ConnectContextFactory.createUsernamePasswordConnectContext(username, password));
            } else if (password != null) {
                fileTransfer.setConnectContextForAuthentication(
                        ConnectContextFactory.createPasswordConnectContext(password));
            }
        }

        FileTransferListener transferListener = new FileTransferListener(eTag);

        try {
            FileTransferID fileTransferID = new FileTransferID(new FileTransferNamespace(),
                    IOUtil.newURI(uriString));
            Map<Object, Object> requestOptions = new HashMap<Object, Object>();
            requestOptions.put(IRetrieveFileTransferOptions.CONNECT_TIMEOUT, CONNECT_TIMEOUT);
            requestOptions.put(IRetrieveFileTransferOptions.READ_TIMEOUT, READ_TIMEOUT);
            if (authorization != null && authorization.isAuthorized()) {
                requestOptions.put(IRetrieveFileTransferOptions.REQUEST_HEADERS,
                        Collections.singletonMap("Authorization", authorization.getAuthorization()));
            }

            fileTransfer.sendRetrieveRequest(fileTransferID, transferListener, requestOptions);
        } catch (IncomingFileTransferException ex) {
            throw new IOExceptionWithCause(ex);
        }
        try {
            transferListener.receiveLatch.await();
        } catch (InterruptedException ex) {
            throw new IOExceptionWithCause(ex);
        }

        if (transferListener.exception != null) {
            if (!(transferListener.exception instanceof UserCancelledException)) {
                if (transferListener.exception.getCause() instanceof SocketTimeoutException && i <= 2) {
                    continue;
                }

                if (authorizatonHandler != null
                        && transferListener.exception instanceof IncomingFileTransferException) {
                    // We assume contents can be accessed via the github API https://developer.github.com/v3/repos/contents/#get-contents
                    // That API, for security reasons, does not return HTTP_UNAUTHORIZED, so we need this special case for that host.
                    IncomingFileTransferException incomingFileTransferException = (IncomingFileTransferException) transferListener.exception;
                    int errorCode = incomingFileTransferException.getErrorCode();
                    if (errorCode == HttpURLConnection.HTTP_UNAUTHORIZED || API_GITHUB_HOST.equals(getHost(uri))
                            && errorCode == HttpURLConnection.HTTP_NOT_FOUND) {
                        if (authorization == null) {
                            authorization = authorizatonHandler.authorize(uri);
                            if (authorization.isAuthorized()) {
                                --i;
                                continue;
                            }
                        }

                        if (!authorization.isUnauthorizeable() && triedReauthorization++ < 3) {
                            authorization = authorizatonHandler.reauthorize(uri, authorization);
                            if (authorization.isAuthorized()) {
                                --i;
                                continue;
                            }
                        }
                    }
                }
            }

            if (!CacheHandling.CACHE_IGNORE.equals(cacheHandling) && uriConverter.exists(cacheURI, options)
                    && (!(transferListener.exception instanceof IncomingFileTransferException)
                            || ((IncomingFileTransferException) transferListener.exception)
                                    .getErrorCode() != HttpURLConnection.HTTP_NOT_FOUND)) {
                setExpectedETag(uri, transferListener.eTag == null ? eTag : transferListener.eTag);
                return uriConverter.createInputStream(cacheURI, options);
            }

            throw new IOExceptionWithCause(transferListener.exception);
        }

        byte[] bytes = transferListener.out.toByteArray();

        // In the case of the Github API, the bytes will be JSON that contains a "content" pair containing the Base64 encoding of the actual contents.
        if (API_GITHUB_HOST.equals(getHost(uri))) {
            // Find the start tag in the JSON value.
            String value = new String(bytes, "UTF-8");
            int start = value.indexOf(CONTENT_TAG);
            if (start != -1) {
                // Find the ending quote of the encoded contents.
                start += CONTENT_TAG.length();
                int end = value.indexOf('"', start);
                if (end != -1) {
                    // The content is delimited by \n so split on that during the conversion.
                    String content = value.substring(start, end);
                    String[] split = content.split("\\\\n");

                    // Write the converted bytes to a new stream and process those bytes instead.
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    for (String line : split) {
                        byte[] binary = XMLTypeFactory.eINSTANCE.createBase64Binary(line);
                        out.write(binary);
                    }

                    out.close();
                    bytes = out.toByteArray();
                }
            }
        }

        try {
            BaseUtil.writeFile(uriConverter, options, cacheURI, bytes);
        } catch (IORuntimeException ex) {
            // Ignore attempts to write out to the cache file.
            // This may collide with another JVM doing exactly the same thing.
            transferListener.eTag = null;
        } finally {
            setETag(uriConverter, cacheURI, transferListener.eTag);
        }

        setExpectedETag(uri, transferListener.eTag);
        Map<Object, Object> response = getResponse(options);
        if (response != null) {
            response.put(URIConverter.RESPONSE_TIME_STAMP_PROPERTY, transferListener.lastModified);
        }

        ETagMirror etagMirror = (ETagMirror) options.get(ETagMirror.OPTION_ETAG_MIRROR);
        if (etagMirror != null) {
            etagMirror.cacheUpdated(uri);
        }

        return new ByteArrayInputStream(bytes);
    }
}

From source file:org.sonarqube.tests.upgrade.UpgradeTest.java

private void checkUrlIsReturningNotFound(String url) {
    WsResponse response = newWsClient(orchestrator).wsConnector().call(new GetRequest(url));
    assertThat(response.code()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
}