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:com.baracuda.piepet.nexusrelease.nexus.StageClient.java

/**
 * Retrieve and parse an XML file from the given URL.
 * //from ww w  . j a  v a 2 s  .  c  o m
 * @param url the URL where the XML document can be obtained.
 * @return the parsed Document.
 * @throws StageException if there was an issue obtaining or parsing the document.
 */
protected Document getDocument(URL url) throws StageException {
    try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        addAuthHeader(conn);
        conn.setRequestProperty("Accept", "application/xml");
        int status = conn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(conn.getInputStream());
            conn.disconnect();
            return doc;
        } else {
            drainOutput(conn);
            if (status == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new IOException("Incorrect username / password supplied.");
            } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
                throw new IOException("Document not found - is this a Nexus server?");
            } else {
                throw new IOException("Server returned error code " + status + " for " + url.toString());
            }
        }
    } catch (IOException ex) {
        throw createStageExceptionForIOException(nexusURL, ex);
    } catch (ParserConfigurationException ex) {
        throw new StageException(ex);
    } catch (SAXException ex) {
        throw new StageException(ex);
    }

}

From source file:org.projectbuendia.client.ui.OdkActivityLauncher.java

private static void handleFetchError(VolleyError error) {
    FetchXformFailedEvent.Reason reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN;
    if (error.networkResponse != null) {
        switch (error.networkResponse.statusCode) {
        case HttpURLConnection.HTTP_FORBIDDEN:
        case HttpURLConnection.HTTP_UNAUTHORIZED:
            reason = FetchXformFailedEvent.Reason.SERVER_AUTH;
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            reason = FetchXformFailedEvent.Reason.SERVER_BAD_ENDPOINT;
            break;
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
        default:/*w  w w .ja v a 2s .  c om*/
            reason = FetchXformFailedEvent.Reason.SERVER_UNKNOWN;
        }
    }
    EventBus.getDefault().post(new FetchXformFailedEvent(reason, error));
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitCheckoutTest.java

@Test
public void testCheckoutInvalidBranchName() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    JSONObject clone = clone(clonePath);
    String location = clone.getString(ProtocolConstants.KEY_LOCATION);

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    // checkout 'a', which hasn't been created
    response = checkoutBranch(location, "a");
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

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

@Override
public void removeAll(final String tenantId, final String deviceId,
        final Handler<AsyncResult<CredentialsResult<JsonObject>>> resultHandler) {

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

    if (getConfig().isModificationEnabled()) {

        final Map<String, JsonArray> credentialsForTenant = credentials.get(tenantId);
        if (credentialsForTenant == null) {
            resultHandler/*from w  ww . ja v a2 s .  c  om*/
                    .handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
        } else {

            boolean removedAnyElement = false;

            // delete based on type (no authId provided) - this might consume more time on large data sets and is thus
            // handled explicitly
            for (final JsonArray credentialsForAuthId : credentialsForTenant.values()) {
                if (removeCredentialsFromCredentialsArray(deviceId, CredentialsConstants.SPECIFIER_WILDCARD,
                        credentialsForAuthId)) {
                    removedAnyElement = true;
                }
            }

            // there might be empty credentials arrays left now, so remove them in a second run
            cleanupEmptyCredentialsArrays(credentialsForTenant);

            if (removedAnyElement) {
                dirty = true;
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NO_CONTENT)));
            } else {
                resultHandler.handle(
                        Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_NOT_FOUND)));
            }
        }
    } else {
        resultHandler.handle(Future.succeededFuture(CredentialsResult.from(HttpURLConnection.HTTP_FORBIDDEN)));
    }
}

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

/**
 * Delete the all jar files from a given application.
 *
 * @param id The id of the application to delete the jar files from. Not
 *           null/empty/blank./*from  w w  w  . j  a va  2s .  c om*/
 * @return Empty set if successful
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/jars")
@ApiOperation(value = "Remove all jar files from an application", notes = "Remove all the jar files from the application with given 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> removeAllJarsForApplication(
        @ApiParam(value = "Id of the application to delete from.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called with id " + id);
    return this.applicationConfigService.removeAllJarsForApplication(id);
}

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

private Response getTaxonomy(String taxonomyIdOrName, Output output, String callback, String prettyPrint,
        FetchLevel fetchLevel) {//from   ww  w.j  av a2s .c o  m

    if (StringUtils.isBlank(taxonomyIdOrName)) {
        logger.warn("No Taxonomy Name provided");
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }

    try {
        String taxonomyXmlorJson = retrieveTaxonomyXMLorJSONByIdOrSystemName(taxonomyIdOrName, output,
                prettyPrint, fetchLevel);

        StringBuilder resourceRepresentation = new StringBuilder();

        if (StringUtils.isBlank(callback)) {
            resourceRepresentation.append(taxonomyXmlorJson);
        } else {
            switch (output) {
            case XML: {
                ContentApiUtils.generateXMLP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            }
            case JSON:
                ContentApiUtils.generateJSONP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            default: {
                ContentApiUtils.generateXMLP(resourceRepresentation, taxonomyXmlorJson, callback);
                break;
            }
            }

        }

        return ContentApiUtils.createResponse(resourceRepresentation, output, callback, null);
    } catch (Exception e) {
        logger.error("Taxonomy IdOrName: " + taxonomyIdOrName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

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

private Response getTopicInternal(String topicIdOrName, Output output, String callback, String prettyPrint,
        FetchLevel fetchLevel) {/*from   w  w  w  .j a v a2  s  .  co m*/

    //OLD Method
    //return generateTopicResponseUsingTopicInstance(topicIdOrName, output,   callback);

    boolean prettyPrintEnabled = ContentApiUtils.isPrettyPrintEnabled(prettyPrint);

    try {

        StringBuilder topicAsXMLOrJSONBuilder = new StringBuilder();

        switch (output) {
        case XML: {
            String topicXML = astroboaClient.getTopicService().getTopic(topicIdOrName,
                    ResourceRepresentationType.XML, fetchLevel, prettyPrintEnabled);

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

            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topicXML);
            } else {
                ContentApiUtils.generateXMLP(topicAsXMLOrJSONBuilder, topicXML, callback);
            }
            break;
        }
        case JSON: {
            String topicJSON = astroboaClient.getTopicService().getTopic(topicIdOrName,
                    ResourceRepresentationType.JSON, fetchLevel, prettyPrintEnabled);

            if (StringUtils.isBlank(topicJSON)) {
                throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
            }
            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topicJSON);
            } else {
                ContentApiUtils.generateJSONP(topicAsXMLOrJSONBuilder, topicJSON, callback);
            }
            break;
        }
        }

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

    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        logger.error("Topic IdOrName: " + topicIdOrName, e);
        throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
    }

}

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

/**
 * Remove an command from a given cluster.
 *
 * @param id    The id of the cluster to delete the command from. Not
 *              null/empty/blank./*ww w .j a v a  2 s .com*/
 * @param cmdId The id of the command to remove. Not null/empty/blank.
 * @return The active set of commands for the cluster.
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/commands/{cmdId}")
@ApiOperation(value = "Remove a command from a cluster", notes = "Remove the given command from the cluster with given id.", response = Command.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<Command> removeCommandForCluster(
        @ApiParam(value = "Id of the cluster to delete from.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The id of the command to remove.", required = true) @PathParam("cmdId") final String cmdId)
        throws GenieException {
    LOG.info("Called with id " + id + " and command id " + cmdId);
    return this.clusterConfigService.removeCommandForCluster(id, cmdId);
}

From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java

/**
 * When the servlet container generates a 404 page not found, we want to pass
 * it through without caching and without adding anything to it.
 * <p/>//from ww w.j  a v a2 s . c  om
 * Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/PageNotFound.jsp
 */
public void testNotFound() throws Exception {

    String url = "http://localhost:9080/non_ok/PageNotFound.jsp";
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.addRequestHeader("If-modified-Since", "Fri, 13 May 3006 23:54:18 GMT");
    httpMethod.addRequestHeader("Accept-Encoding", "gzip");
    int responseCode = httpClient.executeMethod(httpMethod);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, responseCode);
    String responseBody = httpMethod.getResponseBodyAsString();
    assertNotNull(responseBody);
    assertNull(httpMethod.getResponseHeader("Content-Encoding"));
}

From source file:ORG.oclc.os.SRW.SRWServlet.java

/**
 * handle a ?wsdl request//from  w w  w  . j av a2s. c  om
 * @param msgContext message context so far
 * @param response response to write to
 * @throws AxisFault when anything other than a Server.NoService fault is reported
 * during WSDL generation
 */
//MIH: add request to method-parameters//////////////////////////////
protected void processWsdlRequest(MessageContext msgContext, HttpServletResponse response,
        HttpServletRequest request) throws AxisFault, IOException {
    AxisEngine engine = getEngine();
    PrintWriter writer;
    try {
        // MIH: retrieve WSDL hardcoded//////////////////////////////////////////////////
        try {
            response.setContentType("text/xml");
            writer = response.getWriter();
            writer.print(getWsdl(msgContext.getTargetService(), request));
            writer.close();
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
        //            engine.generateWSDL(msgContext);
        //            Document doc = (Document) msgContext.getProperty("WSDL");
        //            if (doc != null) {
        //                response.setContentType("text/xml");
        //                writer=response.getWriter();
        //                XMLUtils.DocumentToWriter(doc, writer);
        //                writer.close();
        //            } else {
        //                if (servletLog.isDebugEnabled()) {
        //                    servletLog.debug("processWsdlRequest: failed to create WSDL");
        //                }
        //                reportNoWSDL(response, "noWSDL02", null);
        //            }
        ////////////////////////////////////////////////////////////////////////////////////
    } catch (AxisFault axisFault) {
        //the no-service fault is mapped to a no-wsdl error
        if (axisFault.getFaultCode().equals(Constants.QNAME_NO_SERVICE_FAULT_CODE)) {
            //which we log
            processAxisFault(axisFault);
            //then report under a 404 error
            response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
            reportNoWSDL(response, "noWSDL01", axisFault);
        } else {
            //all other faults get thrown
            throw axisFault;
        }
    }
}