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.CommandConfigResource.java

/**
 * Set the application for the given command.
 *
 * @param id          The id of the command to add the applications to. Not
 *                    null/empty/blank./*from  w  ww  .ja  va  2  s.  c  o m*/
 * @param application The application to set. Not null.
 * @return The active applications for this command.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/application")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Set the application for a command", notes = "Set the supplied application to the command "
        + "with the supplied id. Applications should already "
        + "have been created.", response = Application.class)
@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 Application setApplicationForCommand(
        @ApiParam(value = "Id of the command to set application for.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The application to add.", required = true) final Application application)
        throws GenieException {
    LOG.info("Called with id " + id + " and application " + application);
    return this.commandConfigService.setApplicationForCommand(id, application);
}

From source file:net.myrrix.client.ClientRecommender.java

public float estimateForAnonymous(long toItemID, long[] itemIDs, float[] values, Long contextUserID)
        throws TasteException {
    Preconditions.checkArgument(values == null || values.length == itemIDs.length,
            "Number of values doesn't match number of items");
    StringBuilder urlPath = new StringBuilder(32);
    urlPath.append("/estimateForAnonymous/");
    urlPath.append(toItemID);//from   ww  w .j a  v a  2 s.c o  m
    for (int i = 0; i < itemIDs.length; i++) {
        urlPath.append('/').append(itemIDs[i]);
        if (values != null) {
            urlPath.append('=').append(values[i]);
        }
    }

    // Requests are typically partitioned by user, but this request does not directly depend on a user.
    // If a user ID is supplied anyway, use it for partitioning since it will follow routing for other
    // requests related to that user. Otherwise just partition on the "to" item ID, which is at least
    // deterministic.
    long idToPartitionOn = contextUserID == null ? toItemID : contextUserID;

    TasteException savedException = null;
    for (HostAndPort replica : choosePartitionAndReplicas(idToPartitionOn)) {
        HttpURLConnection connection = null;
        try {
            connection = buildConnectionToReplica(replica, urlPath.toString(), "GET");
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                BufferedReader reader = IOUtils.bufferStream(connection.getInputStream());
                try {
                    return LangUtils.parseFloat(reader.readLine());
                } finally {
                    reader.close();
                }
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new NoSuchItemException(Arrays.toString(itemIDs) + ' ' + toItemID);
            case HttpURLConnection.HTTP_UNAVAILABLE:
                throw new NotReadyException();
            default:
                throw new TasteException(connection.getResponseCode() + " " + connection.getResponseMessage());
            }
        } catch (TasteException te) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, te.toString());
            savedException = te;
        } catch (IOException ioe) {
            log.info("Can't access {} at {}: ({})", urlPath, replica, ioe.toString());
            savedException = new TasteException(ioe);
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
    throw savedException;
}

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

@Test
public void testNotExistStreamCreateWriter() throws IOException {
    try {/* www  . java 2  s .  c  o  m*/
        StreamWriter streamWriter = streamClient.createWriter(TestUtils.NOT_FOUND_STREAM_NAME);
        assertNotNull(streamWriter);
        assertEquals(RestStreamWriter.class, streamWriter.getClass());
        RestStreamWriter restStreamWriter = (RestStreamWriter) streamWriter;
        assertEquals(TestUtils.SUCCESS_STREAM_NAME, restStreamWriter.getStreamName());
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_NOT_FOUND, e.getStatusCode());
    }
}

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

@Test
public void testDiffUntrackedUri() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());

    String projectName = getMethodName();
    JSONObject project = createProjectOrLink(workspaceLocation, projectName, gitDir.toString());

    String fileName = "new.txt";
    WebRequest request = getPostFilesRequest("", getNewFileJSON(fileName).toString(), fileName);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

    JSONObject newTxt = getChild(project, "new.txt");

    String gitDiffUri = newTxt.getJSONObject(GitConstants.KEY_GIT).getString(GitConstants.KEY_DIFF);

    request = getGetRequest(gitDiffUri + "?parts=uris");
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // modified assertDiffUris(...);
    JSONObject jsonPart = new JSONObject(response.getText());
    assertEquals(Diff.TYPE, jsonPart.getString(ProtocolConstants.KEY_TYPE));

    String fileOldUri = jsonPart.getString(GitConstants.KEY_COMMIT_OLD);
    request = getGetRequest(fileOldUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

    String fileNewUri = jsonPart.getString(GitConstants.KEY_COMMIT_NEW);
    request = getGetRequest(fileNewUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("", response.getText());

    String fileBaseUri = jsonPart.getString(GitConstants.KEY_COMMIT_BASE);
    request = getGetRequest(fileBaseUri);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

    assertEquals(gitDiffUri, jsonPart.getString(ProtocolConstants.KEY_LOCATION));
}

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

/**
 * Add new tags to a given application.//from w  w w  .j  av  a2 s  .co m
 *
 * @param id   The id of the application to add the tags to. Not
 *             null/empty/blank.
 * @param tags The tags to add. Not null/empty/blank.
 * @return The active tags for this application.
 * @throws GenieException For any error
 */
@POST
@Path("/{id}/tags")
@Consumes(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Add new tags to a application", notes = "Add the supplied tags to the application with the supplied 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> addTagsForApplication(
        @ApiParam(value = "Id of the application to add configuration to.", required = true) @PathParam("id") final String id,
        @ApiParam(value = "The tags to add.", required = true) final Set<String> tags) throws GenieException {
    LOG.info("Called with id " + id + " and config " + tags);
    return this.applicationConfigService.addTagsForApplication(id, tags);
}

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

@Test
public void testUpdateNonExistingConfigEntryUsingPUT() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        // clone a  repo
        String contentLocation = clone(clonePath).getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // get project metadata
        WebRequest request = getGetRequest(contentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());
        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitConfigUri = gitSection.getString(GitConstants.KEY_CONFIG);

        final String ENTRY_KEY = "a.b.c";
        final String ENTRY_VALUE = "v";

        String invalidEntryLocation = gitConfigUri.replace(ConfigOption.RESOURCE,
                ConfigOption.RESOURCE + "/" + ENTRY_KEY);

        // check if it doesn't exist
        request = getGetGitConfigRequest(invalidEntryLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());

        // try to update non-existing config entry using PUT (not allowed)
        request = getPutGitConfigRequest(invalidEntryLocation, ENTRY_VALUE);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    }//  w  ww.j a va 2s.  c o m
}

From source file:org.sipfoundry.sipxprovision.auto.Servlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String path = request.getPathInfo();
    String useragent = request.getHeader("User-Agent");
    LOG.info("GET " + path + "  User-Agent: " + useragent);

    // Examine the User-Agent.
    if (null == useragent || useragent.isEmpty()) {

        // Can't do anything without this.
        writeUiForwardResponse(request, response);
        return;//  w ww .  ja  v a2 s  .  co m
    }

    // For debugging.
    if (isDebugTestUserAgent(useragent)) {
        if (Servlet.isPolycomConfigurationFilePath(path)) {
            useragent = "FileTransport PolycomSoundStationIP-SSIP_6000-UA/3.2.0.0157";
        } else if (isNortelIp12x0ConfigurationFilePath(path)) {
            useragent = "Nortel IP Phone 1210 (SIP12x0.45.02.05.00)";
        }
    }

    // Is this a path that triggers provisioning of a phone with sipXconfig?
    DetectedPhone phone = null;
    if (POLYCOM_SIP_PATH_RE.matcher(path).matches() || POLYCOM_40_PATH_RE.matcher(path).matches()) {

        // Polycom SoundPoint IP / SoundStation IP / VVX
        phone = new DetectedPhone();

        // MAC, Model, & Version
        phone.mac = extractMac(path, POLYCOM_PATH_PREFIX);
        if (null == phone.mac || !extractPolycomModelAndVersion(phone, useragent)) {
            writeUiForwardResponse(request, response);
            return;
        }
    } else if (isNortelIp12x0ConfigurationFilePath(path)) {

        // Nortel IP 1210/1220/1230
        phone = new DetectedPhone();

        // MAC, Model, & Version
        phone.mac = extractMac(path, NORTEL_IP_12X0_PATH_PREFIX);
        if (null == phone.mac || !extractNortelIp12X0ModelAndVersion(phone, useragent)) {
            writeUiForwardResponse(request, response);
            return;
        }
    } else if (path.startsWith("/debug") && m_config.isDebugOn()) {
        // Debugging.
        writeDebuggingResponse(request, response);
        return;
    } else if (path.contains("firmwareUpdate")) {
        phone = new DetectedPhone();
        extractPolycomModelAndVersion(phone, useragent);
        phone.mac = extractMac(path, POLYCOM_PATH_PREFIX);
        if (null != phone.mac && extractPolycomModelAndVersion(phone, useragent)) {
            doUpdatePhone(phone.mac, phone.version, phone.model.sipxconfig_id, response);
        }
        return;
    }
    /*
     * TODO: Test case to catch this problem.... else { writeUiForwardResponse(request,
     * response); return; }
     */
    // Provision the phone with sipXconfig. (If it wasn't a provision trigger path, then phone
    // will
    // be null, which fails cleanly.)
    doProvisionPhone(phone);

    // Return the appropriate actual profile content.
    response.setContentType("application/text");
    if (isPolycomConfigurationFilePath(path)) {

        if (POLYCOM_000000000000_CONTACTS_PATH_RE.matcher(path).matches()) {

            // This file won't be found, so save the REST request overhead.
            response.sendError(HttpURLConnection.HTTP_NOT_FOUND);
        } else if (POLYCOM_OVERRIDES_PATH_RE.matcher(path).matches()) {

            // sipXconfig doesn't currently generate this Polycom config file. (See XX-5450)
            PrintWriter out = response.getWriter();
            out.println("<?xml version=\"1.0\" standalone=\"yes\"?>");
            out.println("<PHONE_CONFIG><OVERRIDES/></PHONE_CONFIG>");
        } else {
            writeProfileConfigurationResponse(path, extractMac(path, POLYCOM_PATH_PREFIX), response);
        }
    } else if (isNortelIp12x0ConfigurationFilePath(path)) {

        int index = path.indexOf(NORTEL_IP_12X0_PATH_PREFIX);
        if (-1 != index) {
            path = path.substring(index, path.length());
        }

        writeProfileConfigurationResponse(path, extractMac(path, NORTEL_IP_12X0_PATH_PREFIX), response);
    } else {

        // Unknown configuration file path. (Wouldn't know how to extract a MAC from the
        // path.)
        writeUiForwardResponse(request, response);
        return;
    }
}

From source file:com.vmware.vchs.base.DbaasApi.java

public void deleteSnapshotWithRetry(String snapshotId) throws Exception {
    try {//  www . j a va 2s .  com
        deleteSnapshot(snapshotId);
    } catch (Exception e) {
        throw e;
    }
    try {
        this.retryTask.execute(new GetDeletedSnapshotEntityTask(snapshotId));
        failBecauseExceptionWasNotThrown(RestException.class);
    } catch (RestException e) {
        assertThat(e.getStatusCode()).isEqualTo(HttpURLConnection.HTTP_NOT_FOUND);
    } catch (Exception e) {
        throw e;
    }
}

From source file:org.openecomp.sdnc.sli.aai.AAIService.java

@Override
public SearchResults requestServiceInstanceURL(String svc_instance_id) throws AAIServiceException {
    SearchResults response = null;/*from   w w  w.j  av  a2s .c om*/
    InputStream inputStream = null;

    try {
        String path = svc_inst_qry_path;
        path = path.replace("{svc-instance-id}", encodeQuery(svc_instance_id));

        String request_url = target_uri + path;
        URL http_req_url = new URL(request_url);

        HttpURLConnection con = getConfiguredConnection(http_req_url, HttpMethod.GET);

        LOGwriteFirstTrace(HttpMethod.GET, http_req_url.toString());
        LOGwriteDateTrace("svc_instance_id", svc_instance_id);

        // Check for errors
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inputStream = con.getInputStream();
        } else {
            inputStream = con.getErrorStream();
        }

        // Process the response
        LOG.debug("HttpURLConnection result:" + responseCode);
        if (inputStream == null)
            inputStream = new ByteArrayInputStream("".getBytes(StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        ObjectMapper mapper = getObjectMapper();

        if (responseCode == HttpURLConnection.HTTP_OK) {
            //            StringBuilder stringBuilder = new StringBuilder("\n");
            //            String line = null;
            //            while( ( line = reader.readLine() ) != null ) {
            //               stringBuilder.append("\n").append( line );
            //            }
            //            LOG.info(stringBuilder.toString());
            response = mapper.readValue(reader, SearchResults.class);
            LOGwriteEndingTrace(HttpURLConnection.HTTP_OK, "SUCCESS", mapper.writeValueAsString(response));
        } else if (responseCode == HttpURLConnection.HTTP_NOT_FOUND) {
            LOGwriteEndingTrace(responseCode, "HTTP_NOT_FOUND", "Entry does not exist.");
            return response;
        } else {
            ErrorResponse errorresponse = mapper.readValue(reader, ErrorResponse.class);
            LOGwriteEndingTrace(responseCode, "FAILURE", mapper.writeValueAsString(errorresponse));
            throw new AAIServiceException(responseCode, errorresponse);
        }

    } catch (AAIServiceException aaiexc) {
        throw aaiexc;
    } catch (Exception exc) {
        LOG.warn("requestServiceInstanceURL", exc);
        throw new AAIServiceException(exc);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception exc) {

            }
        }
    }
    return response;
}

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

private Response generateTopicResponseUsingTopicInstance(String topicIdOrName, Output output, String callback,
        boolean prettyPrint) {
    try {/*from ww  w.j a  v  a2  s. c o m*/

        Topic topic = findTopicByTopicIdOrName(topicIdOrName);

        if (topic == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        topic.getChildren();

        StringBuilder topicAsXMLOrJSONBuilder = new StringBuilder();

        switch (output) {
        case XML: {
            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topic.xml(prettyPrint));
            } else {
                ContentApiUtils.generateXMLP(topicAsXMLOrJSONBuilder, topic.xml(prettyPrint), callback);
            }
            break;
        }
        case JSON:
            if (StringUtils.isBlank(callback)) {
                topicAsXMLOrJSONBuilder.append(topic.json(prettyPrint));
            } else {
                ContentApiUtils.generateJSONP(topicAsXMLOrJSONBuilder, topic.json(prettyPrint), callback);
            }
            break;
        }

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

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