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:de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService.java

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//  w w  w  .  j  a v  a  2s . c  o m
@ApiOperation(value = "This method returns a list of activities", notes = "Default the latest ten activities will be returned")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of activities"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") })
//TODO add filter
public HttpResponse getActivities(
        @ApiParam(value = "Before cursor pagination", required = false) @DefaultValue("-1") @QueryParam("before") int before,
        @ApiParam(value = "After cursor pagination", required = false) @DefaultValue("-1") @QueryParam("after") int after,
        @ApiParam(value = "Limit of elements of components", required = false) @DefaultValue("10") @QueryParam("limit") int limit,
        @ApiParam(value = "User authorization token", required = false) @DefaultValue("") @HeaderParam("authorization") String authorizationToken) {

    DALFacade dalFacade = null;
    try {
        if (before != -1 && after != -1) {
            ExceptionHandler.getInstance().throwException(ExceptionLocation.ACTIVITIESERVICE,
                    ErrorCode.WRONG_PARAMETER, "both: before and after parameter not possible");
        }
        int cursor = before != -1 ? before : after;
        Pageable.SortDirection sortDirection = after != -1 ? Pageable.SortDirection.ASC
                : Pageable.SortDirection.DESC;

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(20);
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

        dalFacade = getDBConnection();
        Gson gson = new Gson();
        ExecutorService executor = Executors.newCachedThreadPool();

        int getObjectCount = 0;
        PaginationResult<Activity> activities;
        List<ActivityEx> activitiesEx = new ArrayList<>();
        Pageable pageInfo = new PageInfo(cursor, limit, "", sortDirection);
        while (activitiesEx.size() < limit && getObjectCount < 5) {
            pageInfo = new PageInfo(cursor, limit, "", sortDirection);
            activities = dalFacade.findActivities(pageInfo);
            getObjectCount++;
            cursor = sortDirection == Pageable.SortDirection.ASC ? cursor + limit : cursor - limit;
            if (cursor < 0) {
                cursor = 0;
            }
            activitiesEx.addAll(
                    getObjectBodies(httpclient, executor, authorizationToken, activities.getElements()));
        }

        executor.shutdown();
        if (activitiesEx.size() > limit) {
            activitiesEx = activitiesEx.subList(0, limit);
        }
        PaginationResult<ActivityEx> activitiesExResult = new PaginationResult<>(pageInfo, activitiesEx);

        HttpResponse response = new HttpResponse(gson.toJson(activitiesExResult.getElements()),
                HttpURLConnection.HTTP_OK);
        Map<String, String> parameter = new HashMap<>();
        parameter.put("limit", String.valueOf(limit));
        response = this.addPaginationToHtppResponse(activitiesExResult, "", parameter, response);

        return response;

    } catch (ActivityTrackerException atException) {
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception ex) {
        ActivityTrackerException atException = ExceptionHandler.getInstance().convert(ex,
                ExceptionLocation.ACTIVITIESERVICE, ErrorCode.UNKNOWN, ex.getMessage());
        return new HttpResponse(ExceptionHandler.getInstance().toJSON(atException),
                HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        closeDBConnection(dalFacade);
    }
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

/** send a POST Request and return the response as string */
String sendPostRequest(String url, String bodytext) throws Exception {
    String sresponse;/* ww  w  . j  av  a 2 s.  c om*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    // set authentication header
    httppost.addHeader("Authorization", authHeader);

    // very important. otherwise there comes a invalid request error
    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    StringEntity body = new StringEntity(bodytext);
    body.setContentType("application/x-www-form-urlencoded");

    httppost.setEntity(body);

    HttpResponse response = httpclient.execute(httppost);

    // check status code.
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
        // Not found too. no exception should be thrown.
        HttpEntity entity = response.getEntity();

        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Connotea Error", RDFUtils.parseError(sresponse));
    }
    return sresponse;

}

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

/**
 * Throws a NOT_FOUND with the given message if the given parameter is null
 * @param <T> the type of parameter
 * @param o the parameter to check//from w  w  w  .j av a 2s.  com
 * @param msg the message format
 * @param params the message parameters
 * @return the parameter
 */
protected <T> T checkNotFound(T o, String msg, Object... params) {
    if (o == null)
        throw new WebApplicationException(
                Response.status(HttpURLConnection.HTTP_NOT_FOUND).entity(String.format(msg, params)).build());
    return o;
}

From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java

@Test
public void testCopyFileInvalidSource() throws Exception {
    String directoryPath = "testCopyFile/directory/path" + System.currentTimeMillis();
    createDirectory(directoryPath);/* ww w .java  2  s  .  c  o  m*/

    JSONObject requestObject = new JSONObject();
    requestObject.put("Location", toAbsoluteURI("file/this/does/not/exist/at/all"));
    WebRequest request = getPostFilesRequest(directoryPath, requestObject.toString(), "destination.txt");
    request.setHeaderField("X-Create-Options", "copy");
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    JSONObject responseObject = new JSONObject(response.getText());
    assertEquals("Error", responseObject.get("Severity"));
}

From source file:cn.ctyun.amazonaws.internal.EC2MetadataClient.java

/**
 * Reads a response from the Amazon EC2 Instance Metadata Service and
 * returns the content as a string.//from   w  w  w .  ja  va 2  s. c  o  m
 *
 * @param connection
 *            The connection to the Amazon EC2 Instance Metadata Service.
 *
 * @return The content contained in the response from the Amazon EC2
 *         Instance Metadata Service.
 *
 * @throws IOException
 *             If any problems ocurred while reading the response.
 */
private String readResponse(HttpURLConnection connection) throws IOException {
    if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND)
        throw new AmazonClientException("The requested metadata is not found at " + connection.getURL());

    InputStream inputStream = connection.getInputStream();

    try {
        StringBuilder buffer = new StringBuilder();
        while (true) {
            int c = inputStream.read();
            if (c == -1)
                break;
            buffer.append((char) c);
        }

        return buffer.toString();
    } finally {
        inputStream.close();
    }
}

From source file:org.sonarsource.sonarlint.core.container.connected.validate.ServerVersionAndStatusChecker.java

private ServerInfos fetchServerInfos() {
    try (WsResponse response = wsClient.rawGet("api/system/status")) {
        if (!response.isSuccessful()) {
            if (response.code() == HttpURLConnection.HTTP_NOT_FOUND) {
                return tryFromDeprecatedApi(response);
            } else {
                throw SonarLintWsClient.handleError(response);
            }/*  w  w  w . j a v  a 2  s  .  co m*/
        } else {
            String responseStr = response.content();
            try {
                ServerInfos.Builder builder = ServerInfos.newBuilder();
                JsonFormat.parser().merge(responseStr, builder);
                return builder.build();
            } catch (InvalidProtocolBufferException e) {
                throw new IllegalStateException(
                        "Unable to parse server infos from: " + StringUtils.abbreviate(responseStr, 100), e);
            }
        }
    }
}

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

@GET
@Produces("*/*")/*from ww  w.j  av a  2  s . c om*/
@Path("/{propertyPath: " + CmsConstants.PROPERTY_PATH_REG_EXP_FOR_RESTEASY + "}")
public Response getDefinition(@PathParam("propertyPath") String propertyPath,
        @QueryParam("output") String output, @QueryParam("callback") String callback,
        @QueryParam("prettyPrint") String prettyPrint) {

    boolean prettyPrintEnabled = ContentApiUtils.isPrettyPrintEnabled(prettyPrint);

    if (output == null) {

        if (propertyPath != null && propertyPath.endsWith(".xsd")) {
            //user has provided a file name and not a property path
            return getDefinitionInternal(propertyPath, Output.XSD, callback, prettyPrintEnabled);
        }

        return getDefinitionInternal(propertyPath, Output.XML, callback, prettyPrintEnabled);
    }

    Output outputEnum = Output.valueOf(output.toUpperCase());

    if (outputEnum != Output.XSD && asrtoboaBuiltInModelIsRequested(propertyPath)) {
        //User has requested astroboa-model or astroboa-api built in schemata
        //but at the same time, the "output" request parameter was not XSD
        //In this case an HTTP NOT FOUND error should be returned.
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }

    return getDefinitionInternal(propertyPath, outputEnum, callback, prettyPrintEnabled);

}

From source file:uk.co.firstzero.webdav.Common.java

/**
 * Used for checking if a file exists/*from w w  w .  j av a  2s  .c  o  m*/
 * @param client    The client to execute the method
 * @param method    The method to be executed
 * @param ignoreHTTPNOTFOUND  Used to flag if the HTTP_NOT_FOUND error has to be ignored, if not the IOException raised will be thrown
 * @return  Returns if the execution has been successful
 * @throws IOException
 */
public static boolean executeMethod(HttpClient client, HttpMethod method, boolean ignoreHTTPNOTFOUND)
        throws IOException {
    try {
        client.executeMethod(method);
    } catch (IOException e) {
        //If it is not 404 - throw exception, otherwise
        if (method.getStatusCode() != HttpURLConnection.HTTP_NOT_FOUND)
            throw e;
    }
    int statusCode = method.getStatusCode();
    logger.trace("executeMethod - statusCode - " + statusCode);

    boolean result = (method.getStatusCode() == HttpURLConnection.HTTP_OK);
    logger.debug("executeMethod - result - " + result);
    logger.debug(method.getStatusCode() + " " + method.getStatusText() + " " + method.getResponseBodyAsString()
            + " " + Arrays.toString(method.getResponseHeaders()));

    return result;
}

From source file:com.datos.vfs.provider.http.HttpFileObject.java

/**
 * Creates an input stream to read the file content from.  Is only called
 * if {@link #doGetType} returns {@link FileType#FILE}.
 * <p>//from  w w w.  j a v a 2 s.c  o  m
 * It is guaranteed that there are no open output streams for this file
 * when this method is called.
 * <p>
 * The returned stream does not have to be buffered.
 */
@Override
protected InputStream doGetInputStream() throws Exception {
    final GetMethod getMethod = new GetMethod();
    setupMethod(getMethod);
    final int status = getAbstractFileSystem().getClient().executeMethod(getMethod);
    if (status == HttpURLConnection.HTTP_NOT_FOUND) {
        throw new FileNotFoundException(getName());
    }
    if (status != HttpURLConnection.HTTP_OK) {
        throw new FileSystemException("vfs.provider.http/get.error", getName(), Integer.valueOf(status));
    }

    return new HttpInputStream(getMethod);
}

From source file:nz.skytv.example.SwaggerApplication.java

@ApiOperation(value = "Update a book", notes = "Update a book.", response = Book.class, tags = { "book",
        "updates" })
@ApiResponses({ @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Book updated successfully"),
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "Transient Entity") })
@RequestMapping(value = { "/rest/book" }, method = RequestMethod.PATCH)
void updateBook(@ApiParam(value = "Book entity", required = true) @RequestBody @Valid final Book book) {
    LOG.debug("update {}", book);
}