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:online.privacy.PrivacyOnlineApiRequest.java

private JSONObject makeAPIRequest(String method, String endPoint, String jsonPayload)
        throws IOException, JSONException {
    InputStream inputStream = null;
    OutputStream outputStream = null;
    String apiUrl = "https://api.privacy.online";
    String apiKey = this.context.getString(R.string.privacy_online_api_key);
    String keyString = "?key=" + apiKey;

    int payloadSize = jsonPayload.length();

    try {/*from  ww  w. j  a  v  a  2s. co m*/
        URL url = new URL(apiUrl + endPoint + keyString);
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        // Sec 5 second connect/read timeouts
        connection.setReadTimeout(5000);
        connection.setConnectTimeout(5000);
        connection.setRequestMethod(method);
        connection.setRequestProperty("Content-Type", "application/json");

        if (payloadSize > 0) {
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setFixedLengthStreamingMode(payloadSize);
        }

        // Initiate the connection
        connection.connect();

        // Write the payload if there is one.
        if (payloadSize > 0) {
            outputStream = connection.getOutputStream();
            outputStream.write(jsonPayload.getBytes("UTF-8"));
        }

        // Get the response code ...
        int responseCode = connection.getResponseCode();
        Log.e(LOG_TAG, "Response code: " + responseCode);

        switch (responseCode) {
        case HttpsURLConnection.HTTP_OK:
            inputStream = connection.getInputStream();
            break;
        case HttpsURLConnection.HTTP_FORBIDDEN:
            inputStream = connection.getErrorStream();
            break;
        case HttpURLConnection.HTTP_NOT_FOUND:
            inputStream = connection.getErrorStream();
            break;
        case HttpsURLConnection.HTTP_UNAUTHORIZED:
            inputStream = connection.getErrorStream();
            break;
        default:
            inputStream = connection.getInputStream();
            break;
        }

        String responseContent = "{}"; // Default to an empty object.
        if (inputStream != null) {
            responseContent = readInputStream(inputStream, connection.getContentLength());
        }

        JSONObject responseObject = new JSONObject(responseContent);
        responseObject.put("code", responseCode);

        return responseObject;

    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    }
}

From source file:poisondog.vfs.webdav.WebdavFileFactory.java

public InputStream get(String url) throws FileNotFoundException, IOException, DavException {
    final GetMethod getMethod = new GetMethod(mTask.process(url));
    final int status = executeNotClose(getMethod);
    if (status == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new FileNotFoundException(url);
    }/*from   w  w  w  .ja v  a 2s.  c  o  m*/
    if (status != HttpURLConnection.HTTP_OK) {
        throw new IOException("can't get " + url + "\nbecause response code is " + status);
    }
    return new HttpInputStream(getMethod);
}

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

@Test
public void testGetUnknownRemote() throws Exception {
    // clone a  repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);//from w w  w . j a v  a  2 s  .  c om

    // 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());
    JSONObject gitSection = project.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection);
    String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);

    request = getGetGitRemoteRequest(gitRemoteUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    JSONObject remotes = new JSONObject(response.getText());
    JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertEquals(1, remotesArray.length());
    JSONObject remote = remotesArray.getJSONObject(0);
    assertNotNull(remote);
    String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(remoteLocation);

    URI u = URI.create(toRelativeURI(remoteLocation));
    IPath p = new Path(u.getPath());
    p = p.uptoSegment(2).append("xxx").append(p.removeFirstSegments(3));
    URI nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), p.toString(), u.getQuery(),
            u.getFragment());

    request = getGetGitRemoteRequest(nu.toString());
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response);
    assertEquals(status.toString(), status.getHttpCode(), HttpURLConnection.HTTP_NOT_FOUND);

    p = new Path(u.getPath());
    p = p.uptoSegment(3).append("xxx").append(p.removeFirstSegments(3));
    nu = new URI(u.getScheme(), u.getUserInfo(), u.getHost(), u.getPort(), p.toString(), u.getQuery(),
            u.getFragment());

    request = getGetGitRemoteRequest(nu.toString());
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

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

/**
 * Get job status for give job id./* www .j a v a  2  s  .co m*/
 *
 * @param id id for job to look up
 * @return The status of the job
 * @throws GenieException For any error
 */
@GET
@Path("/{id}/status")
@ApiOperation(value = "Get the status of the job ", notes = "Get the status of job whose id is sent", response = String.class)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid id supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public ObjectNode getJobStatus(
        @ApiParam(value = "Id of the job.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called for job id:" + id);
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode node = mapper.createObjectNode();
    node.put("status", this.jobService.getJobStatus(id).toString());
    return node;
}

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

/**
 * Test behavior when controller URL has been set to a non-existent location.
 *
 * @throws IOException if something happens to the connection, invalid URL path should only
 *                     result an HTTP error code
 *///from www.  j ava  2  s.c  o  m
public void testVerifyControllerWrongURL() throws IOException {
    try {
        //if (!wifi.isWifiEnabled())
        //  fail(wifiRequired());

        AppSettingsModel.setCurrentPanelIdentity(ctx, "something");

        HttpResponse response = ORNetworkCheck.verifyControllerURL(ctx,
                "http://controller.openremote.org/nothing/here");

        assertNotNull("Got null HTTP response, was expecting: " + HttpURLConnection.HTTP_NOT_FOUND, response);

        int status = response.getStatusLine().getStatusCode();

        assertTrue("Was expecting 404, got " + status, status == HttpURLConnection.HTTP_NOT_FOUND);
    } finally {
        AppSettingsModel.setCurrentPanelIdentity(ctx, null);
    }
}

From source file:org.jboss.as.test.manualmode.web.valve.authenticator.GlobalAuthenticatorTestCase.java

/**
 * Testing that if authenticator valve is disabled then it is not used
 *//*from ww w .  java 2 s.co  m*/
@Test
@InSequence(10)
@OperateOnDeployment(value = DEPLOYMENT_NAME_2)
public void testValveAuthDisable(@ArquillianResource URL url, @ArquillianResource ManagementClient client)
        throws Exception {
    ValveUtil.activateValve(client, CUSTOM_AUTHENTICATOR_2, false);
    ValveUtil.reload(client);
    String appUrl = url.toExternalForm() + WEB_APP_URL_2;
    Header[] valveHeaders = ValveUtil.hitValve(new URL(appUrl), HttpURLConnection.HTTP_NOT_FOUND);
    assertEquals("Auth valve is disabled => expecting no valve headers: " + Arrays.toString(valveHeaders), 0,
            valveHeaders.length);
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

private double getAvail(int code) {
    // There are too many options to list everything that is
    // successful. So, instead we are going to call out the
    // things that should be considered failure, everything else
    // is OK./*from  w w w. j  av a2 s .c  om*/
    switch (code) {
    case HttpURLConnection.HTTP_BAD_REQUEST:
    case HttpURLConnection.HTTP_FORBIDDEN:
    case HttpURLConnection.HTTP_NOT_FOUND:
    case HttpURLConnection.HTTP_BAD_METHOD:
    case HttpURLConnection.HTTP_CLIENT_TIMEOUT:
    case HttpURLConnection.HTTP_CONFLICT:
    case HttpURLConnection.HTTP_PRECON_FAILED:
    case HttpURLConnection.HTTP_ENTITY_TOO_LARGE:
    case HttpURLConnection.HTTP_REQ_TOO_LONG:
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
    case HttpURLConnection.HTTP_UNAVAILABLE:
    case HttpURLConnection.HTTP_VERSION:
    case HttpURLConnection.HTTP_BAD_GATEWAY:
    case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
        return Metric.AVAIL_DOWN;
    default:
    }

    if (hasCredentials()) {
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            return Metric.AVAIL_DOWN;
        }
    }

    return Metric.AVAIL_UP;
}

From source file:i5.las2peer.services.servicePackage.TemplateService.java

/**
 * Example method that shows how to retrieve a user email address from a database 
 * and return an HTTP response including a JSON object.
 * /*from   ww  w .  j a v a2  s  .co  m*/
 * WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! 
 * IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.
 * 
 */
@GET
@Path("/userEmail/{username}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "User Email"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "User not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal Server Error") })
@ApiOperation(value = "Email Address Administration", notes = "Example method that retrieves a user email address from a database."
        + " WARNING: THIS METHOD IS ONLY FOR DEMONSTRATIONAL PURPOSES!!! "
        + "IT WILL REQUIRE RESPECTIVE DATABASE TABLES IN THE BACKEND, WHICH DON'T EXIST IN THE TEMPLATE.")
public HttpResponse getUserEmail(@PathParam("username") String username) {
    String result = "";
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    try {

        // get connection from connection pool
        conn = dbm.getConnection();

        // prepare statement
        stmnt = conn.prepareStatement("SELECT email FROM users WHERE username = ?;");
        stmnt.setString(1, username);

        // retrieve result set
        rs = stmnt.executeQuery();

        // process result set
        if (rs.next()) {
            result = rs.getString(1);

            // setup resulting JSON Object
            JSONObject ro = new JSONObject();
            ro.put("email", result);

            // return HTTP Response on success
            return new HttpResponse(ro.toString(), HttpURLConnection.HTTP_OK);
        } else {
            result = "No result for username " + username;

            // return HTTP Response on error
            return new HttpResponse(result, HttpURLConnection.HTTP_NOT_FOUND);
        }
    } catch (Exception e) {
        // return HTTP Response on error
        return new HttpResponse("Internal error: " + e.getMessage(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        // free resources
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (stmnt != null) {
            try {
                stmnt.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                Context.logError(this, e.getMessage());

                // return HTTP Response on error
                return new HttpResponse("Internal error: " + e.getMessage(),
                        HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        }
    }
}

From source file:sonata.kernel.vimadaptor.wrapper.openstack.OpenStackMistralClient.java

/**
 * Updates / inserts (creates) a workflow.
 * <p>//from   ww  w  .  j a v a2 s .  co  m
 * First try to update the workflow for performance reasons as the workflow probably already
 * exists.
 *
 * @param workflowDsl The DSL of the action
 * @return The created / updated workflow.
 */
private Workflow upsertWorkflow(String workflowDsl) throws RuntimeException {

    Logger.info("call upsertWorkflow - update/insert Muistral workflow");

    try {
        return mistralClient.workflowUpdate(workflowDsl);
    } catch (MistralHttpException e) {
        if (e.getHttpStatus() != HttpURLConnection.HTTP_NOT_FOUND) {
            throw new RuntimeException("Could not update Mistral workflow with DSL [" + workflowDsl + "]", e);
        } // else workflow does not exist - continue with creation
    }

    try {
        return mistralClient.workflowCreate(workflowDsl);

    } catch (MistralHttpException e) {
        throw new RuntimeException("Could not create Mistral workflow with DSL [" + workflowDsl + "]", e);
    }

}

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

@MethodMapping(value = "/hsspresult/{id}", httpMethod = HttpMethod.GET, produces = RestMimeTypes.TEXT_PLAIN)
public String hsspResult(String id) {

    if (Config.isXmlOnly()) {

        log.warn("rest/hsspresult was requested, but not enabled");

        // hssp job submission is not allowed if hssp is turned off
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_NOT_FOUND);
    }//from   w ww  . j  a v  a2s  .com

    File hsspFile = new File(Config.getHSSPCacheDir(), id + ".hssp.bz2");

    String jobStatus = this.status(id);

    try {

        if (jobStatus.equals("SUCCESS") && hsspFile.isFile()) {

            StringWriter sw = new StringWriter();
            InputStream hsspIn = new BZip2CompressorInputStream(new FileInputStream(hsspFile));
            IOUtils.copy(hsspIn, sw);
            hsspIn.close();
            sw.close();

            return sw.toString();
        }

        URL url = new URL(hsspRestURL + "/result/pdb_file/hssp_stockholm/" + id + "/");

        Writer writer = new StringWriter();
        IOUtils.copy(url.openStream(), writer);
        writer.close();

        JSONObject output = new JSONObject(writer.toString());

        String result = output.getString("result");

        if (jobStatus.equals("SUCCESS") && Config.hsspPdbCacheEnabled()) {

            // Write it to the cache:
            OutputStream fileOut = new BZip2CompressorOutputStream(new FileOutputStream(hsspFile));
            IOUtils.write(result, fileOut);
            fileOut.close();
        } else
            return "";

        return result;

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new AbortWithHttpErrorCodeException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}