Example usage for javax.servlet.http HttpServletRequest getServletPath

List of usage examples for javax.servlet.http HttpServletRequest getServletPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletPath.

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:de.jwi.jfm.servlets.Controller.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String self = null;/* w w  w.  j av a 2s  .c o  m*/
    String contextPath = null;
    String pathInfo = null;
    Folder folder = null;
    String queryString = null;

    try {
        contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String method = request.getMethod();
        boolean formPosted = "POST".equals(method);

        pathInfo = request.getPathInfo();

        if (null == pathInfo) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + servletPath + " is alive.");

            return;
        }

        File f = new File(filebase, pathInfo);

        if (!f.exists()) {

            PrintWriter writer = response.getWriter();
            writer.print(contextPath + pathInfo + " does not exist.");

            return;
        }

        if (f.isFile()) {
            doDownload(request, response, f);
            return;
        }

        if (!pathInfo.endsWith("/")) {
            response.sendRedirect(request.getRequestURL() + "/");
            return;
        }

        queryString = request.getQueryString();

        String pathTranslated = request.getPathTranslated();
        String requestURI = request.getRequestURI();
        String requestURL = request.getRequestURL().toString();

        self = contextPath + servletPath;

        String fileURL = requestURI.replaceFirst(contextPath, "");
        fileURL = fileURL.replaceFirst(servletPath, "");

        folder = new Folder(f, pathInfo, fileURL);

        folder.load();

        String actionresult = "";

        if (FileUpload.isMultipartContent(request)) {
            try {
                actionresult = handleUpload(request, folder);
                folder.load();
            } catch (Exception e) {
                throw new ServletException(e.getMessage(), e);
            }
        } else if (formPosted || null != queryString) {
            try {
                actionresult = handleQuery(request, response, folder);
            } catch (OutOfSyncException e) {
                actionresult = e.getMessage();
            }
            if (null == actionresult) {
                return;
            }
        }

        request.setAttribute("actionresult", actionresult);
    } catch (SecurityException e) {
        request.setAttribute("actionresult", e.getClass().getName() + " " + e.getMessage());
        request.setAttribute("fatalerror", new Boolean(true));

    }

    String s = request.getRemoteUser();

    Principal principal = request.getUserPrincipal();

    if (principal != null) {
        request.setAttribute("principal", principal.getName());
    }

    request.setAttribute("self", self);

    s = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z").format(new Date());

    request.setAttribute("date", s);

    request.setAttribute("version", version);

    request.setAttribute("builddate", builddate);

    request.setAttribute("javaversion", System.getProperty("java.version"));

    request.setAttribute("serverInfo", getServletContext().getServerInfo());

    request.setAttribute("jfmhome", "https://java.net/projects/jfm");

    request.setAttribute("url", contextPath);

    request.setAttribute("path", pathInfo);

    request.setAttribute("folder", folder);

    String forward = "/WEB-INF/fm.jsp";

    if (queryString != null) {
        // hide get query parameters
        //         response.sendRedirect(request.getRequestURL() + "");
        //         return;
    }

    RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(forward);

    requestDispatcher.forward(request, response);
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

private String getProxyURL(HttpServletRequest httpServletRequest) {
    String stringProxyURL = this.getProxyHostAndPort(httpServletRequest);

    // simply use whatever servlet path that was part of the request as opposed to getting a preset/configurable proxy path
    if (!removePrefix) {
        stringProxyURL += httpServletRequest.getServletPath();
    }/* w  w  w  . j  a  va 2 s  .  co  m*/
    stringProxyURL += "/";

    // Handle the path given to the servlet
    String pathInfo = httpServletRequest.getPathInfo();
    if (pathInfo != null && pathInfo.startsWith("/")) {
        if (stringProxyURL != null && stringProxyURL.endsWith("/")) {
            // avoid double '/'
            stringProxyURL += pathInfo.substring(1);
        }
    } else {
        stringProxyURL += httpServletRequest.getPathInfo();
    }
    // Handle the query string
    if (httpServletRequest.getQueryString() != null) {
        //stringProxyURL += "?" + httpServletRequest.getQueryString();
    }

    return stringProxyURL;
}

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Deletes a User/*from  w w w  .  jav a 2 s.  c o m*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/user/{userMrn}", method = RequestMethod.DELETE)
@ResponseBody
@PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> deleteUser(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String userMrn) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being deleted belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn).equals(MrnUtil.getOrgShortNameFromEntityMrn(userMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        User user = this.entityService.getByMrn(userMrn);
        if (user == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.USER_NOT_FOUND,
                    request.getServletPath());
        }
        if (user.getIdOrganization().compareTo(org.getId()) == 0) {
            this.entityService.delete(user.getId());
            // Remove user from keycloak if created there.
            if (org.getIdentityProviderAttributes() == null || org.getIdentityProviderAttributes().isEmpty()) {
                keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE);
                keycloakAU.deleteUser(user.getEmail());
            }
            return new ResponseEntity<>(HttpStatus.OK);
        }
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.lightbody.bmp.proxy.jetty.servlet.SendRedirect.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache,no-store");

    String url = request.getParameter("URL");
    if (url != null && url.length() > 0) {
        response.sendRedirect(url);// w w  w  .  j  a va 2  s.  c o m
    } else {
        PrintWriter pout = response.getWriter();
        Page page = null;

        try {
            page = new Page();
            page.title("SendRedirect Servlet");

            page.add(new Heading(1, "SendRedirect Servlet"));

            page.add(new Heading(1, "Form to generate Dump content"));
            TableForm tf = new TableForm(response
                    .encodeURL(URI.addPaths(request.getContextPath(), request.getServletPath()) + "/action"));
            tf.method("GET");
            tf.addTextField("URL", "URL", 40, request.getContextPath() + "/dump");
            tf.addButton("Redirect", "Redirect");
            page.add(tf);
            page.write(pout);
            pout.close();
        } catch (Exception e) {
            log.warn(LogSupport.EXCEPTION, e);
        }
    }
}

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Sync user from keycloak, diff from create/update user is that this should only be done by
 * the keycloak sync-mechanism. /*from   w w  w  .  j a v a 2 s .c o m*/
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@ApiOperation(hidden = true, value = "Sync user from keycloak")
@RequestMapping(value = "/api/org/{orgMrn}/user-sync/", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public ResponseEntity<?> syncUser(HttpServletRequest request, @PathVariable String orgMrn,
        @RequestBody User input, @RequestParam(value = "org-name", required = false) String orgName,
        @RequestParam(value = "org-address", required = false) String orgAddress) throws McBasicRestException {
    if (!AccessControlUtil.isUserSync(this.userSyncMRN, this.userSyncO, this.userSyncOU, this.userSyncC)) {
        throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrnNoFilter(orgMrn);
    // The organization does not exists - check if this a an organization hosted by an external "validator".
    if (org == null && orgAddress != null && orgName != null) {
        // Check that the org shortname is the same for the orgMrn and originalErrorMessage
        String orgShortname = MrnUtil.getOrgShortNameFromOrgMrn(orgMrn);
        if (!orgShortname.equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                    request.getServletPath());
        }
        // Since the permissions of this user will be used as a template for administrator permissions, it must be
        // verified that the user actually has some permissions.
        if (input.getPermissions() == null || input.getPermissions().isEmpty()) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ROLE_NOT_FOUND,
                    request.getServletPath());
        }
        // Check validators?
        String orgValidator = MrnUtil.getOrgValidatorFromOrgShortname(orgShortname);
        // Create the new org based on given info
        org = new Organization();
        org.setName(orgName);
        org.setMrn(orgMrn);
        org.setApproved(true);
        org.setEmail(input.getEmail());
        // Extract domain-name from the user email and use that for org url.
        int at = input.getEmail().indexOf("@");
        String url = "http://" + input.getEmail().substring(at + 1);
        org.setUrl(url);
        // Extract country from address
        String country;
        String address;
        int lastComma = orgAddress.lastIndexOf(",");
        if (lastComma > 0) {
            country = orgAddress.substring(lastComma + 1).trim();
            address = orgAddress.substring(0, lastComma).trim();
        } else {
            country = "The Seven Seas";
            address = orgAddress;
        }
        org.setAddress(address);
        org.setCountry(country);
        org.setFederationType("external-idp");
        // save the new organization
        org = this.organizationService.save(org);
        // Create the initial roles for the organization. The permissions of the first user is used to define the ORG_ADMIN
        // Come on! That's a great idea!!
        if (input.getPermissions() != null) {
            for (String permission : input.getPermissions().split(",")) {
                Role newRole = new Role();
                newRole.setRoleName("ROLE_ORG_ADMIN");
                newRole.setPermission(permission.trim());
                newRole.setIdOrganization(org.getId());
                this.roleService.save(newRole);
            }
        }
    }

    if (org != null) {
        String userMrn = input.getMrn();
        if (userMrn == null || userMrn.isEmpty()) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.USER_NOT_FOUND,
                    request.getServletPath());
        }
        User oldUser = this.entityService.getByMrn(userMrn);
        // If user does not exists, we create him
        if (oldUser == null) {
            input.setIdOrganization(org.getId());
            this.entityService.save(input);
        } else {
            // Update the existing user and save
            oldUser = input.selectiveCopyTo(oldUser);
            this.entityService.save(oldUser);
        }
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:com.alfaariss.oa.OAServlet.java

/**
 * Process HTTP requests.//  w  w w. j a va 2s .c  om
 * 
 * Retrieve an enabled requestor profile or helper for the given request 
 * and delegate the request using the following algorithm:
 * 
 * <dl>
 *  <dt>type (helper or profile)</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} from 
 *      {@link HttpServletRequest#getContextPath()} till '/' minus slashes</dd>
 *  <dt>id of helper or profile</dt>
 *  <dd>{@link HttpServletRequest#getRequestURI()} 
 *      first '/' till second '/' minus slashes</dd>
 * </dl>
 * 
 * @see javax.servlet.http.HttpServlet#service(
 *  javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
public void service(HttpServletRequest oRequest, HttpServletResponse oResponse)
        throws ServletException, IOException {
    try {
        String sRequestURI = oRequest.getRequestURI();

        //Check if profiles are available
        if (_profiles.isEmpty() && _helpers.isEmpty())
            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);

        //Retrieve profile
        String sContextPath = oRequest.getContextPath();
        String sServletPath = oRequest.getServletPath();

        //type = uri  - context
        String sType = sRequestURI.substring(sContextPath.length());
        if (sType.length() <= 1) {
            //No profile or helper requested
            oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
        } else {
            //type minus slashes 
            sType = sType.substring(1, sType.length());
            int index = sType.indexOf('/');
            if (index <= 1) {
                _logger.debug("Bad request: no id in path: " + sServletPath);
                //No id requested
                oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
            } else {

                String sId = sType.substring(index + 1, sType.length()); //id minus slashes 
                sType = sType.substring(0, index);
                if (_logger.isDebugEnabled())
                    _logger.debug("Processing: " + sType + " request");

                //sId = sId.substring(1, sId.length());
                index = sId.indexOf('/');
                if (index > 0) {
                    //remove suffix
                    sId = sId.substring(0, index);
                }

                try {
                    ServiceTypes type = ServiceTypes.valueOf(sType);
                    switch (type) {
                    case helpers: {
                        IHelper helper = _helpers.get(sId);
                        if (helper == null || !(helper instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else if (!helper.isEnabled())
                            oResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, sRequestURI);
                        else
                            ((IService) helper).service(oRequest, oResponse);
                        break;
                    }
                    case profiles: {
                        IRequestorProfile profile = _profiles.get(sId);
                        if (profile == null || !(profile instanceof IService))
                            oResponse.sendError(HttpServletResponse.SC_NOT_FOUND, sRequestURI);
                        else
                            ((IService) profile).service(oRequest, oResponse);
                        break;
                    }
                    }
                } catch (IllegalArgumentException e) {
                    _logger.debug("Bad request", e);
                    //Invalid type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                } catch (NullPointerException e) {
                    _logger.debug("Bad request", e);
                    //No type requested
                    oResponse.sendError(HttpServletResponse.SC_BAD_REQUEST);
                }
            }
        }

        //send okay if no response is sent yet
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_OK);
    } catch (OAException e) {
        _logger.error("Could not process request", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } catch (Exception e) {
        _logger.fatal("Could not process request due to internal error", e);
        if (!oResponse.isCommitted())
            oResponse.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaController.java

@RequestMapping(value = { "/oauth/token" }, params = "grant_type=password")
@ResponseBody/*from   ww w . j a v a  2s.c o  m*/
public ResponseEntity<byte[]> passwordGrant(HttpServletRequest request,
        @RequestHeader("Authorization") String authorization, @RequestHeader HttpHeaders headers,
        @RequestBody MultiValueMap<String, String> originalBody, Map<String, Object> model, Principal principal)
        throws Exception {
    logger.info("Passing through password grant token request for " + request.getServletPath());

    Set<String> maskedAttribute = new HashSet<>();
    maskedAttribute.add("password");
    maskedAttribute.add("client_secret");
    LinkedMaskingMultiValueMap<String, String> body = new LinkedMaskingMultiValueMap<>(maskedAttribute);
    for (Map.Entry<String, List<String>> entry : originalBody.entrySet()) {
        body.put(entry.getKey(), entry.getValue());
    }

    body.setAll(getLoginCredentials(principal));
    //for grant_type=password, we want to do user authentication
    //in the login server rather than in UAA
    String[] basic = extractAndDecodeHeader(authorization);
    //create a modifiable list
    headers = getRequestHeaders(headers);
    headers.remove(AUTHORIZATION);
    headers.remove(AUTHORIZATION.toLowerCase());
    body.remove("client_id");
    body.add("client_id", basic[0]);
    body.add("client_secret", basic[1]);
    body.add("source", "login");

    //remove multiple values as the UAA can't handle it
    body.remove("grant_type");
    if (!extractPath(request).contains("grant_type")) {
        body.add("grant_type", "password");
    }

    HttpEntity entity = new HttpEntity(body, headers);
    return passthru(request, entity, model, true);
}

From source file:com.logiclander.jaasmine.authentication.http.JaasLoginFilter.java

/**
 * This implementation will filter requests for credentials and determine if
 * processing of the FilterChain can proceed.  Filtering occurs as follows:
 * <OL>//from   w  w w. j  ava  2 s .  co  m
 *  <LI>If the request is not an HttpServletRequest and the response is not
 * an HttpServletResponse, continue processing the filter chain (this almost
 * never happens)</LI>
 *  <LI>The HttpSession is checked for an attribute named
 * {@link AuthenticationService#SUBJECT_KEY
 * AuthenticationService.SUBJECT_KEY}</LI>
 *  <LI>If found, then processing the filter chain continues.</LI>
 *  <LI>If not found, then the request is checked for the {@code username}
 * and {@code password} parameters.  If these parameters are present, then
 * the SimpleAuthenticationService's login method is invoked with those
 * credentials.</LI>
 *  <LI>If a Subject is returned, it is saved to the HttpSession with the
 * key from above.</LI>
 * </OL>
 * When the login is successful, the ServletRequest is wrapped in a
 * {@link JaasmineHttpServletRequest}.  If it is unsuccessful, this filter
 * will send the request to a login processor as follows:
 * <OL>
 *  <LI>If {@code loginPath} is set, dispatch the request to that resource.
 * </LI>
 *  <LI>If (@code loginRedirect} is set, redirect the request to that URL.
 * </LI>
 *  <LI>Dispatch to {@code loginServletName} if neither of the above are
 * set./LI>
 * </OL>
 *
 * @param request the ServletRequest
 * @param response the ServletResponse
 * @param chain the FilterChain
 * @throws IOException if an I/O error occurs in the FilterChain
 * @throws ServletException if a processing error occurs in the FilterChain
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("%s: entering doFilter", filterName));
    }

    if (!(request instanceof HttpServletRequest) && !(response instanceof HttpServletResponse)) {

        logger.debug("This is not an HTTP request");
        chain.doFilter(request, response);

    } else {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        Exception exception = null;

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Filtering request: %s%s", httpReq.getContextPath(),
                    httpReq.getServletPath()));
        }

        try {

            if (!hasRequestUri(httpReq)) {
                cacheRequestUri(httpReq);
            }

            boolean canExecute = hasCredentials(httpReq);

            // Attempt to login the user and obtain a Subject.

            if (!canExecute) {
                canExecute = login(httpReq);
            }

            if (canExecute) {

                // The Subject was found which means the user has a valid
                // credential (Subject).  Processing can continue.

                // TODO: always wrap request, set to cached requestURI
                HttpServletRequest sendOn = httpReq;

                if (setRemoteUserOnLogin) {
                    sendOn = new JaasmineHttpServletRequest(httpReq, getSubject(httpReq));
                    logger.debug(String.format("Wrapping request in %s", sendOn.toString()));

                }

                chain.doFilter(sendOn, httpResp);

            } else {

                // No Subject found, need to dispatch to someplace to gather
                // the user's credentials and attempt a login on the
                // next request.

                RequestDispatcher loginDispatcher = null;
                if (!loginPath.equals(EMPTY_STRING)) {

                    loginDispatcher = httpReq.getSession().getServletContext().getRequestDispatcher(loginPath);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to path %s", loginPath));
                    }

                } else if (!loginRedirect.equals(EMPTY_STRING)) {

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Redirectiong login " + "request to %s", loginRedirect));
                    }
                    httpResp.sendRedirect(loginRedirect);

                    // TODO: cache incoming requestURI

                    return;

                } else if (isUsingBasicAuthentication) {

                    String s = "Basic realm=\"Jaasmine\"";
                    httpResp.setHeader("WWW-Authenticate", s);
                    httpResp.setStatus(401);

                    return;
                } else {

                    loginDispatcher = httpReq.getSession().getServletContext()
                            .getNamedDispatcher(loginServletName);

                    if (logger.isDebugEnabled()) {
                        logger.debug(String.format("Dispatching login " + "request to named dispatcher %s",
                                loginServletName));
                    }
                }

                if (loginDispatcher != null) {

                    loginDispatcher.forward(httpReq, httpResp);
                    return;

                } else {

                    // Try to figure out what went wrong and send back
                    // a HELPFUL exception message.

                    String msg = "";

                    if (!loginPath.equals(EMPTY_STRING)) {

                        // First, is there a loginPath set, but nowhere to
                        // send it to?

                        msg = String.format(
                                "loginPath set to %s, but no " + "resource is available to dispatch to",
                                loginPath);
                    } else {

                        // Is JaasLoginServlet (or the servlet-name
                        // specified by loginServletName) not configured in
                        // the web.xml?

                        msg = String.format("Servlet named %s specified by "
                                + "the loginServletName is not configured in " + "the web.xml",
                                loginServletName);
                    }

                    throw new ServletException(msg);

                }
            }

        } catch (IOException ex) {

            exception = ex;
            throw (ex);

        } catch (ServletException ex) {

            exception = ex;
            throw (ex);

        } finally {

            if (exception != null) {

                if (logger.isErrorEnabled()) {
                    String msg = String.format("Caught exception in filter chain: %s", exception.getMessage());
                    logger.error(msg, exception);
                }
            }

        }
    }
}

From source file:it.unimi.di.big.mg4j.query.QueryServlet.java

public Template handleRequest(final HttpServletRequest request, final HttpServletResponse response,
        final Context context) {

    try {//  www. j a  va 2  s .  c om
        response.setCharacterEncoding("UTF-8");

        // This string is URL-encoded, and with the wrong coding.
        //String query = request.getParameter( "q" ) != null ? new String( request.getParameter( "q" ).getBytes( "ISO-8859-1" ), "UTF-8" ) : null;
        String query = request.getParameter("q");
        context.put("action", request.getContextPath() + request.getServletPath());

        // Sanitise parameters.
        int start = 0, maxNumItems = STD_MAX_NUM_ITEMS;
        try {
            maxNumItems = Integer.parseInt(request.getParameter("m"));
        } catch (NumberFormatException dontCare) {
        }
        try {
            start = Integer.parseInt(request.getParameter("s"));
        } catch (NumberFormatException dontCare) {
        }

        if (maxNumItems < 0 || maxNumItems > 1000)
            maxNumItems = STD_MAX_NUM_ITEMS;
        if (start < 0)
            start = 0;

        if (query != null && query.length() != 0) {

            // This is used to display again the query in the input control.
            context.put("q", StringEscapeUtils.escapeHtml(query));
            // This is used to put the query in URLs.
            context.put("qUrl", URLEncoder.encode(query, "UTF-8"));
            context.put("firstItem", new Integer(start));

            // First of all, we check that the query is correct

            long time = -System.currentTimeMillis();
            ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>> results = new ObjectArrayList<DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>>>();

            int globNumItems;

            try {
                globNumItems = queryEngine.copy().process(query, start, maxNumItems, results);
            } catch (QueryBuilderVisitorException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (QueryParserException e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.getCause().toString()));
                return getTemplate(template);
            } catch (Exception e) {
                context.put("errmsg", StringEscapeUtils.escapeHtml(e.toString()));
                return getTemplate(template);
            }

            time += System.currentTimeMillis();

            ObjectArrayList<ResultItem> resultItems = new ObjectArrayList<ResultItem>();

            if (!results.isEmpty()) {
                SelectedInterval[] selectedInterval = null;

                final DocumentCollection collection = documentCollection != null ? documentCollection.copy()
                        : null;

                for (int i = 0; i < results.size(); i++) {
                    DocumentScoreInfo<Reference2ObjectMap<Index, SelectedInterval[]>> dsi = results.get(i);
                    LOGGER.debug("Intervals for item " + i);
                    final ResultItem resultItem = new ResultItem(dsi.document, dsi.score);
                    resultItems.add(resultItem);

                    if (collection != null) {
                        final Document document = collection.document(dsi.document);
                        // If both collection and title list are present, we override the collection title (cfr. Query)
                        resultItem.title = StringEscapeUtils
                                .escapeHtml(titleList != null ? titleList.get(resultItem.doc).toString()
                                        : document.title().toString());
                        if (useUri) {
                            if (document.uri() != null)
                                resultItem.uri = StringEscapeUtils.escapeHtml(document.uri().toString());
                        } else {
                            if (document.uri() != null) {
                                String stringUri = document.uri().toString();
                                // TODO: this is a quick patch to get the file server running with relative files
                                final String documentUri = URLEncoder.encode(derelativise
                                        ? new File(stringUri.startsWith("file:") ? stringUri.substring(5)
                                                : stringUri).getAbsoluteFile().toURI().toASCIIString()
                                        : document.uri().toString(), "UTF-8");
                                resultItem.uri = StringEscapeUtils.escapeHtml("./Item?doc=" + resultItem.doc
                                        + "&m=" + urlEncodedMimeType + "&uri=" + documentUri);
                            } else
                                resultItem.uri = StringEscapeUtils.escapeHtml(
                                        "./Item?doc=" + resultItem.doc + "&m=" + urlEncodedMimeType);
                        }

                        MarkingMutableString snippet = new MarkingMutableString(TextMarker.HTML_STRONG,
                                MarkingMutableString.HTML_ESCAPE);

                        for (int j = 0; j < sortedIndex.length; j++) {
                            if (!sortedIndex[j].hasPositions || dsi.info == null)
                                continue;
                            selectedInterval = dsi.info.get(sortedIndex[j]);
                            if (selectedInterval != null) {
                                final int field = documentCollection.factory().fieldIndex(sortedIndex[j].field);
                                // If the field is not present (e.g., because of parallel indexing) or it is not text we skip
                                if (field == -1 || documentCollection.factory()
                                        .fieldType(field) != DocumentFactory.FieldType.TEXT)
                                    continue;
                                LOGGER.debug(
                                        "Found intervals for " + sortedIndex[j].field + " (" + field + ")");
                                final Reader content = (Reader) document.content(field);
                                snippet.startField(selectedInterval)
                                        .appendAndMark(document.wordReader(field).setReader(content))
                                        .endField();
                            }
                            if (LOGGER.isDebugEnabled())
                                LOGGER.debug(sortedIndex[j].field + ": "
                                        + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                            document.close();
                        }

                        resultItem.text = snippet;
                    } else {
                        if (titleList != null) {
                            // TODO: this is a bit radical
                            resultItem.title = resultItem.uri = titleList.get(resultItem.doc);
                        } else {
                            resultItem.title = "Document #" + resultItem.doc;
                            resultItem.uri = new MutableString("./Item?doc=").append(resultItem.doc)
                                    .append("&m=").append(urlEncodedMimeType);
                        }

                        MutableString text = new MutableString();
                        for (Iterator<Index> j = indexMap.values().iterator(); j.hasNext();) {
                            final Index index = j.next();
                            selectedInterval = dsi.info.get(index);
                            if (selectedInterval != null)
                                text.append("<p>").append(index.field).append(": ")
                                        .append(Arrays.asList(selectedInterval));
                            LOGGER.debug(index.field + ": "
                                    + (selectedInterval == null ? null : Arrays.asList(selectedInterval)));
                        }
                        resultItem.text = text;
                    }
                }

                if (collection != null)
                    collection.close();
            }

            // Note that if we pass an array to the template we lose the possibility of measuring its length.
            context.put("result", resultItems);
            /* Note that this number is just the number of relevant documents met while
               trying to obtain the current results. Due to the short-circuit semantics of the
               "and then" operator, it  might not reflect accurately the overall number of
               results of the query. */
            context.put("globNumItems", new Integer(globNumItems));
            context.put("start", new Integer(start));
            context.put("maxNumItems", new Integer(maxNumItems));
            context.put("time", new Integer((int) time));
            context.put("speed", new Long((int) (globNumItems * 1000L / (time + 1))));
        }

        return getTemplate(template);
    } catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }
}

From source file:eionet.eunis.servlets.DownloadServlet.java

/**
 * Process the actual request./*from w w  w. ja  va2 s .com*/
 *
 * @param request The request to be processed.
 * @param response The response to be created.
 * @param content Whether the request body should be written (GET) or not (HEAD).
 * @throws IOException If something fails at I/O level.
 * @throws ServletException
 */
private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content)
        throws IOException, ServletException {

    String requestURI = request.getRequestURI();
    String contextPath = request.getContextPath();
    String pathInfo = request.getPathInfo();
    String servletPath = request.getServletPath();

    // Create the abstract file reference to the requested file.
    File file = null;
    String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath());
    fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " ");
    if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) {
        file = new File(appHome, fileRelativePath);
    }

    // If file was not found, send 404.
    if (file == null || !file.exists() || file.isDirectory()) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;

    // Validate request headers for caching ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so, then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setHeader("ETag", eTag); // Required in 304.
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Validate request headers for resume ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required in 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response --------------------------------------------------------

    // Get content type by file name and set default GZIP support and content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding is supported by
    // the browser and expand content type with the one and right character encoding.
    // Else, expect for images, determine content disposition. If content type is supported by
    // the browser, then set to inline, else attachment which will pop a 'save as' dialogue.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    } else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    // Initialize response.
    response.reset();
    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);

    // Send requested file (part(s)) to client ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of GZIP.
                    // So only add it if there is no means of GZIP, else browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}