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.netflix.genie.server.resources.JobResource.java

/**
 * Update the tags for a given job./*from w  w  w. j a v  a 2 s  .c om*/
 *
 * @param id   The id of the job to update the tags for.
 *             Not null/empty/blank.
 * @param tags The tags to replace existing configuration
 *             files with. Not null/empty/blank.
 * @return The new set of job tags.
 * @throws GenieException For any error
 */
@PUT
@Path("/{id}/tags")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Update tags for a job", notes = "Replace the existing tags for job with given id.", response = String.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Bad Request"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Job for id does not exist."),
        @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> updateTagsForJob(
        @ApiParam(value = "Id of the job to update tags for.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The tags to replace existing with.", required = true) final Set<String> tags)
        throws GenieException {
    LOG.info("Called with id " + id + " and tags " + tags);
    return this.jobService.updateTagsForJob(id, tags);
}

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

@Override
public boolean checkConnection(int code) {
    switch (code) {
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_OK:
        if (!connectionEstablished) {
            connectionEstablished = true;
            onConnectionResumed();/*w  ww.jav a  2s . c  o m*/
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        connectionEstablished = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        getNewSessionToken();
        if (sessionToken != null) {
            if (!connectionEstablished) {
                onConnectionResumed();
                connectionEstablished = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            connectionEstablished = false;
        }
        break;
    case ConnectionManager.MALFORMED_URL_EXCEPTION:
        onConnectionLost(ConnectionListener.INVALID_URL);
        connectionEstablished = false;
        break;
    case ConnectionManager.CONNECTION_EXCEPTION:
    case ConnectionManager.SOCKET_TIMEOUT_EXCEPTION:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        connectionEstablished = false;
        break;
    case ConnectionManager.GENERAL_EXCEPTION:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case ConnectionManager.UNKNOWN_HOST_EXCEPTION:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case ConnectionManager.AUTHENTIFICATION_PROBLEM:
        if (connListener != null) {
            if (config.getAppToken() != null) {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_APP_TOKEN);
            } else {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_USER_OR_PASSWORD);
            }
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        connectionEstablished = false;
        break;
    }
    return connectionEstablished;
}

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

@Test
public void testRemoteProxyRequest() throws SAXException, IOException, JSONException, URISyntaxException {
    final String siteName = "My remote hosting site";
    final String remoteRoot = "/remoteWeb", remotePrefPath = "/remotePref", remoteFilePath = "/remoteFile";

    final JSONArray mappings = makeMappings(new String[][] { { remoteRoot, SERVER_LOCATION },
            { remoteFilePath, SERVER_LOCATION + FILE_SERVLET_LOCATION },
            { remotePrefPath, SERVER_LOCATION + "/prefs" } });
    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);//from w w w. j av a  2 s . c o m

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

    // Access the remote URL through the site
    WebRequest getRemoteUrlReq = new GetMethodWebRequest(hostedURL + remoteRoot);
    WebResponse getRemoteUrlResp = webConversation.getResource(getRemoteUrlReq);
    final String lowerCaseContent = getRemoteUrlResp.getText().toLowerCase();
    assertEquals("Looks like our orion jetty server", true,
            lowerCaseContent.contains("orion") || lowerCaseContent.contains("jetty"));

    // Test that we can invoke the Orion file API through the site, to create a file
    final String fileName = "fizz.txt";
    final String fileContent = "Created through a site";
    createFileOnServer(hostedURL + remoteFilePath + testProjectBaseLocation, fileName, fileContent);

    // Bugs 369813, 366098, 369811, 390732: ensure query parameters are passed through the site unmangled
    // For this we'll call the 'prefs' API which uses query parameters
    String prefKey = "foo[-]bar baz+quux";
    String prefValue = "pref value";
    String remotePrefUrl = hostedURL + remotePrefPath + "/user";
    WebRequest putPrefReq = createSetPreferenceRequest(remotePrefUrl, prefKey, prefValue);
    setAuthentication(putPrefReq);
    WebResponse putPrefResp = webConversation.getResponse(putPrefReq);
    assertEquals(HttpURLConnection.HTTP_NO_CONTENT, putPrefResp.getResponseCode());

    // Check pref value
    WebRequest getPrefReq = new GetMethodWebRequest(remotePrefUrl + "?key=" + URLEncoder.encode(prefKey));
    setAuthentication(getPrefReq);
    WebResponse getPrefResp = webConversation.getResponse(getPrefReq);
    assertEquals(HttpURLConnection.HTTP_OK, getPrefResp.getResponseCode());
    JSONObject prefObject = new JSONObject(getPrefResp.getText());
    assertEquals("Pref obtained through site has correct value", prefObject.optString(prefKey), prefValue);

    // Stop the site
    stopSite(location);

    // Check that remote URL can't be accessed anymore
    WebRequest getRemoteUrl404Req = new GetMethodWebRequest(hostedURL + remoteRoot);
    WebResponse getRemoteUrl404Resp = webConversation.getResponse(getRemoteUrl404Req);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getRemoteUrl404Resp.getResponseCode());
}

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

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

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

/** {@inheritDoc} */
@Override//from  ww  w  . j a va  2s . co  m
public JobStatusResponse killJob(String jobId) {
    logger.info("called for jobId: " + jobId);

    JobStatusResponse response;

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

    // do some basic error handling
    if (jInfo == null) {
        String msg = "Job not found: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_NOT_FOUND, msg));
        return response;
    }

    // check if it is done already
    if (jInfo.getStatus().equalsIgnoreCase("SUCCEEDED") || jInfo.getStatus().equalsIgnoreCase("KILLED")
            || jInfo.getStatus().equalsIgnoreCase("FAILED")) {
        // job already exited, return status to user
        response = new JobStatusResponse();
        response.setStatus(jInfo.getStatus());
        response.setMessage("Job " + jobId + " is already done");
        return response;
    } else if (jInfo.getStatus().equalsIgnoreCase("INIT") || (jInfo.getProcessHandle() == -1)) {
        // can't kill a job if it is still initializing
        String msg = "Unable to kill job as it is still initializing: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, msg));
        return response;
    }

    // if we get here, job is still running - and can be killed

    // redirect to the right node if killURI points to a different node
    String killURI = jInfo.getKillURI();
    if (killURI == null) {
        String msg = "Failed to get killURI for jobID: " + jobId;
        logger.error(msg);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, msg));
        return response;
    }
    String localURI;
    try {
        localURI = getEndPoint() + "/" + jobResourcePrefix + "/" + jobId;
    } catch (CloudServiceException e) {
        logger.error("Error while retrieving local hostname: " + e.getMessage(), e);
        response = new JobStatusResponse(e);
        return response;
    }
    if (!killURI.equals(localURI)) {
        logger.debug("forwarding kill request to: " + killURI);
        response = forwardJobKill(killURI);
        return response;
    }

    // if we get here, killURI == localURI, and job should be killed here
    logger.debug("killing job on same instance: " + jobId);
    try {
        JobManagerFactory.getJobManager(jInfo.getJobType()).kill(jInfo);
    } catch (Exception e) {
        logger.error("Failed to kill job: ", e);
        response = new JobStatusResponse(new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR,
                "Failed to kill job: " + e.getCause()));
        return response;
    }

    jInfo.setJobStatus(JobStatus.KILLED, "Job killed on user request");
    jInfo.setExitCode(SubprocessStatus.JOB_KILLED.code());

    // increment counter for killed jobs
    stats.incrGenieKilledJobs();

    // update final status in DB
    ReentrantReadWriteLock rwl = PersistenceManager.getDbLock();
    try {
        logger.debug("updating job status to KILLED for: " + jobId);
        // acquire write lock first, and then update status
        // if job status changed between when it was read and now,
        // this thread will simply overwrite it - final state will be KILLED
        rwl.writeLock().lock();
        jInfo.setUpdateTime(System.currentTimeMillis());
        if (!jInfo.getDisableLogArchival()) {
            jInfo.setArchiveLocation(NetUtil.getArchiveURI(jobId));
        }
        pm.updateEntity(jInfo);
        rwl.writeLock().unlock();
    } catch (Exception e) {
        logger.error("Failed to update job status in database: ", e);
        response = new JobStatusResponse(
                new CloudServiceException(HttpURLConnection.HTTP_INTERNAL_ERROR, e.getMessage()));

        // unlock before returning response
        if (rwl.writeLock().isHeldByCurrentThread()) {
            rwl.writeLock().unlock();
        }
        return response;
    }

    // all good - return results
    response = new JobStatusResponse();
    response.setStatus(jInfo.getStatus());
    response.setMessage("Successfully killed job: " + jobId);
    return response;
}

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_REG_EXP_FOR_RESTEASY + "}")
public AstroboaResource getContentObjectProperty(
        @PathParam("contentObjectIdOrName") String contentObjectIdOrName,
        @PathParam("propertyPath") String propertyPath) {

    try {//from  w w w  .j  a v a2  s . com

        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, ".");
            }
        }

        //Check if a value index exists and extract it
        IndexExtractor indexExtractor = new IndexExtractor(propertyPath);

        String propertyPathWithoutIndex = indexExtractor.getPropertyPathWithoutIndex();

        int valueIndex = indexExtractor.getIndex();

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

        try {
            property = contentObject.getCmsProperty(propertyPathWithoutIndex);
        } catch (Exception e) {
            logger.warn("Could not load provided property using path '" + propertyPathWithoutIndex
                    + "' 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",
                    propertyPathWithoutIndex, 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",
                    propertyPathWithoutIndex, contentObjectIdOrName);
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);

        case Binary:
            return new BinaryChannelResource(astroboaClient, contentObject, (BinaryProperty) property,
                    valueIndex);

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

        default:
            return new SimplePropertyResource(astroboaClient, contentObject, (SimpleCmsProperty) property,
                    valueIndex);
        }

    } 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.core.jpa.services.JpaClusterServiceImplIntegrationTests.java

/**
 * Test the create method./*www  . java2 s .  co  m*/
 *
 * @throws GenieException For any problem
 */
@Test
public void testCreateCluster() throws GenieException {
    final Set<String> configs = Sets.newHashSet("a config", "another config", "yet another config");
    final Set<String> dependencies = Sets.newHashSet("a dependency");
    final String id = UUID.randomUUID().toString();
    final Cluster cluster = new Cluster.Builder(CLUSTER_1_NAME, CLUSTER_1_USER, CLUSTER_1_VERSION,
            ClusterStatus.OUT_OF_SERVICE).withId(id).withConfigs(configs).withDependencies(dependencies)
                    .build();
    this.service.createCluster(cluster);
    final Cluster created = this.service.getCluster(id);
    Assert.assertNotNull(created);
    Assert.assertEquals(id, created.getId().orElseThrow(IllegalArgumentException::new));
    Assert.assertEquals(CLUSTER_1_NAME, created.getName());
    Assert.assertEquals(CLUSTER_1_USER, created.getUser());
    Assert.assertEquals(ClusterStatus.OUT_OF_SERVICE, created.getStatus());
    Assert.assertEquals(3, created.getConfigs().size());
    Assert.assertEquals(1, created.getDependencies().size());
    this.service.deleteCluster(id);
    try {
        this.service.getCluster(id);
        Assert.fail("Should have thrown exception");
    } catch (final GenieException ge) {
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, ge.getErrorCode());
    }
}

From source file:com.netflix.genie.core.jpa.services.JpaCommandServiceImplIntegrationTests.java

/**
 * Test the create method./*from  w  ww .  j a va2  s . c  om*/
 *
 * @throws GenieException For any problem
 */
@Test
public void testCreateCommand() throws GenieException {
    final String id = UUID.randomUUID().toString();
    final Command command = new Command.Builder(COMMAND_1_NAME, COMMAND_1_USER, COMMAND_1_VERSION,
            CommandStatus.ACTIVE, COMMAND_1_EXECUTABLE, COMMAND_1_CHECK_DELAY).withId(id).build();
    final String createdId = this.service.createCommand(command);
    Assert.assertThat(createdId, Matchers.is(id));
    final Command created = this.service.getCommand(id);
    Assert.assertNotNull(this.service.getCommand(id));
    Assert.assertEquals(id, created.getId().orElseThrow(IllegalArgumentException::new));
    Assert.assertEquals(COMMAND_1_NAME, created.getName());
    Assert.assertEquals(COMMAND_1_USER, created.getUser());
    Assert.assertEquals(CommandStatus.ACTIVE, created.getStatus());
    Assert.assertEquals(COMMAND_1_EXECUTABLE, created.getExecutable());
    Assert.assertThat(COMMAND_1_CHECK_DELAY, Matchers.is(created.getCheckDelay()));
    Assert.assertFalse(created.getMemory().isPresent());
    this.service.deleteCommand(id);
    try {
        this.service.getCommand(id);
        Assert.fail("Should have thrown exception");
    } catch (final GenieException ge) {
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, ge.getErrorCode());
    }
}

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

/**
 * Delete the all configuration files from a given application.
 *
 * @param id The id of the application to delete the configuration files
 *           from. Not null/empty/blank.
 * @return Empty set if successful//w  w w.  j ava2 s .c  o  m
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}/configs")
@ApiOperation(value = "Remove all configuration files from an application", notes = "Remove all the configuration 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> removeAllConfigsForApplication(
        @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.removeAllConfigsForApplication(id);
}

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

/**
 * Add new commands to the given cluster.
 *
 * @param id       The id of the cluster to add the commands to. Not
 *                 null/empty/blank./*from  w w  w.  java 2 s. c o m*/
 * @param commands The commands to add. Not null.
 * @return The active commands for this cluster.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/commands")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new commands to a cluster", notes = "Add the supplied commands to the cluster with the supplied id."
        + " commands should already have been created.", 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> addCommandsForCluster(
        @ApiParam(value = "Id of the cluster to add commands to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The commands to add.", required = true) final List<Command> commands)
        throws GenieException {
    LOG.info("Called with id " + id + " and commands " + commands);
    return this.clusterConfigService.addCommandsForCluster(id, commands);
}