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:i5.las2peer.services.loadStoreGraphService.LoadStoreGraphService.java

/**
 * /*from   w  w w. ja  va 2  s.  com*/
 * loadGraph
 * 
 * @param id a String
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "graphNotFound"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "graphLoaded"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError") })
@ApiOperation(value = "loadGraph", notes = "")
public HttpResponse loadGraph(@PathParam("id") String id) {
    String result = "";
    String columnName = "";
    String selectquery = "";
    int columnCount = 0;
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    try {
        // get connection from connection pool
        conn = dbm.getConnection();
        selectquery = "SELECT * FROM graphs WHERE graphId = " + id + " ;";

        // prepare statement
        stmnt = conn.prepareStatement(selectquery);

        // retrieve result set
        rs = stmnt.executeQuery();
        rsmd = (ResultSetMetaData) rs.getMetaData();
        columnCount = rsmd.getColumnCount();
        // process result set
        if (rs.next()) {
            JSONObject ro = new JSONObject();
            for (int i = 1; i <= columnCount; i++) {
                result = rs.getString(i);
                columnName = rsmd.getColumnName(i);
                // setup resulting JSON Object
                ro.put(columnName, result);
            }
            HttpResponse graphLoaded = new HttpResponse(ro.toJSONString(), HttpURLConnection.HTTP_OK);
            return graphLoaded;
        } else {
            // return HTTP Response on error
            String er = "No result for graph with id " + id;
            HttpResponse graphNotFound = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND);
            return graphNotFound;
        }

    } catch (Exception e) {
        String er = "Internal error: " + e.getMessage();
        HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internalError;
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());
                String er = "Internal error: " + e.getMessage();
                HttpResponse internalError = new HttpResponse(er, HttpURLConnection.HTTP_INTERNAL_ERROR);
                return internalError;
            }
        }
    }
}

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

@GET
@Produces(MediaType.APPLICATION_XML)//  www.j  a  v  a  2 s.c om
@Path("/{propertyPath: " + CmsConstants.PROPERTY_PATH_REG_EXP_FOR_RESTEASY + "}")
public Response getDefinitionAsXml(@PathParam("propertyPath") String propertyPath,
        @QueryParam("output") String output, @QueryParam("callback") String callback,
        @QueryParam("prettyPrint") String prettyPrint, @Context UriInfo uriInfo) {

    boolean prettyPrintEnabled = ContentApiUtils.isPrettyPrintEnabled(prettyPrint);

    // URL-based negotiation overrides any Accept header sent by the client
    //i.e. if the url specifies the desired response type in the "output" parameter this method
    // will return the media type specified in "output" request parameter.
    Output outputEnum = Output.XML;
    if (StringUtils.isNotBlank(output)) {
        outputEnum = Output.valueOf(output.toUpperCase());

        if (outputEnum != Output.XSD && asrtoboaBuiltInModelIsRequested(propertyPath)) {
            //User has requested astroboa-model or astroboa-api built in schemata
            //but at the same time, the "output" request parameter was not XSD
            //In this case an HTTP NOT FOUND error should be returned.
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        //User did not provide value for the "output" parameter therefore 
        //the output at this point is XML. However there is one case where the
        //user may have provide the suffix ".xsd" in the URL, requesting this
        //way the output to be an XML Schema. This case can only be traced by 
        //examining the path of the request and whether it ends in ".xsd" or not
        String path = uriInfo.getPath();

        if (StringUtils.endsWith(path, ".xsd")) {
            //User has provided the suffix ".xsd". 
            //Therefore an XML Schema sholud be returned
            //We have to attach the suffix to the propertyPath variable
            //since the user may have specified a filename instead of 
            //a property path.
            outputEnum = Output.XSD;
            if (propertyPath != null) {
                propertyPath += ".xsd";
            }
        }
    }

    return getDefinitionInternal(propertyPath, outputEnum, callback, prettyPrintEnabled);
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotFoundSetTTL() throws IOException {
    try {/* w ww  .  j  av  a  2  s  .  co m*/
        streamClient.setTTL(TestUtils.NOT_FOUND_STREAM_NAME, STREAM_TTL);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getStatusCode());
    }
}

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

@Test
/**// w ww.  j ava  2  s.  co m
 * Tests accessing a workspace file <del>and remote URL</del> that are part of a running site.
 */
public void testSiteAccess() throws SAXException, IOException, JSONException, URISyntaxException {
    // Create file in workspace
    final String filename = "foo.html";
    final String fileContent = "<html><body>This is a test file</body></html>";
    createFileOnServer("", filename, fileContent);

    // Create a site that exposes the workspace file
    final String siteName = "My hosted site";
    //make absolute by adding test project path
    IPath path = new Path(URI.create(makeResourceURIAbsolute(filename)).getPath());
    while (path.segmentCount() != 0 && !path.segment(0).equals("file")) {
        if (path.segment(0).equals("file")) {
            break;
        }
        path = path.removeFirstSegments(1);
    }
    String filePath = path.toString();
    if (filePath.startsWith("/")) {
        filePath = filePath.substring(1);
    }
    //remove file segment to get the servlet-relative path
    Assert.assertTrue(filePath.startsWith("file/"));
    filePath = filePath.substring(5);
    final String mountAt = "/file.html";

    final JSONArray mappings = makeMappings(new String[][] { { mountAt, filePath } });
    WebRequest createSiteReq = getCreateSiteRequest(siteName, workspaceId, mappings, null);
    WebResponse createSiteResp = webConversation.getResponse(createSiteReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode());
    JSONObject siteObject = new JSONObject(createSiteResp.getText());

    // Start the site
    String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION);
    siteObject = startSite(location);

    final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS);
    final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL);

    // Access the workspace file through the site
    WebRequest getFileReq = new GetMethodWebRequest(hostedURL + mountAt);
    WebResponse getFileResp = webConversation.getResponse(getFileReq);
    assertEquals(fileContent, getFileResp.getText());

    // Stop the site
    stopSite(location);

    // Check that the workspace file can't be accessed anymore
    WebRequest getFile404Req = new GetMethodWebRequest(hostedURL + mountAt);
    WebResponse getFile404Resp = webConversation.getResponse(getFile404Req);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getFile404Resp.getResponseCode());
    assertEquals("no-cache", getFile404Resp.getHeaderField("Cache-Control").toLowerCase());
}

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

/**
 * Check if we have the required permissions for nexus staging.
 * //  w w  w. j av  a 2  s  . c  o  m
 * @return
 * @throws StageException if an exception occurred whilst checking the authorisation.
 */
public void checkAuthentication() throws StageException {
    try {
        URL url = new URL(nexusURL.toString() + "/service/local/status");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        addAuthHeader(conn);
        int status = conn.getResponseCode();
        if (status == 200) {
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(conn.getInputStream());
            /*
             * check for the following permissions:
             */
            String[] requiredPerms = new String[] { "nexus:stagingprofiles", "nexus:stagingfinish",
                    // "nexus:stagingpromote",
                    "nexus:stagingdrop" };

            XPath xpath = XPathFactory.newInstance().newXPath();
            for (String perm : requiredPerms) {
                String expression = "//clientPermissions/permissions/permission[id=\"" + perm + "\"]/value";
                Node node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
                if (node == null) {
                    throw new StageException(
                            "Invalid reponse from server - is the URL a Nexus Professional server?");
                }
                int val = Integer.parseInt(node.getTextContent());
                if (val == 0) {
                    throw new StageException(
                            "User has insufficient privaledges to perform staging actions (" + perm + ")");
                }
            }
        } 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("Service not found - is this a Nexus server?");
            } else {
                throw new IOException("Server returned error code " + status + ".");
            }
        }
    } catch (IOException ex) {
        throw createStageExceptionForIOException(nexusURL, ex);
    } catch (XPathException ex) {
        throw new StageException(ex);
    } catch (ParserConfigurationException ex) {
        throw new StageException(ex);
    } catch (SAXException ex) {
        throw new StageException(ex);
    }
}

From source file:org.lockss.config.HTTPConfigFile.java

private InputStream getUrlInputStream0(String url) throws IOException, MalformedURLException {
    InputStream in = null;//ww w .j av a  2  s.c om
    LockssUrlConnection conn = openUrlConnection(url);

    Configuration conf = ConfigManager.getPlatformConfig();
    String proxySpec = conf.get(ConfigManager.PARAM_PROPS_PROXY);
    String proxyHost = null;
    int proxyPort = 0;

    try {
        HostPortParser hpp = new HostPortParser(proxySpec);
        proxyHost = hpp.getHost();
        proxyPort = hpp.getPort();
    } catch (HostPortParser.InvalidSpec e) {
        log.warning("Illegal props proxy: " + proxySpec, e);
    }

    if (proxyHost != null) {
        log.debug2("Setting request proxy to: " + proxyHost + ":" + proxyPort);
        conn.setProxy(proxyHost, proxyPort);
    }
    if (m_config != null && m_lastModified != null) {
        log.debug2("Setting request if-modified-since to: " + m_lastModified);
        conn.setIfModifiedSince(m_lastModified);
    }
    conn.setRequestProperty("Accept-Encoding", "gzip");

    if (m_props != null) {
        Object x = m_props.get(Constants.X_LOCKSS_INFO);
        if (x instanceof String) {
            conn.setRequestProperty(Constants.X_LOCKSS_INFO, (String) x);
        }
    }
    conn.execute();
    if (checkAuth && !conn.isAuthenticatedServer()) {
        IOUtil.safeRelease(conn);
        throw new IOException("Config server not authenticated");
    }

    int resp = conn.getResponseCode();
    String respMsg = conn.getResponseMessage();
    log.debug2(url + " request got response: " + resp + ": " + respMsg);
    switch (resp) {
    case HttpURLConnection.HTTP_OK:
        m_loadError = null;
        m_httpLastModifiedString = conn.getResponseHeaderValue("last-modified");
        log.debug2("New file, or file changed.  Loading file from " + "remote connection:" + url);
        in = conn.getUncompressedResponseInputStream();
        break;
    case HttpURLConnection.HTTP_NOT_MODIFIED:
        m_loadError = null;
        log.debug2("HTTP content not changed, not reloading.");
        IOUtil.safeRelease(conn);
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        m_loadError = resp + ": " + respMsg;
        IOUtil.safeRelease(conn);
        throw new FileNotFoundException(m_loadError);
    case HttpURLConnection.HTTP_FORBIDDEN:
        m_loadError = findErrorMessage(resp, conn);
        IOUtil.safeRelease(conn);
        throw new IOException(m_loadError);
    default:
        m_loadError = resp + ": " + respMsg;
        IOUtil.safeRelease(conn);
        throw new IOException(m_loadError);
    }

    return in;
}

From source file:org.okj.im.core.service.QQHttpService.java

/**
 * ?//from  w w w  .  ja v a  2s. co m
 * @param conn
 * @return
 */
protected boolean checkResponseCode(final HttpURLConnection conn) {
    boolean success = false;

    //?false;
    if (conn == null) {
        return false;
    }

    try {
        InputStream is = conn.getInputStream();
        if (is == null) {
            return false;
        }

        InputStream isrs = conn.getErrorStream();
        if (isrs != null) {
            return false;
        }

        int status = conn.getResponseCode();
        switch (status) {
        case java.net.HttpURLConnection.HTTP_GATEWAY_TIMEOUT://504
            LogUtils.warn(LOGGER, "! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_FORBIDDEN://403
            LogUtils.warn(LOGGER, "?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_INTERNAL_ERROR://500
            LogUtils.warn(LOGGER, "WebQQ?! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_NOT_FOUND://404
            LogUtils.warn(LOGGER, "??! status{0}", status);
            break;
        case java.net.HttpURLConnection.HTTP_OK:
            LogUtils.warn(LOGGER, "Connect OK! status{0}", status);
            success = true;
        }
    } catch (IOException ex) {
        LogUtils.error(LOGGER, "??", ex);
    }
    return success;
}

From source file:com.murrayc.galaxyzoo.app.provider.test.ZooniverseClientTest.java

public void testMoreItemsWithBadResponseCode() throws IOException {
    final MockWebServer server = new MockWebServer();

    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    response.setBody("test nonsense failure message");
    server.enqueue(response);/*from w  w  w.  j ava2 s.co m*/
    server.play();

    final ZooniverseClient client = createZooniverseClient(server);

    //Mostly we want to check that it doesn't crash on a bad HTTP response.

    try {
        final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(5);
        assertTrue((subjects == null) || (subjects.isEmpty()));
    } catch (final ZooniverseClient.RequestMoreItemsException e) {
        assertTrue(e.getCause() instanceof ExecutionException);
    }

    server.shutdown();
}

From source file:org.eclipse.hono.service.auth.device.CredentialsApiAuthProvider.java

@Override
public final void authenticate(final DeviceCredentials deviceCredentials,
        final Handler<AsyncResult<Device>> resultHandler) {

    Objects.requireNonNull(deviceCredentials);
    Objects.requireNonNull(resultHandler);
    Future<Device> validationResult = Future.future();
    validationResult.setHandler(resultHandler);

    getCredentialsForDevice(deviceCredentials).recover(t -> {
        final ServiceInvocationException e = (ServiceInvocationException) t;
        if (e.getErrorCode() == HttpURLConnection.HTTP_NOT_FOUND) {
            return Future.failedFuture(
                    new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials"));
        } else {/*from www  .  ja  va  2 s . c  om*/
            return Future.failedFuture(t);
        }
    }).map(credentialsOnRecord -> {
        if (deviceCredentials.validate(credentialsOnRecord)) {
            return new Device(deviceCredentials.getTenantId(), credentialsOnRecord.getDeviceId());
        } else {
            throw new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "invalid credentials");
        }
    }).setHandler(resultHandler);
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public synchronized boolean checkConnection() {
    int code = this.digitalSTROMClient.checkConnection(sessionToken);
    switch (code) {
    case HttpURLConnection.HTTP_OK:
        if (!lostConnectionState) {
            lostConnectionState = true;//from w  ww .  java  2  s  .  c  o  m
            onConnectionResumed();
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        lostConnectionState = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (this.genAppToken) {
            if (StringUtils.isNotBlank(config.getAppToken())) {
                sessionToken = this.digitalSTROMClient.loginApplication(config.getAppToken());
            } else {
                this.onNotAuthenticated();
            }
        } else {
            sessionToken = this.digitalSTROMClient.login(this.config.getUserName(), this.config.getPassword());
        }
        if (sessionToken != null) {
            if (!lostConnectionState) {
                onConnectionResumed();
                lostConnectionState = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            lostConnectionState = false;
        }
        break;
    case -2:
        onConnectionLost(ConnectionListener.INVALID_URL);
        lostConnectionState = false;
        break;
    case -3:
    case -4:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        lostConnectionState = false;
        break;
    case -1:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case -5:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        lostConnectionState = false;
        break;
    }
    return lostConnectionState;
}