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.orion.server.tests.servlets.files.AdvancedFilesTest.java

@Test
public void testGetNonExistingFile() throws IOException, SAXException {
    WebRequest request = getGetFilesRequest("does/not/exists/directory");
    WebResponse response = webConversation.getResponse(request);
    assertEquals("Retriving non existing directory return wrong response code.",
            HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

    request = getGetFilesRequest("does/not/exists/directory?depth=5");
    response = webConversation.getResponse(request);
    assertEquals("Retriving non existing directory return wrong response code.",
            HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
}

From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java

public void testCreateTooManyGuestUsers() throws IOException, Exception {
    // Limit to 2 guest users
    IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(ServerConstants.PREFERENCE_SCOPE);
    int oldLimitValue = prefs.getInt(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST_LIMIT, 100);
    String oldGuestValue = prefs.get(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST, null);
    prefs.put(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST, "true");
    prefs.putInt(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST_LIMIT, 2);
    prefs.flush();/*from  ww  w.java2  s. c  om*/
    try {
        WebConversation webConversation = new WebConversation();
        webConversation.setExceptionsThrownOnErrorStatus(false);
        JSONObject[] guests = { null, null, null };

        // Create guest user with only a Name
        Map<String, String> params = new HashMap<String, String>();
        params.put("guest", null);
        WebRequest request = getPostUsersRequest("", params, true);

        WebResponse response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
        guests[0] = new JSONObject(response.getText());

        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
        guests[1] = new JSONObject(response.getText());

        // This POST should cause the 0th guest to be deleted
        response = webConversation.getResponse(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
        guests[2] = new JSONObject(response.getText());

        // Try to get the 0th guest -- should be gone
        request = getAuthenticatedRequest(guests[0].getString(ProtocolConstants.KEY_LOCATION), METHOD_GET,
                true);
        response = webConversation.getResource(request);
        assertEquals(response.getText(), HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

        // Delete remaining users
        for (int i = 1; i < guests.length; i++) {
            request = getAuthenticatedRequest(guests[i].getString(ProtocolConstants.KEY_LOCATION),
                    METHOD_DELETE, true);
            response = webConversation.getResource(request);
            assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());
        }
    } finally {
        prefs.put(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST, oldGuestValue);
        prefs.putInt(ServerConstants.CONFIG_AUTH_USER_CREATION_GUEST_LIMIT, oldLimitValue);
    }
}

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

TenantResult<JsonObject> getTenantResult(final String tenantId) {

    final TenantObject tenant = tenants.get(tenantId);

    if (tenant == null) {
        return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
    } else {/*ww  w .  j av a  2 s  . co m*/
        return TenantResult.from(HttpURLConnection.HTTP_OK, JsonObject.mapFrom(tenant),
                CacheDirective.maxAgeDirective(MAX_AGE_GET_TENANT));
    }
}

From source file:org.intermine.webservice.client.util.HttpConnection.java

/**
 * Handles an error response received while executing a service request.
 * Throws a {@link ServiceException} or one of its subclasses, depending on
 * the failure conditions./*from  w w  w  . j  a va  2  s.co m*/
 *
 * @throws ServiceException exception describing the failure.
 * @throws IOException error reading the error response from the
 *         service.
 */
protected void handleErrorResponse() throws IOException {

    String message = executedMethod.getResponseBodyAsString();
    try {
        JSONObject jo = new JSONObject(message);
        message = jo.getString("error");
    } catch (JSONException e) {
        // Pass
    }

    switch (executedMethod.getStatusCode()) {

    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new ResourceNotFoundException(this);

    case HttpURLConnection.HTTP_BAD_REQUEST:
        if (message != null) {
            throw new BadRequestException(message);
        } else {
            throw new BadRequestException(this);
        }
    case HttpURLConnection.HTTP_FORBIDDEN:
        if (message != null) {
            throw new ServiceForbiddenException(message);
        } else {
            throw new ServiceForbiddenException(this);
        }
    case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
        throw new NotImplementedException(this);

    case HttpURLConnection.HTTP_INTERNAL_ERROR:
        if (message != null) {
            throw new InternalErrorException(message);
        } else {
            throw new InternalErrorException(this);
        }
    case HttpURLConnection.HTTP_UNAVAILABLE:
        throw new ServiceUnavailableException(this);

    default:
        if (message != null) {
            throw new ServiceException(message);
        } else {
            throw new ServiceException(this);
        }
    }
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void findCarByDriver(String username) {

    String servlet = "FindCarByDriver";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CAR_BY_DRIVER_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();//from  w  w  w . j av  a2 s  . c  o m

}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilterTest.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 w  w  w  .j  a  v a 2s.c om
* Manual Test: wget -d --server-response --header='Accept-Encoding: gzip'  http://localhost:9080/non_ok/PageNotFoundGzip.jsp
*/
public void testNotFound() throws Exception {

    String url = "http://localhost:9080/non_ok/PageNotFoundGzip.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.apache.hadoop.hdfs.tools.offlineImageViewer.TestOfflineImageViewerForAcl.java

@Test
public void testWebImageViewerForAcl() throws Exception {
    WebImageViewer viewer = new WebImageViewer(NetUtils.createSocketAddr("localhost:0"));
    try {/*from w ww.  ja  va2 s  . c o m*/
        viewer.initServer(originalFsimage.getAbsolutePath());
        int port = viewer.getPort();

        // create a WebHdfsFileSystem instance
        URI uri = new URI("webhdfs://localhost:" + String.valueOf(port));
        Configuration conf = new Configuration();
        WebHdfsFileSystem webhdfs = (WebHdfsFileSystem) FileSystem.get(uri, conf);

        // GETACLSTATUS operation to a directory without ACL
        AclStatus acl = webhdfs.getAclStatus(new Path("/dirWithNoAcl"));
        assertEquals(writtenAcls.get("/dirWithNoAcl"), acl);

        // GETACLSTATUS operation to a directory with a default ACL
        acl = webhdfs.getAclStatus(new Path("/dirWithDefaultAcl"));
        assertEquals(writtenAcls.get("/dirWithDefaultAcl"), acl);

        // GETACLSTATUS operation to a file without ACL
        acl = webhdfs.getAclStatus(new Path("/noAcl"));
        assertEquals(writtenAcls.get("/noAcl"), acl);

        // GETACLSTATUS operation to a file with a ACL
        acl = webhdfs.getAclStatus(new Path("/withAcl"));
        assertEquals(writtenAcls.get("/withAcl"), acl);

        // GETACLSTATUS operation to a file with several ACL entries
        acl = webhdfs.getAclStatus(new Path("/withSeveralAcls"));
        assertEquals(writtenAcls.get("/withSeveralAcls"), acl);

        // GETACLSTATUS operation to a invalid path
        URL url = new URL("http://localhost:" + port + "/webhdfs/v1/invalid/?op=GETACLSTATUS");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, connection.getResponseCode());
    } finally {
        // shutdown the viewer
        viewer.close();
    }
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void findCarsByOwner(String username) {

    String servlet = "FindCarsByOwner";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_OK, GodotMessage.Entity.CARS_BY_OWNER_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Error.NOT_FOUND);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();//from  ww  w  .ja  va 2 s .  co  m

}

From source file:org.wso2.carbon.registry.app.RemoteRegistry.java

public Resource get(String path) throws RegistryException {
    AbderaClient abderaClient = new AbderaClient(abdera);
    ClientResponse clientResponse;//from w  w w  .ja  v a  2  s .c o  m
    String encodedPath;
    // If the request is to fetch all comments for a given path, then encode ":" as well to
    // avoid confusion with versioned paths.
    if (path.endsWith(RegistryConstants.URL_SEPARATOR + APPConstants.PARAMETER_COMMENTS)) {
        encodedPath = encodeURL(path);
        if (encodedPath.contains(RegistryConstants.VERSION_SEPARATOR)) {
            int index = encodedPath.lastIndexOf(RegistryConstants.VERSION_SEPARATOR);
            encodedPath = encodedPath.substring(0, index).replace(":", "%3A") + encodedPath.substring(index);
        } else {
            encodedPath = encodedPath.replace(":", "%3A");
        }
    } else {
        encodedPath = encodeURL(path);
    }
    if (!cache.isResourceCached(path)) {
        clientResponse = abderaClient.get(baseURI + "/atom" + encodedPath, getAuthorization());
    } else {
        clientResponse = abderaClient.get(baseURI + "/atom" + encodedPath, getAuthorizationForCaching(path));
    }
    if (clientResponse.getType() == Response.ResponseType.CLIENT_ERROR
            || clientResponse.getType() == Response.ResponseType.SERVER_ERROR) {
        if (clientResponse.getStatus() == HttpURLConnection.HTTP_NOT_FOUND) {
            abderaClient.teardown();
            throw new ResourceNotFoundException(path);
        }
        abderaClient.teardown();
        throw new RegistryException(clientResponse.getStatusText());
    }

    if (clientResponse.getStatus() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        abderaClient.teardown();
        /*do caching here */
        log.debug("Cached resource returned since no modification has been done on the resource");
        return cache.getCachedResource(path);
    }
    String eTag = clientResponse.getHeader("ETag");
    Element introspection = clientResponse.getDocument().getRoot();
    ResourceImpl resource;
    if (introspection instanceof Feed) {
        // This is a collection
        Feed feed = (Feed) introspection;
        String state = feed.getSimpleExtension(new QName(APPConstants.NAMESPACE, APPConstants.NAMESPACE_STATE));
        if (state != null && state.equals("Deleted")) {
            abderaClient.teardown();
            throw new ResourceNotFoundException(path);
        }
        resource = createResourceFromFeed(feed);
    } else {
        Entry entry = (Entry) introspection;
        resource = createResourceFromEntry(entry);
    }
    /* if the resource is not Get before  add it to cache before adding it check the max cache
    or if the resource is modified then new resource is replacing the current resource in the cache
    * size configured in registry.xml */
    if (!cache.cacheResource(path, resource, eTag, RegistryConstants.MAX_REG_CLIENT_CACHE_SIZE)) {
        log.debug("Max Cache size exceeded the configured Cache size");
    }

    abderaClient.teardown();
    //        resource.setPath(path);
    return resource;
}

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

/**
 * Get jobs for given filter criteria.//from www  . jav a  2  s  .  co  m
 *
 * @param id          id for job
 * @param name        name of job (can be a SQL-style pattern such as HIVE%)
 * @param userName    user who submitted job
 * @param statuses    statuses of jobs to find
 * @param tags        tags for the job
 * @param clusterName the name of the cluster
 * @param clusterId   the id of the cluster
 * @param commandName the name of the command run by the job
 * @param commandId   the id of the command run by the job
 * @param page        page number for job
 * @param limit       max number of jobs to return
 * @param descending  Whether the order of the results should be descending or ascending
 * @param orderBys    Fields to order the results by
 * @return successful response, or one with HTTP error code
 * @throws GenieException For any error
 */
@GET
@ApiOperation(value = "Find jobs", notes = "Find jobs by the submitted criteria.", response = Job.class, responseContainer = "List")
@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 List<Job> getJobs(@ApiParam(value = "Id of the job.") @QueryParam("id") final String id,
        @ApiParam(value = "Name of the job.") @QueryParam("name") final String name,
        @ApiParam(value = "Name of the user who submitted the job.") @QueryParam("userName") final String userName,
        @ApiParam(value = "Statuses of the jobs to fetch.", allowableValues = "INIT, RUNNING, SUCCEEDED, KILLED, FAILED") @QueryParam("status") final Set<String> statuses,
        @ApiParam(value = "Tags for the job.") @QueryParam("tag") final Set<String> tags,
        @ApiParam(value = "Name of the cluster on which the job ran.") @QueryParam("executionClusterName") final String clusterName,
        @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("executionClusterId") final String clusterId,
        @ApiParam(value = "The page to start on.") @QueryParam("commandName") final String commandName,
        @ApiParam(value = "Id of the cluster on which the job ran.") @QueryParam("commandId") final String commandId,
        @ApiParam(value = "The page to start on.") @QueryParam("page") @DefaultValue("0") final int page,
        @ApiParam(value = "Max number of results per page.") @QueryParam("limit") @DefaultValue("1024") final int limit,
        @ApiParam(value = "Whether results should be sorted in descending or ascending order. Defaults to descending") @QueryParam("descending") @DefaultValue("true") final boolean descending,
        @ApiParam(value = "The fields to order the results by. Must not be collection fields. Default is updated.") @QueryParam("orderBy") final Set<String> orderBys)
        throws GenieException {
    LOG.info("Called with [id | jobName | userName | statuses | executionClusterName "
            + "| executionClusterId | page | limit | descending | orderBys]");
    LOG.info(id + " | " + name + " | " + userName + " | " + statuses + " | " + tags + " | " + clusterName
            + " | " + clusterId + " | " + commandName + " | " + commandId + " | " + page + " | " + limit + " | "
            + descending + " | " + orderBys);
    Set<JobStatus> enumStatuses = null;
    if (!statuses.isEmpty()) {
        enumStatuses = EnumSet.noneOf(JobStatus.class);
        for (final String status : statuses) {
            if (StringUtils.isNotBlank(status)) {
                enumStatuses.add(JobStatus.parse(status));
            }
        }
    }

    return this.jobService.getJobs(id, name, userName, enumStatuses, tags, clusterName, clusterId, commandName,
            commandId, page, limit, descending, orderBys);
}