Example usage for javax.servlet.http HttpServletResponse SC_NOT_FOUND

List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_FOUND

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_NOT_FOUND.

Prototype

int SC_NOT_FOUND

To view the source code for javax.servlet.http HttpServletResponse SC_NOT_FOUND.

Click Source Link

Document

Status code (404) indicating that the requested resource is not available.

Usage

From source file:eu.dasish.annotation.backend.rest.AnnotationResource.java

/**
 * //from ww  w.  j  av  a  2  s  . c o m
 * @param externalIdentifier the string representing the UUID of an annotation.
 * @return the xml element representing the list of h-references of the targets of the annotation with "externalIdentifier".
 * @throws IOException if sending an error fails.
 */
@GET
@Produces(MediaType.TEXT_XML)
@Path("{annotationid: " + BackendConstants.regExpIdentifier + "}/targets")
@Transactional(readOnly = true)
public JAXBElement<ReferenceList> getAnnotationTargets(@PathParam("annotationid") String externalIdentifier)
        throws IOException {
    Map params = new HashMap();
    try {
        ReferenceList result = (ReferenceList) (new RequestWrappers(this)).wrapRequestResource(params,
                new GetTargetList(), Resource.ANNOTATION, Access.READ, externalIdentifier);
        if (result != null) {
            return (new ObjectFactory()).createTargetList(result);
        } else {
            return (new ObjectFactory()).createTargetList(new ReferenceList());
        }
    } catch (NotInDataBaseException e1) {
        httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage());
        return (new ObjectFactory()).createReferenceList(new ReferenceList());
    } catch (ForbiddenException e2) {
        httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage());
        return (new ObjectFactory()).createReferenceList(new ReferenceList());
    }
}

From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java

private void sendProjectFileContent() {
    try {/*ww  w  . j  a  va 2s .  c o  m*/
        ProjectFile file = MySqlConnector.getInstance().getFile(request.getParameter("publicId"));
        if (file != null) {
            writeResponse(objectMapper.writeValueAsString(file), HttpServletResponse.SC_OK);
        } else {
            writeResponse("", HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (IOException e) {
        writeResponse("Can't write response", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (NullPointerException e) {
        writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST);
    } catch (DatabaseOperationException e) {
        writeResponse(e.getMessage(), HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:controller.TemasNivel3RestController.java

/**
*
* @param id/* w w  w . ja  v  a 2s. c om*/
* @param request
* @param response
* @return JSON
* este metodo se encarga de generar la lista de municipios que pertecen 
* a una entidad con ID especifico 
*/

@RequestMapping(value = "/{id}/indicadores", method = RequestMethod.GET, produces = "application/json")
public String getIndicadoresJSON(@PathVariable("id") int id, HttpServletRequest request,
        HttpServletResponse response) {
    TemasNivel3DAO tabla = new TemasNivel3DAO();
    Gson JSON;
    List<Indicadores> lista;
    try {
        lista = tabla.selectAllIndicadores(id);
        if (lista.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            Error e = new Error();
            e.setTypeAndDescription("Warning", "No existen elementos");
            JSON = new Gson();
            return JSON.toJson(e);
        }
    } catch (HibernateException ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        Error e = new Error();
        e.setTypeAndDescription("errorServer", ex.getMessage());
        JSON = new Gson();
        return JSON.toJson(e);
    }

    Datos<Indicadores> datos = new Datos<>();
    datos.setDatos(lista);
    JSON = new Gson();
    response.setStatus(HttpServletResponse.SC_OK);
    return JSON.toJson(datos);
}

From source file:de.mare.mobile.ui.security.AuthFilter.java

public void doFilterInternal(final ServletRequest servletRequest, final ServletResponse servletResponse,
        final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;
    if (AppFeatures.PORTAL.isActive()) {
        final String requestURI = request.getRequestURI();
        User user = userSession.getUser();
        // area accessible without login
        boolean anonymousArea = false;
        if (this.excludeURIs != null) {
            for (final String excludeURI : this.excludeURIs) {
                String excludeURIWithContext = request.getContextPath() + excludeURI.trim();
                final boolean withStart = excludeURIWithContext.endsWith("*");
                final boolean isRequestURIexcluded;
                if (withStart) {
                    // remove the star
                    excludeURIWithContext = excludeURIWithContext.substring(0,
                            excludeURIWithContext.length() - 1);
                    isRequestURIexcluded = requestURI.startsWith(excludeURIWithContext);
                } else {
                    isRequestURIexcluded = requestURI.equals(excludeURIWithContext);
                }/*from w w  w .  j  a  va2 s  . co m*/
                if (isRequestURIexcluded) {
                    anonymousArea = true;
                    break;
                }
            }
        }
        if (anonymousArea || user != null) {
            // let the others work
            chain.doFilter(servletRequest, servletResponse);
        } else {
            if (this.redirectToLoginPage) {
                // save the requested URL
                final StringBuffer urlBuffer = request.getRequestURL();
                if (StringUtils.isNotEmpty(request.getQueryString())) {
                    urlBuffer.append("?").append(request.getQueryString());
                }
                final String url = urlBuffer.toString();
                if (!url.contains("login") && !url.contains("error.")) {
                    // does not redirect to a login page (like loginFailed)
                    request.getSession().setAttribute(AppConstants.REDIRECT_AFTER_SUCCESSFUL_LOGIN, url);
                }
                request.getRequestDispatcher(this.loginPage).forward(servletRequest, servletResponse);
            } else {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }
        }
    } else {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.asual.lesscss.ResourceServlet.java

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    try {/*  www. j a v  a 2  s  .com*/

        String pkg = request.getParameter("pack");
        String[] uri = (pkg != null) ? pkg.split(separator)
                : new String[] { request.getRequestURI().replaceAll("/+", "/") };
        String mimeType = getResourceMimeType(uri[0]);

        long lastModified = 0;
        byte[] content = new byte[0];

        for (String resource : uri) {
            resource = resource.replaceAll("^" + request.getContextPath(), "");
            try {
                content = mergeContent(content, getResourceContent(resource));
            } catch (FileNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            } catch (ResourceNotFoundException e) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            lastModified = Math.max(lastModified, getResourceLastModified(resource));
        }

        long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        if (ifModifiedSince != 0 && ifModifiedSince / milliseconds == lastModified / milliseconds) {
            logger.debug("Return with SC_NOT_MODIFIED, since " + ifModifiedSince + " == " + lastModified);
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        response.setContentType(mimeType + (mimeType.startsWith("text/") ? ";charset=" + charset : ""));
        if (cache) {
            response.setDateHeader("Expires", System.currentTimeMillis() + maxAge * milliseconds);
            response.setDateHeader("Last-Modified", lastModified);
            response.setHeader("Cache-control", "max-age=" + maxAge);
        } else {
            response.setDateHeader("Expires", System.currentTimeMillis());
            response.setDateHeader("Last-Modified", System.currentTimeMillis());
            response.setHeader("Cache-control", "max-age=0");
        }
        response.setContentLength(content.length);
        response.getOutputStream().write(content);
        response.getOutputStream().flush();
        response.getOutputStream().close();

    } catch (Exception e) {
        throw new ServletException(e.getMessage(), e);
    }
}

From source file:org.dasein.cloud.azure.AzureMethod.java

public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull String resource)
        throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + resource + ")");
    }/*from   w w w. j  a v  a2  s.  c  o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug(
                "--------------------------------------------------------> " + endpoint + account + resource);
        wire.debug("");
    }
    try {
        HttpClient client = getClient();
        HttpUriRequest get = new HttpGet(endpoint + account + resource);

        //get.addHeader("Content-Type", "application/xml");
        get.addHeader("x-ms-version", "2012-03-01");
        if (wire.isDebugEnabled()) {
            wire.debug(get.getRequestLine().toString());
            for (Header header : get.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;
        StatusLine status;

        try {
            response = client.execute(get);
            status = response.getStatusLine();
        } catch (IOException e) {
            logger.error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
            e.printStackTrace();
            throw new CloudException(e);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("get(): HTTP Status " + status);
        }
        Header[] headers = response.getAllHeaders();

        if (wire.isDebugEnabled()) {
            wire.debug(status.toString());
            for (Header h : headers) {
                if (h.getValue() != null) {
                    wire.debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    wire.debug(h.getName() + ":");
                }
            }
            wire.debug("");
        }
        if (status.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {
            return null;
        }
        if (status.getStatusCode() != HttpServletResponse.SC_OK
                && status.getStatusCode() != HttpServletResponse.SC_NON_AUTHORITATIVE_INFORMATION) {
            logger.error("get(): Expected OK for GET request, got " + status.getStatusCode());

            HttpEntity entity = response.getEntity();
            String body;

            if (entity == null) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), "An error was returned without explanation");
            }
            try {
                body = EntityUtils.toString(entity);
            } catch (IOException e) {
                throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(),
                        status.getReasonPhrase(), e.getMessage());
            }
            if (wire.isDebugEnabled()) {
                wire.debug(body);
            }
            wire.debug("");
            AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);

            if (items == null) {
                return null;
            }
            logger.error("get(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
            throw new AzureException(items);
        } else {
            HttpEntity entity = response.getEntity();

            if (entity == null) {
                return null;
            }
            InputStream input;

            try {
                input = entity.getContent();
            } catch (IOException e) {
                logger.error(
                        "get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            if (wire.isDebugEnabled()) {
                wire.debug("---> Binary Data <---");
            }
            wire.debug("");
            return input;
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + AzureMethod.class.getName() + ".getStream()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + account
                    + resource);
        }
    }
}

From source file:com.imaginary.home.cloud.api.RestApi.java

@Override
public void doDelete(@Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp)
        throws IOException, ServletException {
    String requestId = request(req);

    try {//from   w  ww  .j av  a 2s. c  o  m
        Map<String, Object> headers = parseHeaders(req);
        String[] path = getPath(req);

        if (path.length < 1) {
            throw new RestException(HttpServletResponse.SC_METHOD_NOT_ALLOWED, RestException.INVALID_OPERATION,
                    "No DELETE is allowed against /");
        } else if (apiCalls.containsKey(path[0])) {
            Map<String, Object> parameters = parseParameters(req);
            APICall call = apiCalls.get(path[0]);

            String userId = authenticate("DELETE", req, headers);

            call.delete(requestId, userId, path, req, resp, headers, parameters);
        } else {
            throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_RESOURCE,
                    "No " + path[0] + " resource exists in this API");
        }
    } catch (RestException e) {
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", e.getStatus());
        error.put("message", e.getMessage());
        error.put("description", e.getDescription());
        resp.setStatus(e.getStatus());
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    } catch (Throwable t) {
        t.printStackTrace();
        HashMap<String, Object> error = new HashMap<String, Object>();

        error.put("code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        error.put("message", RestException.INTERNAL_ERROR);
        error.put("description", t.getMessage());
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        resp.getWriter().println((new JSONObject(error)).toString());
        resp.getWriter().flush();
    }
}

From source file:org.dataconservancy.ui.api.FileController.java

/**
 * Accepts the parameters as specified below and returns the content of the file with matching id and qualifies the
 * criteria specified in the request header.
 * @param idpart id string that uniquely identify requested.
 * @param mimeType specifies the acceptable type of the response's content. The matching file's mime type is
 *        determined using the {@link javax.activation.MimetypesFileTypeMap}'s default map.
 * @param modifiedSince specifies that the request is only for file with matching id that has been modified
 *        since the {@code modifiedSince} date. Files with matching ids that has not been modified since
 *        {@code modifiedSince} date will be disqualified and not returned.
 * @param request http request/*from  w w w.j  ava 2  s  .  c om*/
 * @throws {@link IOException} when an exception occurs when writing to the {@link HttpServletResponse} object.
 *
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.GET })
public void handleFileGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException {

    // this impl does not require authz at the moment, but need a user for the fileBizService getFile method
    // ok if null
    Person user = getAuthenticatedUser();

    // Get file id from the request
    String id = requestUtil.buildRequestUrl(request);

    // Resolve the Request URL to the ID of the file (in this case URL == ID)
    if (id == null || id.trim().isEmpty()) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }

    try {

        archiveService.pollArchive();

        // Get file's last modified date via the fileBizService if it is a DataFile, or
        // via the metadataFileBizService if it is a MetadataFile

        DateTime lastModifiedDate = (fileBizService.getLastModifiedDate(id) != null)
                ? fileBizService.getLastModifiedDate(id)
                : metadataFileBizService.getLastModifiedDate(id);

        // Handle if-modified-since header
        if (failIfModifiedSinceHeader(request, resp, modifiedSince, lastModifiedDate)) {
            return;
        }

        // Get file via fileBizService if it is a DataFile, or
        // via the metadataFileBizService if it is a MetadataFile
        DataFile file = null;
        if (fileBizService.getFile(id, user) != null) {
            file = fileBizService.getFile(id, user);
        } else {
            file = metadataFileBizService.retrieveMetadataFile(id);
        }

        //If file is not found
        if (file == null) {
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, "No file matching this id " + id + " was found.");
        } else { //if file is found

            String fileMimeType = file.getFormat();

            if (fileMimeType == null) {
                fileMimeType = "application/octet-stream";
            }

            //Handling mimeType header
            if (failAcceptHeader(request, resp, mimeType, fileMimeType)) {
                return;
            }

            //Set the Content-Length
            resp.setContentLength((int) file.getSize());
            resp.setStatus(HttpStatus.SC_OK);
            //Calculate ETAG
            resp.setHeader(ETAG, ETagCalculator.calculate(Integer.toString(file.hashCode())));
            DateTimeFormatter fmt = new DateTimeFormatterBuilder().appendPattern("EEE, dd MMM yyyy HH:mm:ss Z")
                    .toFormatter();
            String rfcDate = fmt.print(lastModifiedDate);
            resp.setHeader(LAST_MODIFIED, rfcDate);
            //Set Content-Disposition
            resp.setHeader(CONTENT_DISPOSITION,
                    getResponseContentDispositionString("\"" + file.getName() + "\"", file.getSize()));
            //Set Content-Type
            resp.setContentType(fileMimeType);

            InputStream is = new URL(file.getSource()).openStream();
            IOUtils.copy(is, resp.getOutputStream());
            is.close();
        }
    } catch (BizPolicyException be) {
        handleException(be, request, resp);
    } catch (ArchiveServiceException ae) {
        handleException(ae, request, resp);
    } catch (RelationshipConstraintException re) {
        handleException(re, request, resp);
    }
}

From source file:info.raack.appliancedetection.evaluation.web.EvaluationController.java

@RequestMapping(value = "/evaluation/{id}", method = RequestMethod.GET)
public void getEvaluationData(@PathVariable("id") String simulationId,
        @RequestParam("algorithmId") int algorithmId,
        @RequestParam(value = "start", required = false) Double startMillis,
        @RequestParam(value = "end", required = false) Double endMillis,
        @RequestParam(value = "ticks", required = false) Integer ticks, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    // TODO - for now, just use the naive algorithm's energy measurements.

    Date start = null;/*  ww  w.j av a  2s . co  m*/
    Date end = null;

    if (startMillis != null && endMillis != null) {
        start = new Date(startMillis.longValue());
        end = new Date(endMillis.longValue());
    } else if (startMillis != null && endMillis == null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(startMillis.longValue());
        start = c.getTime();
    } else if (startMillis == null && endMillis != null) {
        // if only start or end are provided, create a one day span
        Calendar c = new GregorianCalendar();
        c.setTimeInMillis(endMillis.longValue());
        end = c.getTime();

    }

    if (ticks == null) {
        ticks = 300;
    }

    Evaluation evaluation = simulationService.getEvaluation(algorithmId, simulationId, start, end, true);

    if (evaluation == null) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    EvaluationWrapper wrapper = new EvaluationWrapper(evaluation);

    JsonSerializer<EnergyTimestep> dateSerializer = new JsonSerializer<EnergyTimestep>() {
        // serialize date to milliseconds since epoch
        public JsonElement serialize(EnergyTimestep energyTimestep, Type me, JsonSerializationContext arg2) {
            JsonArray object = new JsonArray();
            object.add(new JsonPrimitive(energyTimestep.getStartTime().getTime()));
            object.add(new JsonPrimitive(energyTimestep.getEnergyConsumed()));
            return object;
        }
    };

    String dataJS = new GsonBuilder().registerTypeAdapter(EnergyTimestep.class, dateSerializer)
            .excludeFieldsWithModifiers(Modifier.STATIC).setExclusionStrategies(new ExclusionStrategy() {

                // skip logger
                public boolean shouldSkipClass(Class<?> clazz) {
                    return clazz.equals(Logger.class);
                }

                public boolean shouldSkipField(FieldAttributes fieldAttributes) {
                    // skip simulation of simulated appliance
                    return (fieldAttributes.getName().equals("simulation")
                            && fieldAttributes.getDeclaringClass() == SimulatedAppliance.class) ||
                    // skip simulation second data
                    (fieldAttributes.getName().equals("secondData")
                            && fieldAttributes.getDeclaringClass() == Simulation.class) ||
                    // skip endTime of energytimestep
                    (fieldAttributes.getName().equals("endTime")
                            && fieldAttributes.getDeclaringClass() == EnergyTimestep.class) ||
                    // skip userAppliance, detectionAlgorithmId of appliance state transition
                    ((fieldAttributes.getName().equals("userAppliance")
                            || fieldAttributes.getName().equals("detectionAlgorithmId"))
                            && fieldAttributes.getDeclaringClass() == ApplianceStateTransition.class);
                }
            }).create().toJson(wrapper);

    response.getWriter().write(dataJS);
    response.setContentType("application/json");
}