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.eclipse.hono.deviceregistry.FileBasedTenantService.java

TenantResult<JsonObject> removeTenant(final String tenantId) {

    Objects.requireNonNull(tenantId);

    if (getConfig().isModificationEnabled()) {
        if (tenants.remove(tenantId) != null) {
            dirty = true;//from   ww w  .  j a  va  2s.c  o  m
            return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:org.languagetool.server.LanguageToolHttpHandler.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long startTime = System.currentTimeMillis();
    String remoteAddress = null;/*www .  j  a  v a2s  .com*/
    Map<String, String> parameters = new HashMap<>();
    int reqId = reqCounter.incrementRequestCount();
    ServerMetricsCollector.getInstance().logRequest();
    boolean incrementHandleCount = false;
    try {
        URI requestedUri = httpExchange.getRequestURI();
        if (requestedUri.getRawPath().startsWith("/v2/")) {
            // healthcheck should come before other limit checks (requests per time etc.), to be sure it works: 
            String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
            if (pathWithoutVersion.equals("healthcheck")) {
                if (workQueueFull(httpExchange, parameters,
                        "Healthcheck failed: There are currently too many parallel requests.")) {
                    ServerMetricsCollector.getInstance().logFailedHealthcheck();
                    return;
                } else {
                    String ok = "OK";
                    httpExchange.getResponseHeaders().set("Content-Type", "text/plain");
                    httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, ok.getBytes(ENCODING).length);
                    httpExchange.getResponseBody().write(ok.getBytes(ENCODING));
                    ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_OK);
                    return;
                }
            }
        }
        String referrer = httpExchange.getRequestHeaders().getFirst("Referer");
        String origin = httpExchange.getRequestHeaders().getFirst("Origin"); // Referer can be turned off with meta tags, so also check this
        for (String ref : config.getBlockedReferrers()) {
            String errorMessage = null;
            if (ref != null && !ref.isEmpty()) {
                if (referrer != null && siteMatches(referrer, ref)) {
                    errorMessage = "Error: Access with referrer " + referrer + " denied.";
                } else if (origin != null && siteMatches(origin, ref)) {
                    errorMessage = "Error: Access with origin " + origin + " denied.";
                }
            }
            if (errorMessage != null) {
                sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
                logError(errorMessage, HttpURLConnection.HTTP_FORBIDDEN, parameters, httpExchange);
                ServerMetricsCollector.getInstance().logResponse(HttpURLConnection.HTTP_FORBIDDEN);
                return;
            }
        }
        String origAddress = httpExchange.getRemoteAddress().getAddress().getHostAddress();
        String realAddressOrNull = getRealRemoteAddressOrNull(httpExchange);
        remoteAddress = realAddressOrNull != null ? realAddressOrNull : origAddress;
        reqCounter.incrementHandleCount(remoteAddress, reqId);
        incrementHandleCount = true;
        // According to the Javadoc, "Closing an exchange without consuming all of the request body is
        // not an error but may make the underlying TCP connection unusable for following exchanges.",
        // so we consume the request now, even before checking for request limits:
        parameters = getRequestQuery(httpExchange, requestedUri);
        if (requestLimiter != null) {
            try {
                requestLimiter.checkAccess(remoteAddress, parameters, httpExchange.getRequestHeaders());
            } catch (TooManyRequestsException e) {
                String errorMessage = "Error: Access from " + remoteAddress + " denied: " + e.getMessage();
                int code = HttpURLConnection.HTTP_FORBIDDEN;
                sendError(httpExchange, code, errorMessage);
                // already logged vai DatabaseAccessLimitLogEntry
                logError(errorMessage, code, parameters, httpExchange, false);
                return;
            }
        }
        if (errorRequestLimiter != null && !errorRequestLimiter.wouldAccessBeOkay(remoteAddress, parameters,
                httpExchange.getRequestHeaders())) {
            String textSizeMessage = getTextOrDataSizeMessage(parameters);
            String errorMessage = "Error: Access from " + remoteAddress + " denied - too many recent timeouts. "
                    + textSizeMessage + " Allowed maximum timeouts: " + errorRequestLimiter.getRequestLimit()
                    + " per " + errorRequestLimiter.getRequestLimitPeriodInSeconds() + " seconds";
            int code = HttpURLConnection.HTTP_FORBIDDEN;
            sendError(httpExchange, code, errorMessage);
            logError(errorMessage, code, parameters, httpExchange);
            return;
        }
        if (workQueueFull(httpExchange, parameters,
                "Error: There are currently too many parallel requests. Please try again later.")) {
            ServerMetricsCollector.getInstance()
                    .logRequestError(ServerMetricsCollector.RequestErrorType.QUEUE_FULL);
            return;
        }
        if (allowedIps == null || allowedIps.contains(origAddress)) {
            if (requestedUri.getRawPath().startsWith("/v2/")) {
                ApiV2 apiV2 = new ApiV2(textCheckerV2, config.getAllowOriginUrl());
                String pathWithoutVersion = requestedUri.getRawPath().substring("/v2/".length());
                apiV2.handleRequest(pathWithoutVersion, httpExchange, parameters, errorRequestLimiter,
                        remoteAddress, config);
            } else if (requestedUri.getRawPath().endsWith("/Languages")) {
                throw new IllegalArgumentException(
                        "You're using an old version of our API that's not supported anymore. Please see https://languagetool.org/http-api/migration.php");
            } else if (requestedUri.getRawPath().equals("/")) {
                throw new IllegalArgumentException(
                        "Missing arguments for LanguageTool API. Please see " + API_DOC_URL);
            } else if (requestedUri.getRawPath().contains("/v2/")) {
                throw new IllegalArgumentException(
                        "You have '/v2/' in your path, but not at the root. Try an URL like 'http://server/v2/...' ");
            } else if (requestedUri.getRawPath().equals("/favicon.ico")) {
                sendError(httpExchange, HttpURLConnection.HTTP_NOT_FOUND, "Not found");
            } else {
                throw new IllegalArgumentException(
                        "This is the LanguageTool API. You have not specified any parameters. Please see "
                                + API_DOC_URL);
            }
        } else {
            String errorMessage = "Error: Access from " + StringTools.escapeXML(origAddress) + " denied";
            sendError(httpExchange, HttpURLConnection.HTTP_FORBIDDEN, errorMessage);
            throw new RuntimeException(errorMessage);
        }
    } catch (Exception e) {
        String response;
        int errorCode;
        boolean textLoggingAllowed = false;
        boolean logStacktrace = true;
        Throwable rootCause = ExceptionUtils.getRootCause(e);
        if (e instanceof TextTooLongException || rootCause instanceof TextTooLongException) {
            errorCode = HttpURLConnection.HTTP_ENTITY_TOO_LARGE;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof ErrorRateTooHighException || rootCause instanceof ErrorRateTooHighException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = ExceptionUtils.getRootCause(e).getMessage();
            logStacktrace = false;
        } else if (hasCause(e, AuthException.class)) {
            errorCode = HttpURLConnection.HTTP_FORBIDDEN;
            response = e.getMessage();
            logStacktrace = false;
        } else if (e instanceof IllegalArgumentException || rootCause instanceof IllegalArgumentException) {
            errorCode = HttpURLConnection.HTTP_BAD_REQUEST;
            response = e.getMessage();
        } else if (e instanceof PathNotFoundException || rootCause instanceof PathNotFoundException) {
            errorCode = HttpURLConnection.HTTP_NOT_FOUND;
            response = e.getMessage();
        } else if (e instanceof TimeoutException || rootCause instanceof TimeoutException) {
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            response = "Checking took longer than " + config.getMaxCheckTimeMillis() / 1000.0f
                    + " seconds, which is this server's limit. "
                    + "Please make sure you have selected the proper language or consider submitting a shorter text.";
        } else {
            response = "Internal Error: " + e.getMessage();
            errorCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
            textLoggingAllowed = true;
        }
        long endTime = System.currentTimeMillis();
        logError(remoteAddress, e, errorCode, httpExchange, parameters, textLoggingAllowed, logStacktrace,
                endTime - startTime);
        sendError(httpExchange, errorCode, "Error: " + response);

    } finally {
        httpExchange.close();
        if (incrementHandleCount) {
            reqCounter.decrementHandleCount(reqId);
        }
    }
}

From source file:nl.ru.cmbi.vase.web.rest.JobRestResource.java

@MethodMapping(value = "/structure/{id}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN)
public String structure(String id) {
    try {/*from   ww  w . j a va  2  s.  c o m*/
        Matcher mpdb = StockholmParser.pPDBAC.matcher(id);
        if (mpdb.matches()) {

            URL url = Utils.getRcsbURL(mpdb.group(1));

            StringWriter pdbWriter = new StringWriter();
            IOUtils.copy(url.openStream(), pdbWriter, "UTF-8");
            pdbWriter.close();

            return pdbWriter.toString();
        }

        File xmlFile = new File(Config.getCacheDir(), id + ".xml.gz");
        if (xmlFile.isFile()) {

            VASEDataObject data = VASEXMLParser.parse(new GZIPInputStream(new FileInputStream(xmlFile)));

            return Utils.getPdbContents(data.getPdbID());
        }
        if (Config.hsspPdbCacheEnabled()) {

            File pdbFile = new File(Config.getHSSPCacheDir(), id + ".pdb.gz");

            if (pdbFile.isFile()) {

                StringWriter pdbWriter = new StringWriter();
                IOUtils.copy(new GZIPInputStream(new FileInputStream(pdbFile)), pdbWriter, "UTF-8");
                pdbWriter.close();

                return pdbWriter.toString();
            }
        }

        log.error("no structure file for " + id);
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);

    } catch (Exception e) {

        log.error("structure " + id + ": " + e.getMessage(), e);

        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

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

@Path("/{contentObjectIdOrName: " + CmsConstants.UUID_OR_SYSTEM_NAME_REG_EXP_FOR_RESTEASY + "}"
        + "/{propertyPath: " + CmsConstants.PROPERTY_PATH_WITH_ID_REG_EXP_FOR_RESTEASY + "}")
public AstroboaResource getContentObjectPropertyUsingIdentifierInsteadOfIndex(
        @PathParam("contentObjectIdOrName") String contentObjectIdOrName,
        @PathParam("propertyPath") String propertyPath) {

    try {//w  w w  .j a  va  2  s. c  om

        ContentObject contentObject = retrieveContentObjectByIdOrSystemName(contentObjectIdOrName,
                FetchLevel.ENTITY, null);

        if (contentObject == null) {
            logger.warn(
                    "The provided content object id / system name {} does not correspond to a content object or you do not have permission to access the requested object",
                    contentObjectIdOrName);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        // We allow to put a mime type suffix (i.e. .jpg, .png, .doc) at the end of the property path
        // This is required when accessing binary properties and the programs which consume the 
        // URL binary outcome do not read the mime type and filename from the header but rather depend on the mime type suffix at 
        // the end of the URL in order to determine how to treat the binary content.
        // Additionally we may utilize this suffix in latter version of the API to support the delivery of different representations 
        // of the property contents. 
        // So we need to check if the property path contains a mime type suffix and remove it
        // This may cause problems if a requested property itself is named under the name of a mime type suffix.
        // To resolve this potential problem it is required to always put a mime type suffix at the end of URLs that read property values 
        // if the requested property is named under the name of a mime type suffix 
        // (i.e. .../objects/{contentObjectId}/myImageWithMultipleFormats.jpg.jpg this will result in removing the last "jpg" suffix but keep the previous one which corresponds to a 
        // property named "jpg") 
        if (propertyPath != null && !propertyPath.endsWith("]")) {
            String candidateMimeTypeSuffix = StringUtils.substringAfterLast(propertyPath, ".");
            if (ContentApiUtils.isKnownMimeTypeSuffix(candidateMimeTypeSuffix)) {
                propertyPath = StringUtils.substringBeforeLast(propertyPath, ".");
            }
        }

        //Extract property along with the value identifier or the value index
        PropertyExtractor propertyExtractor = null;

        //Load Property according to property path
        CmsProperty property = null;

        try {
            propertyExtractor = new PropertyExtractor(contentObject, propertyPath);
            property = propertyExtractor.getProperty();
        } catch (Exception e) {
            logger.warn("Could not load provided property using path '" + propertyPath + "' from contentObject "
                    + contentObjectIdOrName, e);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        if (property == null) {
            logger.warn(
                    "The provided property '{}' for content object with id or system name '{}' does not exist",
                    propertyPath, contentObjectIdOrName);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        switch (property.getValueType()) {
        case Complex:
            logger.warn(
                    "The provided property '{}' for content object with id or system name '{}' is complex. Currently only simple type property values or binary channel content can be returned through this API call",
                    propertyPath, contentObjectIdOrName);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);

        case Binary:
            if (propertyExtractor.getIdentifierOfTheValueOfTheProperty() == null) {
                return new BinaryChannelResource(astroboaClient, contentObject, (BinaryProperty) property,
                        propertyExtractor.getIndexOfTheValueOfTheProperty());
            } else {
                return new BinaryChannelResource(astroboaClient, contentObject, (BinaryProperty) property,
                        propertyExtractor.getIdentifierOfTheValueOfTheProperty());
            }

        case ContentType:
            logger.error("Astroboa returned value type '" + ValueType.ContentType
                    + "' for property '{}' for content object with id or system name '{}'. This should never happen",
                    propertyPath, contentObjectIdOrName);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);

        default:

            if (propertyExtractor.getIdentifierOfTheValueOfTheProperty() != null) {
                logger.warn(
                        "The provided property '{}' for content object with id or system name '{}' is a simple non-binary property but user has provided an identifier instead of an index.",
                        propertyPath, contentObjectIdOrName);
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }

            return new SimplePropertyResource(astroboaClient, contentObject, (SimpleCmsProperty) property,
                    propertyExtractor.getIndexOfTheValueOfTheProperty());
        }

    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        logger.error("A problem occured while retrieving property: '" + propertyPath
                + "' for content object with id or system name: " + contentObjectIdOrName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }

}

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

/**
 * Delete all applications from database.
 *
 * @return All The deleted comamnd/*from w w  w . jav a2 s . c  o m*/
 * @throws GenieException For any error
 */
@DELETE
@ApiOperation(value = "Delete all commands", notes = "Delete all available commands and get them back.", response = Command.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 List<Command> deleteAllCommands() throws GenieException {
    LOG.info("called to delete all commands.");
    return this.commandConfigService.deleteAllCommands();
}

From source file:org.eclipse.hono.deviceregistry.FileBasedCredentialsService.java

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

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(type);
    Objects.requireNonNull(authId);
    Objects.requireNonNull(resultHandler);

    final JsonObject data = getSingleCredentials(tenantId, authId, type, clientContext);
    if (data == null) {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
    } else {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_OK,
                data.copy(), CacheDirective.noCacheDirective())));
    }
}

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

/**
 * Delete a cluster configuration./*from  ww  w. j a  v  a2 s  .com*/
 *
 * @param id unique id for cluster to delete
 * @return the deleted cluster
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete a cluster", notes = "Delete a cluster with the supplied id.", response = Cluster.class)
@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 Cluster deleteCluster(
        @ApiParam(value = "Id of the cluster to delete.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Delete called for id: " + id);
    return this.clusterConfigService.deleteCluster(id);
}

From source file:org.openremote.modeler.beehive.Beehive30API.java

/**
 * Downloads a user artifact archive from Beehive server and stores it to a local resource
 * cache. /*from w  w w  .j  a  v a  2  s  .  co  m*/
 *
 * @param userAccount   reference to information about user and account being accessed
 * @param cache         the cache to store the user resources to
 *
 * @throws ConfigurationException
 *              If designer configuration error prevents the service from executing
 *              normally. Often a fatal error type that should be logged/notified to
 *              admins, configuration corrected and application re-deployed.
 *
 * @throws NetworkException
 *              If (possibly recoverable) network errors occured during the service
 *              operation. Network errors may be recoverable in which case this operation
 *              could be re-attempted. See {@link NetworkException.Severity} for an
 *              indication of the network error type.
 *
 * @throws CacheOperationException
 *              If there was a failure in writing the downloaded resources to cache.
 *
 *
 */
@Override
public void downloadResources(UserAccount userAccount, ResourceCache cache)
        throws ConfigurationException, NetworkException, CacheOperationException {

    // TODO :
    //    - Must use HTTPS

    // Construct the request...

    HttpClient httpClient = new DefaultHttpClient();

    URI beehiveArchiveURI;

    try {
        beehiveArchiveURI = new URI(config.getBeehiveRESTRootUrl() + "user/"
                + userAccount.getUsernamePassword().getUsername() + "/openremote.zip");
    }

    catch (URISyntaxException e) {
        throw new ConfigurationException("Incorrect Beehive REST URL defined in config.properties : {0}", e,
                e.getMessage());
    }

    HttpGet httpGet = new HttpGet(beehiveArchiveURI);

    // Authenticate...

    addHTTPAuthenticationHeader(httpGet, userAccount.getUsernamePassword().getUsername(),
            userAccount.getUsernamePassword().getPassword());

    // Collect some network statistics...

    long starttime = System.currentTimeMillis();

    // HTTP GET to Beehive...

    HttpResponse response;

    try {
        response = httpClient.execute(httpGet);
    }

    catch (IOException e) {
        throw new NetworkException(
                "Network error while downloading account (OID = {0}) archive from Beehive "
                        + "(URL : {1}) : {2}",
                e,

                userAccount.getAccount().getOid(), beehiveArchiveURI, e.getMessage());
    }

    // Make sure we got a response and a proper HTTP return code...

    if (response == null) {
        throw new NetworkException(NetworkException.Severity.SEVERE,
                "Beehive did not respond to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                printUser(userAccount));
    }

    StatusLine statusLine = response.getStatusLine();

    if (statusLine == null) {
        throw new NetworkException(NetworkException.Severity.SEVERE,
                "There was no status from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                printUser(userAccount));
    }

    int httpResponseCode = statusLine.getStatusCode();

    // Deal with the HTTP OK (200) case.

    if (httpResponseCode == HttpURLConnection.HTTP_OK) {
        HttpEntity httpEntity = response.getEntity();

        if (httpEntity == null) {
            throw new NetworkException(NetworkException.Severity.SEVERE,
                    "No content received from Beehive to HTTP GET request, URL : {0} {1}", beehiveArchiveURI,
                    printUser(userAccount));
        }

        // Download to cache...

        BufferedInputStream httpInput;

        try {
            CacheWriteStream cacheStream = cache.openWriteStream();

            httpInput = new BufferedInputStream(httpEntity.getContent());

            byte[] buffer = new byte[4096];
            int bytecount = 0, len;
            long contentLength = httpEntity.getContentLength();

            try {
                while ((len = httpInput.read(buffer)) != -1) {
                    try {
                        cacheStream.write(buffer, 0, len);
                    }

                    catch (IOException e) {
                        throw new CacheOperationException("Writing archive to cache failed : {0}", e,
                                e.getMessage());
                    }

                    bytecount += len;
                }

                // MUST mark complete for cache to accept the incoming archive...

                cacheStream.markCompleted();
            }

            finally {
                try {
                    cacheStream.close();
                }

                catch (Throwable t) {
                    serviceLog.warn("Unable to close resource archive cache stream : {0}", t, t.getMessage());
                }

                if (httpInput != null) {
                    try {
                        httpInput.close();
                    }

                    catch (Throwable t) {
                        serviceLog.warn("Unable to close HTTP input stream from Beehive URL ''{0}'' : {1}", t,
                                beehiveArchiveURI, t.getMessage());
                    }
                }
            }

            if (contentLength >= 0) {
                if (bytecount != contentLength) {
                    serviceLog.warn(
                            "Expected content length was {0} bytes but wrote {1} bytes to cache stream ''{2}''.",
                            contentLength, bytecount, cacheStream);
                }
            }

            // Record network performance stats...

            long endtime = System.currentTimeMillis();

            float kbytes = ((float) bytecount) / 1000;
            float seconds = ((float) (endtime - starttime)) / 1000;
            float kbpersec = kbytes / seconds;

            String kilobytes = new DecimalFormat("###########0.00").format(kbytes);
            String nettime = new DecimalFormat("##########0.000").format(seconds);
            String persectime = new DecimalFormat("##########0.000").format(kbpersec);

            downloadPerfLog.info("Downloaded " + kilobytes + " kilobytes in " + nettime + " seconds ("
                    + persectime + "kb/s)");
        }

        catch (IOException e) {
            // HTTP request I/O error...

            throw new NetworkException("Download of Beehive archive failed : {0}", e, e.getMessage());
        }
    }

    // Assuming 404 indicates a new user... quietly return, nothing to download...

    // TODO : MODELER-286

    else if (httpResponseCode == HttpURLConnection.HTTP_NOT_FOUND) {
        serviceLog.info("No user data found. Return code 404. Assuming new user account...");

        return;
    }

    else {
        // TODO :
        //
        //   Currently assumes any other HTTP return code is a standard network error.
        //   This could be improved by handling more specific error codes (some are
        //   fatal, some are recoverable) such as 500 Internal Error (permanent) or
        //   307 Temporary Redirect
        //
        // TODO :
        //
        //   Should handle authentication errors in their own branch, not in this generic block

        throw new NetworkException(
                "Failed to download Beehive archive from URL ''{0}'' {1}, " + "HTTP Response code: {2}",

                beehiveArchiveURI, printUser(userAccount), httpResponseCode);
    }
}

From source file:com.netflix.genie.server.services.impl.GenieExecutionServiceImpl.java

/** {@inheritDoc} */
@Override// w w w.jav a 2s.  com
public JobInfoResponse getJobInfo(String jobId) {
    logger.info("called for jobId: " + jobId);

    JobInfoResponse response;
    JobInfoElement jInfo;
    try {
        jInfo = pm.getEntity(jobId, JobInfoElement.class);
    } catch (Exception e) {
        logger.error("Failed to get job info: ", e);
        response = new JobInfoResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));
        return response;
    }

    if (jInfo == null) {
        String msg = "Job not found: " + jobId;
        logger.error(msg);
        response = new JobInfoResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND, msg));
        return response;
    } else {
        response = new JobInfoResponse();
        response.setJob(jInfo);
        response.setMessage("Returning job information for: " + jInfo.getJobID());
        return response;
    }
}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientFileSystemBrowser.java

protected void runRequest() throws Exception {
    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest"); //$NON-NLS-1$
    setupProxies();//  w w w.j av a 2s.  co  m
    // set timeout
    initHttpClientConnectionManager();

    String urlString = directoryOrFile.toString();
    CredentialsProvider credProvider = new HttpClientProxyCredentialProvider() {

        protected Proxy getECFProxy() {
            return getProxy();
        }

        protected Credentials getNTLMCredentials(Proxy lp) {
            if (hasForceNTLMProxyOption())
                return HttpClientRetrieveFileTransfer.createNTLMCredentials(lp);
            return null;
        }

    };
    // setup authentication
    setupAuthentication(urlString);
    // setup https host and port
    setupHostAndPort(credProvider, urlString);

    headMethod = new HeadMethod(hostConfigHelper.getTargetRelativePath());
    headMethod.setFollowRedirects(true);
    // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
    // Seems to be another way to select the credentials.
    headMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider);
    // set max-age for cache control to 0 for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=249990
    headMethod.addRequestHeader("Cache-Control", "max-age=0"); //$NON-NLS-1$//$NON-NLS-2$
    headMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$

    long lastModified = 0;
    long fileLength = -1;
    connectingSockets.clear();
    int code = -1;
    try {
        Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString); //$NON-NLS-1$

        code = httpClient.executeMethod(getHostConfiguration(), headMethod);

        Trace.trace(Activator.PLUGIN_ID, "browse resp=" + code); //$NON-NLS-1$

        // Check for NTLM proxy in response headers 
        // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
        boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(headMethod);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new BrowseFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (code == HttpURLConnection.HTTP_OK) {
            fileLength = headMethod.getResponseContentLength();
            lastModified = getLastModifiedTimeFromHeader();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new BrowseFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            throw new BrowseFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
        remoteFiles = new IRemoteFile[1];
        remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID);
    } catch (Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e); //$NON-NLS-1$
        BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException)
                ? e
                : new BrowseFileTransferException(NLS
                        .bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString),
                        e, code));
        throw ex;
    } finally {
        headMethod.releaseConnection();
    }
}