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:msearch.filmeSuchen.sender.MediathekSrf.java

public static boolean ping(String url) throws SRFException {

    url = url.replaceFirst("https", "http"); // Otherwise an exception may be thrown on invalid SSL certificates.

    try {/*from w  ww. jav  a  2 s .co m*/
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(1000); //1000ms timeout for connect, read timeout to infinity
        connection.setReadTimeout(0);
        int responseCode = connection.getResponseCode();
        connection.disconnect();
        if (responseCode > 399 && responseCode != HttpURLConnection.HTTP_NOT_FOUND) {

            if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                throw new SRFException("TEST");
            }
            //MSLog.debugMeldung("SRF: " + responseCode + " + responseCode " + "Url " + url);
            return false;
        }
        return (200 <= responseCode && responseCode <= 399);

    } catch (IOException exception) {
        return false;
    }
}

From source file:org.betaconceptframework.astroboa.console.security.ResourceApiProxy.java

@GET
@PUT//from   w  ww. j  a  v  a2s.  c om
@POST
@DELETE
@Path("{resourceApiPath:.*}")
@Produces("*/*")
public Response dispatchToAstroboaRepository(@PathParam("resourceApiPath") String resourceApiPath,
        @Context UriInfo uriInfo, @Context HttpServletRequest httpServletRequest) {

    try {

        String repositoryId = AstroboaClientContextHolder.getActiveRepositoryId();
        if (StringUtils.isBlank(repositoryId)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        CmsRepository activeCmsRepository = AstroboaClientContextHolder.getActiveCmsRepository();
        if (activeCmsRepository == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();
        if (securityContext == null) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String username = securityContext.getIdentity();

        if (StringUtils.isBlank(username)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String resourceApiBasePath = activeCmsRepository.getRestfulApiBasePath();

        if (StringUtils.isBlank(resourceApiBasePath)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        HttpSession httpSession = httpServletRequest.getSession();
        String password = (String) httpSession.getAttribute("repositoryPassword");

        if (StringUtils.isBlank(password)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
        }

        String httpMethod = httpServletRequest.getMethod();

        String requestPath = uriInfo.getPath();
        MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();

        ClientRequest request = new ClientRequest(
                "http://localhost:8080" + resourceApiBasePath + "/" + repositoryId + requestPath);

        // read the payload if the http method is put or post
        if (httpMethod.equals("POST") || httpMethod.equals("PUT")) {
            request.body(httpServletRequest.getContentType(), getBody(httpServletRequest));
        }

        // add authorization header (BASIC AUTH)
        String basicAuthString = username + ":" + password;
        String authorization = "BASIC " + Base64.encodeBytes(basicAuthString.getBytes());
        request.header(HttpHeaders.AUTHORIZATION, authorization);

        // add headers
        Enumeration headerNames = httpServletRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            request.header(headerName, httpServletRequest.getHeader(headerName));
        }

        // add query parameters
        for (Map.Entry queryParamEntry : queryParameters.entrySet()) {
            String parameterValue = ((List<String>) queryParamEntry.getValue()).get(0);

            //ClientRequest (request) encodes the values before the execution of the request.
            //Therefore we need to decode the values before we feed them to the ClientRequest instance
            request.queryParameter((String) queryParamEntry.getKey(),
                    URLDecoder.decode(parameterValue, "UTF-8"));
        }

        String uri = request.getUri();

        ClientResponse clientResponse = request.httpMethod(httpMethod, new GenericType<InputStream>() {
        });

        return clientResponse;

    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        logger.error("A problem occured while sending request to Astroboa Repository", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:org.sonar.server.platform.ws.LogsAction.java

@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
    userSession.checkIsSystemAdministrator();

    String processKey = wsRequest.mandatoryParam(PROCESS_PROPERTY);
    ProcessId processId = ProcessId.fromKey(processKey);

    File logsDir = serverLogging.getLogsDir();
    File file = new File(logsDir, processId.getLogFilenamePrefix() + ".log");
    // filenames are defined in the enum LogProcess. Still to prevent any vulnerability,
    // path is double-checked to prevent returning any file present on the file system.
    if (file.exists() && file.getParentFile().equals(logsDir)) {
        wsResponse.stream().setMediaType(MediaTypes.TXT);
        FileUtils.copyFile(file, wsResponse.stream().output());
    } else {/*from   w ww .j ava  2  s. c o m*/
        wsResponse.stream().setStatus(HttpURLConnection.HTTP_NOT_FOUND);
    }
}

From source file:org.jboss.test.cluster.defaultcfg.profileservice.test.FarmedClusterStartupTestCase.java

public void testFarmDWar() throws Exception {
    String index = "/farmD/index.html";

    HttpClient client = new HttpClient();

    GetMethod get = new GetMethod(getHttpURLs()[0] + index);
    assertEquals("farmD is unavailable on node0", HttpURLConnection.HTTP_NOT_FOUND, client.executeMethod(get));
    get = new GetMethod(getHttpURLs()[1] + index);
    assertEquals("farmD is unavailable on node0", HttpURLConnection.HTTP_NOT_FOUND, client.executeMethod(get));
}

From source file:com.facebook.buck.rules.HttpArtifactCache.java

public CacheResult fetchImpl(RuleKey ruleKey, File file) throws IOException {
    Request request = createRequestBuilder(ruleKey.toString()).get().build();
    Response response = fetchCall(request);

    if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
        LOGGER.info("fetch(%s): cache miss", ruleKey);
        return CacheResult.MISS;
    }/*  w w  w  .j av  a 2s  .  c  om*/

    if (response.code() != HttpURLConnection.HTTP_OK) {
        LOGGER.warn("fetch(%s): unexpected response: %d", ruleKey, response.code());
        return CacheResult.MISS;
    }

    // The hash code shipped with the artifact to/from the cache.
    HashCode expectedHashCode, actualHashCode;

    // Setup a temporary file, which sits next to the destination, to write to and
    // make sure all parent dirs exist.
    Path path = file.toPath();
    projectFilesystem.createParentDirs(path);
    Path temp = projectFilesystem.createTempFile(path.getParent(), path.getFileName().toString(), ".tmp");

    // Open the stream to server just long enough to read the hash code and artifact.
    try (DataInputStream input = new DataInputStream(response.body().byteStream())) {

        // First, extract the size of the file data portion, which we put in the beginning of
        // the artifact.
        long length = input.readLong();

        // Now, write the remaining response data to the temp file, while grabbing the hash.
        try (BoundedInputStream boundedInput = new BoundedInputStream(input, length);
                HashingInputStream hashingInput = new HashingInputStream(hashFunction, boundedInput);
                OutputStream output = projectFilesystem.newFileOutputStream(temp)) {
            ByteStreams.copy(hashingInput, output);
            actualHashCode = hashingInput.hash();
        }

        // Lastly, extract the hash code from the end of the request data.
        byte[] hashCodeBytes = new byte[hashFunction.bits() / Byte.SIZE];
        ByteStreams.readFully(input, hashCodeBytes);
        expectedHashCode = HashCode.fromBytes(hashCodeBytes);

        // We should be at the end of output -- verify this.  Also, we could just try to read a
        // single byte here, instead of all remaining input, but some network stack implementations
        // require that we exhaust the input stream before the connection can be reusable.
        try (OutputStream output = ByteStreams.nullOutputStream()) {
            if (ByteStreams.copy(input, output) != 0) {
                LOGGER.warn("fetch(%s): unexpected end of input", ruleKey);
                return CacheResult.MISS;
            }
        }
    }

    // Now form the checksum on the file we got and compare it to the checksum form the
    // the HTTP header.  If it's incorrect, log this and return a miss.
    if (!expectedHashCode.equals(actualHashCode)) {
        LOGGER.warn("fetch(%s): artifact had invalid checksum", ruleKey);
        projectFilesystem.deleteFileAtPath(temp);
        return CacheResult.MISS;
    }

    // Finally, move the temp file into it's final place.
    projectFilesystem.move(temp, path, StandardCopyOption.REPLACE_EXISTING);

    LOGGER.info("fetch(%s): cache hit", ruleKey);
    return CacheResult.HTTP_HIT;
}

From source file:net.joala.expression.library.net.UriStatusCodeExpressionTest.java

@Test
public void get_should_work_for_HTTP_NOT_FOUND() throws Exception {
    final int expectedStatusCode = HttpURLConnection.HTTP_NOT_FOUND;
    webservice.getHttpHandler().feedResponses(statusCode(expectedStatusCode));
    final int actualStatusCode = new UriStatusCodeExpression(webservice.getClientUri()).get();
    assertEquals("Retrieved status code should match expected one.", expectedStatusCode, actualStatusCode);
    assertEquals("All fed responses should have been read.", 0,
            webservice.getHttpHandler().availableResponses());
}

From source file:i5.las2peer.services.videoListService.VideoListService.java

/**
 * /*from  ww  w. jav a2s .c  o  m*/
 * getVideoList
 * 
 * 
 * @return HttpResponse
 * 
 */
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internalError"),
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "videoListAsJSONArray"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "noVideosExist") })
@ApiOperation(value = "getVideoList", notes = "")
public HttpResponse getVideoList() {
    String result = "";
    String columnName = "";
    String selectquery = "";
    int columnCount = 0;
    Connection conn = null;
    PreparedStatement stmnt = null;
    ResultSet rs = null;
    ResultSetMetaData rsmd = null;
    JSONObject ro = null;
    JSONArray array = new JSONArray();
    try {
        // get connection from connection pool
        conn = dbm.getConnection();
        selectquery = "SELECT * FROM videodetails;";
        // prepare statement
        stmnt = conn.prepareStatement(selectquery);

        // retrieve result set
        rs = stmnt.executeQuery();
        rsmd = (ResultSetMetaData) rs.getMetaData();
        columnCount = rsmd.getColumnCount();

        // process result set
        while (rs.next()) {
            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);

            }
            array.add(ro);
        }
        if (array.isEmpty()) {
            String er = "No results";
            HttpResponse noVideosExist = new HttpResponse(er, HttpURLConnection.HTTP_NOT_FOUND);
            return noVideosExist;
        } else {
            // return HTTP Response on success
            HttpResponse videoListAsJSONArray = new HttpResponse(array.toJSONString(),
                    HttpURLConnection.HTTP_OK);
            return videoListAsJSONArray;
        }
    } 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:io.apiman.cli.util.DeclarativeUtil.java

/**
 * Check for the presence of an item using the given Supplier.
 *
 * @param supplier the Supplier of the item
 * @param <T>/*from   w  w w .  j  ava  2s. c  o  m*/
 * @return the item or {@link Optional#empty()}
 */
public static <T> Optional<T> checkExists(Supplier<T> supplier) {
    try {
        // attempt to return the item
        return ofNullable(supplier.get());

    } catch (RetrofitError re) {
        // 404 indicates the item does not exist - anything else is an error
        if (ofNullable(re.getResponse())
                .filter(response -> HttpURLConnection.HTTP_NOT_FOUND == response.getStatus()).isPresent()) {

            return empty();
        }

        throw new DeclarativeException("Error checking for existence of existing item", re);
    }
}

From source file:org.jboss.test.web.test.VirtualHostTestCase.java

/**
 * Test the non existing web app./*  w ww .  j  av  a2s  .co m*/
 * 
 * @throws Exception
 */
public void testNormalHost() throws Exception {
    URL url = new URL(baseURL + webURL);
    Header[] hdrs = new Header[0];
    HttpUtils.accessURL(url, null, HttpURLConnection.HTTP_NOT_FOUND, hdrs, HttpUtils.GET);
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Throws a NOT_FOUND if the given parameter is null
 * @param <T> the type of parameter
 * @param o the parameter to check/*from   w  ww. j a va  2  s  . c  o  m*/
 * @return the parameter
 */
protected <T> T checkNotFound(T o) {
    if (o == null)
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    return o;
}