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:com.novartis.pcs.ontology.rest.servlet.SubtermsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);/*w w w. j a  v  a2  s .co  m*/
    } else if (pathInfo == null || pathInfo.length() == 1) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        response.setContentLength(0);
    } else {
        String referenceId = pathInfo.substring(1);
        boolean pending = Boolean.parseBoolean(request.getParameter("pending"));
        serialize(referenceId, pending, response);
    }
}

From source file:net.duckling.ddl.web.controller.BaseController.java

/**
 * ?404// w  w  w . j a v  a2 s  .  c  o  m
 * @param request   HttpRequest
 * @param response   HttpResponse
 * @param inTeam   true??false???
 */
protected void notFound(HttpServletRequest request, HttpServletResponse response, boolean inTeam) {
    if (!inTeam) {
        request.setAttribute("accessMain", Boolean.TRUE);
    }
    try {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException e) {
        LOGGER.debug("Error founded in not found :", e);
    }
}

From source file:com.eryansky.modules.sys.web.ProxyController.java

/**
 * ?//w ww . j a v  a  2  s . com
 * @param nativeWebRequest
 * @param contentUrl URL
 * @throws IOException
 */
@RequestMapping(value = { "" })
public void getProxy(NativeWebRequest nativeWebRequest, String contentUrl) throws Exception {

    CustomHttpServletRequestWrapper request = nativeWebRequest
            .getNativeRequest(CustomHttpServletRequestWrapper.class);
    HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
    HttpCompoents httpCompoents = HttpCompoents.getInstance();//?? ?Cookie?
    String param = AppUtils.joinParasWithEncodedValue(WebUtils.getParametersStartingWith(request, null));//?
    String url = contentUrl + "?" + param;
    logger.debug("proxy url{}", url);
    Response remoteResponse = httpCompoents.getResponse(url);
    try {
        // 
        if (remoteResponse == null) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return;
        }
        HttpResponse httpResponse = remoteResponse.returnResponse();
        HttpEntity entity = httpResponse.getEntity();
        // 
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            String errorMsg = "?" + contentUrl;
            logger.error(errorMsg);
            logger.error(httpResponse.getStatusLine().getStatusCode() + "");
            logger.error(EntityUtils.toString(entity, "utf-8"));
            if (WebUtils.isAjaxRequest(request)) {
                WebUtils.renderJson(response, Result.errorResult().setObj(errorMsg));
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, errorMsg);
            }
            return;
        }

        // Header
        response.setContentType(entity.getContentType().getValue());
        if (entity.getContentLength() > 0) {
            response.setContentLength((int) entity.getContentLength());
        }
        // 
        InputStream input = entity.getContent();
        OutputStream output = response.getOutputStream();
        // byte?InputStreamOutputStream, ?4k.
        IOUtils.copy(input, output);
        output.flush();
    } finally {
    }
}

From source file:com.siberhus.web.ckeditor.servlet.BaseActionServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String requestURI = request.getRequestURI();
    if (requestURI != null && requestURI.lastIndexOf("/") != -1) {
        String actionName = requestURI.substring(requestURI.lastIndexOf("/") + 1, requestURI.length());
        int paramIdx = actionName.indexOf("?");
        if (paramIdx != -1) {
            actionName = actionName.substring(0, actionName.indexOf("?"));
        }//from   w  ww  . ja va  2s .  c  o  m
        Method method = null;
        try {
            method = this.getClass().getMethod(actionName, HttpServletRequest.class, HttpServletResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_NOT_FOUND,
                    "Action=" + actionName + " not found for servlet=" + this.getClass());
            return;
        }
        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                request = new MultipartServletRequest(request);
                log.debug("Files *********************");
                MultipartServletRequest mrequest = (MultipartServletRequest) request;
                for (FileItem fileItem : mrequest.getFileItems()) {
                    log.debug("File[fieldName={}, fileName={}, fileSize={}]",
                            new Object[] { fileItem.getFieldName(), fileItem.getName(), fileItem.getSize() });
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Parameters **************************");
                Enumeration<String> paramNames = request.getParameterNames();
                while (paramNames.hasMoreElements()) {
                    String paramName = paramNames.nextElement();
                    log.debug("Param[name={},value(s)={}]",
                            new Object[] { paramName, Arrays.toString(request.getParameterValues(paramName)) });
                }
            }

            Object result = method.invoke(this, request, response);

            if (result instanceof StreamingResult) {
                if (!response.isCommitted()) {
                    ((StreamingResult) result).execute(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvocationTargetException) {
                throw new ServletException(((InvocationTargetException) e).getTargetException());
            }
            throw new ServletException(e);
        }
    }
}

From source file:com.haulmont.cuba.web.sys.CubaWebJarsHandler.java

@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request, VaadinResponse response)
        throws IOException {
    String path = request.getPathInfo();

    if (StringUtils.isEmpty(path) || StringUtils.isNotEmpty(path) && !path.startsWith(VAADIN_WEBJARS_PREFIX)) {
        return false;
    }//w  w w.  j ava 2 s.c  o  m

    log.trace("WebJar resource requested: {}", path.replace(VAADIN_WEBJARS_PREFIX, ""));

    String errorMessage = checkResourcePath(path);
    if (StringUtils.isNotEmpty(errorMessage)) {
        log.warn(errorMessage);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, errorMessage);
        return false;
    }

    URL resourceUrl = getStaticResourceUrl(path);

    if (resourceUrl == null) {
        resourceUrl = getClassPathResourceUrl(path);
    }

    if (resourceUrl == null) {
        String msg = String.format("Requested WebJar resource is not found: %s", path);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, msg);
        log.warn(msg);
        return false;
    }

    String resourceName = getResourceName(path);
    String mimeType = servletContext.getMimeType(resourceName);
    response.setContentType(mimeType != null ? mimeType : FileTypesHelper.DEFAULT_MIME_TYPE);

    String cacheControl = "public, max-age=0, must-revalidate";
    int resourceCacheTime = getCacheTime(resourceName);
    if (resourceCacheTime > 0) {
        cacheControl = "max-age=" + String.valueOf(resourceCacheTime);
    }
    response.setHeader("Cache-Control", cacheControl);
    response.setDateHeader("Expires", System.currentTimeMillis() + (resourceCacheTime * 1000));

    InputStream inputStream = null;
    try {
        URLConnection connection = resourceUrl.openConnection();
        long lastModifiedTime = connection.getLastModified();
        // Remove milliseconds to avoid comparison problems (milliseconds
        // are not returned by the browser in the "If-Modified-Since"
        // header).
        lastModifiedTime = lastModifiedTime - lastModifiedTime % 1000;
        response.setDateHeader("Last-Modified", lastModifiedTime);

        if (browserHasNewestVersion(request, lastModifiedTime)) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return true;
        }

        inputStream = connection.getInputStream();

        copy(inputStream, response.getOutputStream());

        return true;
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

From source file:org.dspace.app.webui.cris.controller.ProjectDetailsController.java

@Override
public ModelAndView handleDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    Project grant = extractProject(request);

    if (grant == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Grant page not found");
        return null;
    }//  w  w  w .  j av a  2 s .co m

    Context context = UIUtil.obtainContext(request);

    EPerson currentUser = context.getCurrentUser();

    if ((grant.getStatus() == null || grant.getStatus().booleanValue() == false)
            && !AuthorizeManager.isAdmin(context)) {

        if (currentUser != null || Authenticate.startAuthentication(context, request, response)) {
            // Log the error
            log.info(LogManager.getHeader(context, "authorize_error",
                    "Only system administrator can access to disabled researcher page"));

            JSPManager.showAuthorizeError(request, response,
                    new AuthorizeException("Only system administrator can access to disabled researcher page"));
        }
        return null;
    }

    if (AuthorizeManager.isAdmin(context)) {
        model.put("grant_page_menu", new Boolean(true));
    }

    ModelAndView mvc = null;

    try {
        mvc = super.handleDetails(request, response);
    } catch (RuntimeException e) {
        return null;
    }

    if (subscribeService != null) {
        boolean subscribed = subscribeService.isSubscribed(currentUser, grant);
        model.put("subscribed", subscribed);

    }

    request.setAttribute("sectionid", StatsConfig.DETAILS_SECTION);
    new DSpace().getEventService().fireEvent(new UsageEvent(UsageEvent.Action.VIEW, request, context, grant));

    mvc.getModel().putAll(model);
    mvc.getModel().put("project", grant);
    return mvc;
}

From source file:org.dspace.app.webui.cris.controller.OUDetailsController.java

@Override
public ModelAndView handleDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> model = new HashMap<String, Object>();

    OrganizationUnit ou = extractOrganizationUnit(request);

    if (ou == null) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "OU page not found");
        return null;
    }/*from  ww  w. j a va  2s .co  m*/

    Context context = UIUtil.obtainContext(request);
    EPerson currentUser = context.getCurrentUser();
    if ((ou.getStatus() == null || ou.getStatus().booleanValue() == false)
            && !AuthorizeManager.isAdmin(context)) {

        if (currentUser != null || Authenticate.startAuthentication(context, request, response)) {
            // Log the error
            log.info(LogManager.getHeader(context, "authorize_error",
                    "Only system administrator can access to disabled researcher page"));

            JSPManager.showAuthorizeError(request, response,
                    new AuthorizeException("Only system administrator can access to disabled researcher page"));
        }
        return null;
    }

    if (AuthorizeManager.isAdmin(context)) {
        model.put("ou_page_menu", new Boolean(true));
    }

    ModelAndView mvc = null;

    try {
        mvc = super.handleDetails(request, response);
    } catch (RuntimeException e) {
        return null;
    }

    if (subscribeService != null) {
        boolean subscribed = subscribeService.isSubscribed(currentUser, ou);
        model.put("subscribed", subscribed);
    }

    request.setAttribute("sectionid", StatsConfig.DETAILS_SECTION);
    new DSpace().getEventService().fireEvent(new UsageEvent(UsageEvent.Action.VIEW, request, context, ou));

    mvc.getModel().putAll(model);
    mvc.getModel().put("ou", ou);
    return mvc;
}

From source file:eionet.gdem.web.struts.stylesheet.EditStylesheetFormAction.java

@Override
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

    ActionMessages errors = new ActionMessages();

    StylesheetForm form = (StylesheetForm) actionForm;
    String stylesheetId = httpServletRequest.getParameter("stylesheetId");

    if (stylesheetId == null || stylesheetId.equals("")) {
        stylesheetId = (String) httpServletRequest.getAttribute("stylesheetId");
    }/*  w w w. ja  v a  2s.c o m*/

    ConvTypeHolder ctHolder = new ConvTypeHolder();
    StylesheetManager stylesheetManager = new StylesheetManager();

    try {
        Stylesheet stylesheet = stylesheetManager.getStylesheet(stylesheetId);

        if (stylesheet == null) {
            try {
                httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            } catch (IOException ex) {
                LOGGER.error("Failed to set 404 response status", ex);
            }

            return actionMapping.findForward(null);
        }

        form.setDescription(stylesheet.getDescription());
        form.setOutputtype(stylesheet.getType());
        form.setStylesheetId(stylesheet.getConvId());
        form.setXsl(stylesheet.getXsl());
        form.setXslContent(stylesheet.getXslContent());
        form.setXslFileName(stylesheet.getXslFileName());
        form.setModified(stylesheet.getModified());
        form.setChecksum(stylesheet.getChecksum());
        form.setSchemas(stylesheet.getSchemas());
        // set empty string if dependsOn is null to avoid struts error in define tag:
        // Define tag cannot set a null value
        form.setDependsOn(stylesheet.getDependsOn() == null ? "" : stylesheet.getDependsOn());

        if (stylesheet.getSchemas().size() > 0) {
            //set first schema for Run Conversion link
            form.setSchema(stylesheet.getSchemas().get(0).getSchema());
            // check if any related schema has type=EXCEL, if yes, then depends on info should be visible
            List<Schema> relatedSchemas = new ArrayList<Schema>(stylesheet.getSchemas());
            CollectionUtils.filter(relatedSchemas,
                    new BeanPredicate("schemaLang", new EqualPredicate("EXCEL")));
            if (relatedSchemas.size() > 0) {
                form.setShowDependsOnInfo(true);
                List<Stylesheet> existingStylesheets = new ArrayList<Stylesheet>();
                for (Schema relatedSchema : relatedSchemas) {
                    CollectionUtils.addAll(existingStylesheets, stylesheetManager
                            .getSchemaStylesheets(relatedSchema.getId(), stylesheetId).toArray());
                }
                form.setExistingStylesheets(existingStylesheets);
            }
        }
        ctHolder = stylesheetManager.getConvTypes();

        /** FIXME - do we need the list of DD XML Schemas on the page
        StylesheetListHolder stylesheetList = StylesheetListLoader.getGeneratedList(httpServletRequest);
        List<Schema> schemas = stylesheetList.getDdStylesheets();
        httpServletRequest.setAttribute("stylesheet.DDSchemas", schemas);
        */

        /*
        String schemaId = schema.getSchemaId(stylesheet.getSchema());
        if (!Utils.isNullStr(schemaId)) {
        httpServletRequest.setAttribute("schemaInfo", schema.getSchema(schemaId));
        httpServletRequest.setAttribute("existingStylesheets", stylesheetManager.getSchemaStylesheets(schemaId, stylesheetId));
        }
        */
        //httpServletRequest.setAttribute(StylesheetListLoader.STYLESHEET_LIST_ATTR, StylesheetListLoader.getStylesheetList(httpServletRequest));

    } catch (DCMException e) {
        e.printStackTrace();
        LOGGER.error("Edit stylesheet error", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(e.getErrorCode()));
        saveErrors(httpServletRequest, errors);
    }
    //TODO why is it needed to update session attribute in each request
    httpServletRequest.getSession().setAttribute("stylesheet.outputtype", ctHolder);

    return actionMapping.findForward("success");
}

From source file:org.wso2.carbon.wsdl2form.StubRequestProcessor.java

public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {

    OutputStream outputStream = response.getOutputStream();
    String requestURL = request.getRequestURL() + "?" + request.getQueryString();
    String serviceParameter = request.getParameter(WSDL2FormGenerator.SERVICE_QUERY_PARAM);
    String endpointParameter = request.getParameter(WSDL2FormGenerator.ENDPOINT_QUERY_PARAM);
    String languageParameter = request.getParameter(WSDL2FormGenerator.LANGUAGE_QUERY_PARAM);
    String localhostParameter = request.getParameter(WSDL2FormGenerator.LOCALHOST_QUERY_PARAM);
    String contentTypeParameter = request.getParameter(WSDL2FormGenerator.CONTENT_TYPE_QUERY_PARAM);

    try {/*from   w  ww .  ja  v  a2 s. co  m*/
        Result result = new StreamResult(outputStream);
        String contentType = WSDL2FormGenerator.getInstance().getJSStub(result, configurationContext,
                requestURL, serviceParameter, endpointParameter, languageParameter, localhostParameter,
                contentTypeParameter);
        response.addHeader(HTTP.CONTENT_TYPE, contentType);
    } catch (CarbonException e) {
        log.error("Cannot generate stub", e);
        response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
        if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_INACTIVE)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Requested Service is inactive. Cannot generate stubs.</h4>").getBytes());
            outputStream.flush();
            return;
        } else if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_NOT_FOUND)) {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            outputStream.write(("<h4>Service cannot be found. Cannot display <em>Stub</em>.</h4>").getBytes());
            outputStream.flush();
            return;
        } else if (e.getMessage().equals(WSDL2FormGenerator.UNSUPPORTED_LANG)) {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Unsupported lang parameter " + languageParameter + "</h4>").getBytes());
            outputStream.flush();
            return;
        } else {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
            outputStream.write(("<h4>" + e.getMessage() + "</h4>").getBytes());
            outputStream.flush();
            return;
        }
    }
}

From source file:grails.plugin.springsecurity.web.filter.IpAddressFilter.java

protected void deny(final HttpServletRequest req, final HttpServletResponse res) throws IOException {
    // send 404 to hide the existence of the resource
    res.sendError(HttpServletResponse.SC_NOT_FOUND);
}