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:com.lc.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null
            && !modelAndView.getModel().containsKey(ThirdPartyConstants.SeoRobots.META_ROBOTS)) {
        // Build a default directive
        String robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW;

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_FOLLOW;
            }/*from w ww  .j  a v a  2s.c  om*/
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = ThirdPartyConstants.SeoRobots.INDEX_FOLLOW;
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW;
        }

        modelAndView.addObject(ThirdPartyConstants.SeoRobots.META_ROBOTS, robotsValue);
    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get(ThirdPartyConstants.SeoRobots.META_ROBOTS));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:org.loklak.api.server.SearchServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response)
        throws ServletException, IOException {
    final RemoteAccess.Post post = RemoteAccess.evaluate(request);
    try {/* ww  w .j a v a  2s .c  o  m*/

        // manage DoS
        if (post.isDoS_blackout()) {
            response.sendError(503, "your (" + post.getClientHost() + ") request frequency is too high");
            return;
        }

        // check call type
        boolean jsonExt = request.getServletPath().endsWith(".json");
        boolean rssExt = request.getServletPath().endsWith(".rss");
        boolean txtExt = request.getServletPath().endsWith(".txt");

        // evaluate get parameter
        String callback = post.get("callback", "");
        boolean jsonp = callback != null && callback.length() > 0;
        boolean minified = post.get("minified", false);
        String query = post.get("q", "");
        if (query == null || query.length() == 0)
            query = post.get("query", "");
        query = CharacterCoding.html2unicode(query).replaceAll("\\+", " ");
        final long timeout = (long) post.get("timeout", DAO.getConfig("search.timeout", 2000));
        final int count = post.isDoS_servicereduction() ? 10
                : Math.min(post.get("count", post.get("maximumRecords", 100)),
                        post.isLocalhostAccess() ? 10000 : 1000);
        String source = post.isDoS_servicereduction() ? "cache" : post.get("source", "all"); // possible values: cache, backend, twitter, all
        int limit = post.get("limit", 100);
        String[] fields = post.get("fields", new String[0], ",");
        int timezoneOffset = post.get("timezoneOffset", 0);
        if (query.indexOf("id:") >= 0 && ("all".equals(source) || "twitter".equals(source)))
            source = "cache"; // id's cannot be retrieved from twitter with the scrape-api (yet), only from the cache
        final String ordername = post.get("order", Timeline.Order.CREATED_AT.getMessageFieldName());
        final Timeline.Order order = Timeline.parseOrder(ordername);

        // create tweet timeline
        final Timeline tl = new Timeline(order);
        Map<String, List<Map.Entry<String, Long>>> aggregations = null;
        final QueryEntry.Tokens tokens = new QueryEntry.Tokens(query);

        final AtomicInteger cache_hits = new AtomicInteger(0), count_backend = new AtomicInteger(0),
                count_twitter_all = new AtomicInteger(0), count_twitter_new = new AtomicInteger(0);
        final boolean backend_push = DAO.getConfig("backend.push.enabled", false);

        if ("all".equals(source)) {
            // start all targets for search concurrently
            final int timezoneOffsetf = timezoneOffset;
            final String queryf = query;
            final long start = System.currentTimeMillis();

            // start a scraper
            Thread scraperThread = tokens.raw.length() == 0 ? null : new Thread() {
                public void run() {
                    final String scraper_query = tokens.translate4scraper();
                    DAO.log(request.getServletPath() + " scraping with query: " + scraper_query);
                    Timeline twitterTl = DAO.scrapeTwitter(post, scraper_query, order, timezoneOffsetf, true,
                            timeout, true);
                    count_twitter_new.set(twitterTl.size());
                    tl.putAll(QueryEntry.applyConstraint(twitterTl, tokens, false)); // pre-localized results are not filtered with location constraint any more 
                    tl.setScraperInfo(twitterTl.getScraperInfo());
                    post.recordEvent("twitterscraper_time", System.currentTimeMillis() - start);
                }
            };
            if (scraperThread != null)
                scraperThread.start();

            // start a local search
            Thread localThread = queryf == null || queryf.length() == 0 ? null : new Thread() {
                public void run() {
                    DAO.SearchLocalMessages localSearchResult = new DAO.SearchLocalMessages(queryf, order,
                            timezoneOffsetf, count, 0);
                    post.recordEvent("cache_time", System.currentTimeMillis() - start);
                    cache_hits.set(localSearchResult.timeline.getHits());
                    tl.putAll(localSearchResult.timeline);
                }
            };
            if (localThread != null)
                localThread.start();

            // start a backend search, but only if backend_push == true or result from scraper is too bad
            boolean start_backend_thread = false;
            if (backend_push)
                start_backend_thread = true;
            else {
                // wait now for termination of scraper thread and local search
                // to evaluate how many results are available
                if (scraperThread != null)
                    try {
                        scraperThread.join(Math.max(10000, timeout - System.currentTimeMillis() + start));
                    } catch (InterruptedException e) {
                    }
                if (localThread != null)
                    try {
                        localThread.join(Math.max(100, timeout - System.currentTimeMillis() + start));
                    } catch (InterruptedException e) {
                    }
                localThread = null;
                scraperThread = null;
                if (tl.size() < count)
                    start_backend_thread = true;
            }
            Thread backendThread = tokens.original.length() == 0 || !start_backend_thread ? null
                    : new Thread() {
                        public void run() {
                            Timeline backendTl = DAO.searchBackend(tokens.original, order, count,
                                    timezoneOffsetf, "cache", timeout);
                            if (backendTl != null) {
                                tl.putAll(QueryEntry.applyConstraint(backendTl, tokens, true));
                                count_backend.set(tl.size());
                                // TODO: read and aggregate aggregations from backend as well
                            }
                            post.recordEvent("backend_time", System.currentTimeMillis() - start);
                        }
                    };
            if (backendThread != null)
                backendThread.start();

            // wait for termination of all threads
            if (scraperThread != null)
                try {
                    scraperThread.join(Math.max(10000, timeout - System.currentTimeMillis() + start));
                } catch (InterruptedException e) {
                }
            if (localThread != null)
                try {
                    localThread.join(Math.max(100, timeout - System.currentTimeMillis() + start));
                } catch (InterruptedException e) {
                }
            if (backendThread != null)
                try {
                    backendThread.join(Math.max(100, timeout - System.currentTimeMillis() + start));
                } catch (InterruptedException e) {
                }

        } else if ("twitter".equals(source) && tokens.raw.length() > 0) {
            final long start = System.currentTimeMillis();
            final String scraper_query = tokens.translate4scraper();
            DAO.log(request.getServletPath() + " scraping with query: " + scraper_query);
            Timeline twitterTl = DAO.scrapeTwitter(post, scraper_query, order, timezoneOffset, true, timeout,
                    true);
            count_twitter_new.set(twitterTl.size());
            tl.putAll(QueryEntry.applyConstraint(twitterTl, tokens, false)); // pre-localized results are not filtered with location constraint any more 
            tl.setScraperInfo(twitterTl.getScraperInfo());
            post.recordEvent("twitterscraper_time", System.currentTimeMillis() - start);
            // in this case we use all tweets, not only the latest one because it may happen that there are no new and that is not what the user expects

        } else if ("cache".equals(source)) {
            final long start = System.currentTimeMillis();
            DAO.SearchLocalMessages localSearchResult = new DAO.SearchLocalMessages(query, order,
                    timezoneOffset, count, limit, fields);
            cache_hits.set(localSearchResult.timeline.getHits());
            tl.putAll(localSearchResult.timeline);
            aggregations = localSearchResult.aggregations;
            post.recordEvent("cache_time", System.currentTimeMillis() - start);

        } else if ("backend".equals(source) && query.length() > 0) {
            final long start = System.currentTimeMillis();
            Timeline backendTl = DAO.searchBackend(query, order, count, timezoneOffset, "cache", timeout);
            if (backendTl != null) {
                tl.putAll(QueryEntry.applyConstraint(backendTl, tokens, true));
                tl.setScraperInfo(backendTl.getScraperInfo());
                // TODO: read and aggregate aggregations from backend as well
                count_backend.set(tl.size());
            }
            post.recordEvent("backend_time", System.currentTimeMillis() - start);

        }

        final long start = System.currentTimeMillis();
        // check the latest user_ids
        DAO.announceNewUserId(tl);

        // reduce the list to the wanted number of results if we have more
        tl.reduceToMaxsize(count);

        if (post.isDoS_servicereduction() && !RemoteAccess.isSleepingForClient(post.getClientHost())) {
            RemoteAccess.sleep(post.getClientHost(), 2000);
        }

        // create json or xml according to path extension
        int shortlink_iflinkexceedslength = (int) DAO.getConfig("shortlink.iflinkexceedslength", 500L);
        String shortlink_urlstub = DAO.getConfig("shortlink.urlstub", "http://localhost:9000");
        if (jsonExt) {
            post.setResponse(response, jsonp ? "application/javascript" : "application/json");
            // generate json
            Map<String, Object> m = new LinkedHashMap<String, Object>();
            Map<String, Object> metadata = new LinkedHashMap<String, Object>();
            if (!minified) {
                m.put("readme_0",
                        "THIS JSON IS THE RESULT OF YOUR SEARCH QUERY - THERE IS NO WEB PAGE WHICH SHOWS THE RESULT!");
                m.put("readme_1",
                        "loklak.org is the framework for a message search system, not the portal, read: http://loklak.org/about.html#notasearchportal");
                m.put("readme_2",
                        "This is supposed to be the back-end of a search portal. For the api, see http://loklak.org/api.html");
                m.put("readme_3",
                        "Parameters q=(query), source=(cache|backend|twitter|all), callback=p for jsonp, maximumRecords=(message count), minified=(true|false)");
            }
            metadata.put("itemsPerPage", Integer.toString(count));
            metadata.put("count", Integer.toString(tl.size()));
            metadata.put("count_twitter_all", count_twitter_all.get());
            metadata.put("count_twitter_new", count_twitter_new.get());
            metadata.put("count_backend", count_backend.get());
            metadata.put("count_cache", cache_hits.get());
            metadata.put("hits", Math.max(cache_hits.get(), tl.size()));
            if (order == Timeline.Order.CREATED_AT)
                metadata.put("period", tl.period());
            metadata.put("query", query);
            metadata.put("client", post.getClientHost());
            metadata.put("time", System.currentTimeMillis() - post.getAccessTime());
            metadata.put("servicereduction", post.isDoS_servicereduction() ? "true" : "false");
            if (tl.getScraperInfo().length() > 0)
                metadata.put("scraperInfo", tl.getScraperInfo());
            m.put("search_metadata", metadata);
            List<Object> statuses = new ArrayList<>();
            try {
                for (MessageEntry t : tl) {
                    UserEntry u = tl.getUser(t);
                    if (DAO.getConfig("flag.fixunshorten", false))
                        t.setText(TwitterScraper
                                .unshorten(t.getText(shortlink_iflinkexceedslength, shortlink_urlstub)));
                    statuses.add(t.toMap(u, true, shortlink_iflinkexceedslength, shortlink_urlstub));
                }
            } catch (ConcurrentModificationException e) {
                // late incoming messages from concurrent peer retrieval may cause this
                // we silently do nothing here and return what we listed so far
            }
            m.put("statuses", statuses);

            // aggregations
            Map<String, Object> agg = new LinkedHashMap<String, Object>();
            if (aggregations != null) {
                for (Map.Entry<String, List<Map.Entry<String, Long>>> aggregation : aggregations.entrySet()) {
                    Map<String, Object> facet = new LinkedHashMap<>();
                    for (Map.Entry<String, Long> a : aggregation.getValue()) {
                        if (a.getValue().equals(query))
                            continue; // we omit obvious terms that cannot be used for faceting, like search for "#abc" -> most hashtag is "#abc"
                        facet.put(a.getKey(), a.getValue());
                    }
                    agg.put(aggregation.getKey(), facet);
                }
            }
            m.put("aggregations", agg);

            // write json
            response.setCharacterEncoding("UTF-8");
            PrintWriter sos = response.getWriter();
            if (jsonp)
                sos.print(callback + "(");
            sos.print(minified ? new ObjectMapper().writer().writeValueAsString(m)
                    : new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(m));
            if (jsonp)
                sos.println(");");
            sos.println();
        } else if (rssExt) {
            response.setCharacterEncoding("UTF-8");
            post.setResponse(response, "application/rss+xml;charset=utf-8");
            // generate xml
            RSSMessage channel = new RSSMessage();
            channel.setPubDate(new Date());
            channel.setTitle("RSS feed for Twitter search for " + query);
            channel.setDescription("");
            channel.setLink("");
            RSSFeed feed = new RSSFeed(tl.size());
            feed.setChannel(channel);
            try {
                for (MessageEntry t : tl) {
                    UserEntry u = tl.getUser(t);
                    RSSMessage m = new RSSMessage();
                    m.setLink(t.getStatusIdUrl().toExternalForm());
                    m.setAuthor(u.getName() + " @" + u.getScreenName());
                    m.setTitle(u.getName() + " @" + u.getScreenName());
                    m.setDescription(t.getText(shortlink_iflinkexceedslength, shortlink_urlstub));
                    m.setPubDate(t.getCreatedAt());
                    m.setGuid(t.getIdStr());
                    feed.addMessage(m);
                }
            } catch (ConcurrentModificationException e) {
                // late incoming messages from concurrent peer retrieval may cause this
                // we silently do nothing here and return what we listed so far
            }
            String rss = feed.toString();
            //System.out.println("feed has " + feed.size() + " entries");

            // write xml
            response.getOutputStream().write(UTF8.getBytes(rss));
        } else if (txtExt) {
            post.setResponse(response, "text/plain");
            final StringBuilder buffer = new StringBuilder(1000);
            try {
                for (MessageEntry t : tl) {
                    UserEntry u = tl.getUser(t);
                    buffer.append(t.getCreatedAt()).append(" ").append(u.getScreenName()).append(": ")
                            .append(t.getText(shortlink_iflinkexceedslength, shortlink_urlstub)).append('\n');
                }
            } catch (ConcurrentModificationException e) {
                // late incoming messages from concurrent peer retrieval may cause this
                // we silently do nothing here and return what we listed so far
            }
            response.getOutputStream().write(UTF8.getBytes(buffer.toString()));
        }
        post.recordEvent("result_count", tl.size());
        post.recordEvent("postprocessing_time", System.currentTimeMillis() - start);
        Map<String, Object> hits = new LinkedHashMap<>();
        hits.put("count_twitter_all", count_twitter_all.get());
        hits.put("count_twitter_new", count_twitter_new.get());
        hits.put("count_backend", count_backend.get());
        hits.put("cache_hits", cache_hits.get());
        post.recordEvent("hits", hits);
        DAO.log(request.getServletPath() + "?" + request.getQueryString() + " -> " + tl.size()
                + " records returned, " + count_twitter_new.get() + " new");
        post.finalize();
    } catch (Throwable e) {
        Log.getLog().warn(e.getMessage(), e);
        //e.printStackTrace();
    }
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

private boolean doGet(HttpServletRequest request, HttpServletResponse response, PrintWriter writer,
        Component component) throws AxisFault, ClassException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    String path = request.getServletPath();
    String queryString = request.getQueryString();

    AxisEngine engine = getEngine();/*from   w  w  w.ja  va 2s.c o  m*/

    Iterator i = this.transport.getOptions().keySet().iterator();

    if (queryString == null) {
        return false;
    }

    String servletURI = request.getContextPath() + path;
    String reqURI = request.getRequestURI();

    // service name
    String serviceName;
    if (servletURI.length() + 1 < reqURI.length()) {
        serviceName = reqURI.substring(servletURI.length() + 1);
    } else {
        serviceName = "";
    }

    while (i.hasNext()) {
        String queryHandler = (String) i.next();
        if (queryHandler.startsWith("qs.")) {
            // Only attempt to match the query string with transport
            // parameters prefixed with "qs:".

            String handlerName = queryHandler.substring(queryHandler.indexOf(".") + 1).toLowerCase();
            // Determine the name of the plugin to invoke by using all text
            // in the query string up to the first occurence of &, =, or the
            // whole string if neither is present.

            int length = 0;
            boolean firstParamFound = false;

            while (firstParamFound == false && length < queryString.length()) {
                char ch = queryString.charAt(length++);

                if (ch == '&' || ch == '=') {
                    firstParamFound = true;

                    --length;
                }
            }

            if (length < queryString.length()) {
                queryString = queryString.substring(0, length);
            }

            if (queryString.toLowerCase().equals(handlerName) == true) {
                // Query string matches a defined query string handler name.

                // If the defined class name for this query string handler is blank,
                // just return (the handler is "turned off" in effect).

                if (this.transport.getOption(queryHandler).equals("")) {
                    return false;
                }

                // Attempt to dynamically load the query string handler
                // and its "invoke" method.

                MessageContext msgContext = createMessageContext(engine, request, response, component);
                Class plugin = ClassUtil.loadClass((String) this.transport.getOption(queryHandler));
                Method pluginMethod = plugin.getDeclaredMethod("invoke", new Class[] { msgContext.getClass() });

                msgContext.setProperty(MessageContext.TRANS_URL,
                        HttpUtils.getRequestURL(request).toString().toLowerCase());
                //msgContext.setProperty(MessageContext.TRANS_URL, "http://DefaultNamespace");
                msgContext.setProperty(HTTPConstants.PLUGIN_SERVICE_NAME, serviceName);
                msgContext.setProperty(HTTPConstants.PLUGIN_NAME, handlerName);
                msgContext.setProperty(HTTPConstants.PLUGIN_IS_DEVELOPMENT, Caster.toBoolean(isDevelopment));
                msgContext.setProperty(HTTPConstants.PLUGIN_ENABLE_LIST, Boolean.FALSE);
                msgContext.setProperty(HTTPConstants.PLUGIN_ENGINE, engine);
                msgContext.setProperty(HTTPConstants.PLUGIN_WRITER, writer);
                msgContext.setProperty(HTTPConstants.PLUGIN_LOG, log);
                msgContext.setProperty(HTTPConstants.PLUGIN_EXCEPTION_LOG, exceptionLog);

                // Invoke the plugin.
                pluginMethod.invoke(ClassUtil.loadInstance(plugin), new Object[] { msgContext });
                writer.close();

                return true;

            }
        }
    }

    return false;
}

From source file:edu.isi.wings.portal.classes.Config.java

private void initializeUserConfig(HttpServletRequest request) {
    // Set userid, domainid, viewerId
    this.userId = request.getParameter("userid");
    this.domainId = request.getParameter("domainid");
    this.viewerId = request.getRemoteUser();

    // Set default script values
    this.scriptPath = this.contextRootPath + request.getServletPath();
    this.scriptArguments = new String[] {};

    String path = request.getPathInfo();
    if (path == null)
        path = "/";
    this.scriptArguments = path.split("/");
    if (this.scriptArguments.length > 0)
        this.scriptArguments = (String[]) ArrayUtils.remove(this.scriptArguments, 0);

    if (this.domainId != null) {
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.getDomainId();
        this.scriptPath = this.userDomainUrl + request.getServletPath();
    } else if (this.userId != null) {
        this.scriptPath = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + request.getServletPath();
    }// w  w w .j  a va 2  s.  co  m

    this.sessionId = request.getSession().getId();

    if (this.viewerId == null)
        return;

    // If no userId specified, then set the viewer as the user
    if (this.userId == null)
        this.userId = this.viewerId;

    if (!this.checkUser(null))
        return;

    this.exportUserUrl = serverUrl + contextRootPath + exportServletPath + "/" + usersRelativeDir + "/"
            + userId;
    this.userPath = contextRootPath + "/" + usersRelativeDir + "/" + userId;
    this.userDir = storageDirectory + File.separator + usersRelativeDir + File.separator + userId;

    // Create userDir (if it doesn't exist)
    File uf = new File(this.userDir);
    if (!uf.exists() && !uf.mkdirs())
        System.err.println("Cannot create user directory : " + uf.getAbsolutePath());

    // Get domain and user list
    DomainController dc = new DomainController(1, this);
    this.domainsList = dc.getReadableDomainsList();
    this.usersList = this.userapi.getUsersList();

    // Get user's selected domain
    this.domain = dc.getUserDomain();

    // If the domain isn't a part of the readable domain list, 
    // then choose the first one
    if (this.domain == null || !domainsList.contains(this.domain.getDomainName())) {
        if (domainsList.size() > 0)
            this.domain = dc.getDomain(domainsList.get(0));
        else
            this.domain = null;
    }

    if (this.domain != null) {
        this.userDomainUrl = this.contextRootPath + "/" + this.getUsersRelativeDir() + "/" + this.getUserId()
                + "/" + this.domain.getDomainName();
        this.domainId = this.domain.getDomainName();
    }
}

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

/**
 * Receives an application for a new organization and root-user
 * /*  w  w  w .  j a va  2 s. c  o  m*/
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/apply", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
public ResponseEntity<Organization> applyOrganization(HttpServletRequest request,
        @RequestBody @Valid Organization input, BindingResult bindingResult) throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    // Make sure all mrn are lowercase
    input.setMrn(input.getMrn().trim().toLowerCase());
    input.setApproved(false);
    // If no federation type is set we for now default to "test-idp"
    if (input.getFederationType() == null || input.getFederationType().isEmpty()) {
        input.setFederationType("test-idp");
    }
    Organization newOrg;
    try {
        newOrg = this.organizationService.save(input);
    } catch (DataIntegrityViolationException e) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, e.getRootCause().getMessage(),
                request.getServletPath());
    }
    // Send email to organization saying that the application is awaiting approval
    emailUtil.sendOrgAwaitingApprovalEmail(newOrg.getEmail(), newOrg.getName());
    // Send email to admin saying that an Organization is awaiting approval
    emailUtil.sendAdminOrgAwaitingApprovalEmail(newOrg.getName());
    return new ResponseEntity<>(newOrg, HttpStatus.OK);
}

From source file:com.iorga.webappwatcher.RequestLogFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final String requestURI = httpRequest.getRequestURI();

    final boolean matches = PatternUtils.matches(requestURI, requestNameIncludes, requestNameExcludes);
    final RequestEventLog logRequest;
    if (matches) {
        // log previous excluded requests
        logNbExcludedRequests();//from  w  ww.java  2 s. com
        // create a log request
        logRequest = createRequestEventLog(httpRequest, requestURI);
    } else {
        logRequest = null;
        incrementNbExcludedRequests();
    }

    try {
        if (httpRequest.getServletPath().startsWith("/" + cmdRequestName)) {
            // this is a command request, let's handle it
            handleFilterCommandRequest(requestURI, httpRequest, response);
        } else {
            chain.doFilter(request, response);
        }
    } catch (final Throwable t) {
        if (matches) {
            try {
                logRequest.setThrowableStackTraceAsString(Throwables.getStackTraceAsString(t));
            } catch (final Throwable t2) {
                logRequest.setThrowableStackTraceAsString("Exception in thread \""
                        + Thread.currentThread().getName() + "\" " + t.getClass().getName()
                        + " couldn't be got as string due to " + t2.getClass().getName());
            }
        }
        if (t instanceof IOException) {
            throw (IOException) t;
        }
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        throw (RuntimeException) t;
    } finally {
        if (matches) {
            logRequest.setAfterProcessedDate(new Date());
            EventLogManager.getInstance().fire(logRequest);
        }
    }
}

From source file:com.xmarts.ringingPayroll.rpf_process.Upload.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (log4j.isDebugEnabled())
        log4j.debug("Posted: doPost");

    VariablesSecureApp vars = new VariablesSecureApp(request);

    if (vars.commandIn("DEFAULT")) {
        String strKey = vars.getGlobalVariable("inprpfConceptId", "Upload|RPF_Concept_ID");
        System.out.println("Clave Default:" + strKey);
        String strWindowId = vars.getGlobalVariable("inpwindowId", "Upload|windowId");
        String strTabId = vars.getGlobalVariable("inpTabId", "Upload|tabId");
        String strProcessId = vars.getGlobalVariable("inpProcessed", "Upload|processId", "");
        String strPath = vars.getGlobalVariable("inpPath", "Upload|path",
                strDireccion + request.getServletPath());
        String strPosted = null;/* w w w. j ava2s.c  o  m*/
        String strUploadd = "N";
        String strDocNo = vars.getRequestGlobalVariable("inpdocumentno", "Upload|docNo");
        String strWindowPath = Utility.getTabURL(this, strTabId, "E");
        if (strWindowPath.equals(""))
            strWindowPath = strDefaultServlet;

        if (strUploadd.equals("Y"))
            advisePopUp(request, response, Utility.messageBD(this, "ERROR", vars.getLanguage()),
                    Utility.messageBD(this, "CFDI_Upload", vars.getLanguage()));

        printPage(response, vars, strKey, strWindowId, strTabId, strProcessId, strPath, strPosted,
                strWindowPath, strDocNo);

    } else if (vars.commandIn("SAVE")) {

        String strKey = vars.getGlobalVariable("inprpfConceptId", "Upload|RPF_Concept_ID");
        String strWindowId = vars.getRequestGlobalVariable("inpwindowId", "Upload|windowId");
        String strTabId = vars.getRequestGlobalVariable("inpTabId", "Upload|tabId");
        String strProcessId = vars.getRequestGlobalVariable("inpProcessed", "Upload|processId");
        String strPath = vars.getRequestGlobalVariable("inpPath", "Upload|path");
        String strPosted = null;
        String strDocNo = vars.getRequestGlobalVariable("inpdocumentno", "Upload|docNo");
        String strWindowPath = Utility.getTabURL(this, strTabId, "E");
        String strFilePath = vars.getRequestGlobalVariable("inpFilePath", "Upload|FileName");

        if (strWindowPath.equals(""))
            strWindowPath = strDefaultServlet;

        OBError myMessage = process(response, vars, strKey, strWindowId, strTabId, strProcessId, strPath,
                strPosted, strWindowPath, strDocNo);
        vars.setMessage(strTabId, myMessage);
        printPageClosePopUp(response, vars, strWindowPath);

    } else {
        advisePopUp(request, response, Utility.messageBD(this, "ERROR", vars.getLanguage()),
                Utility.messageBD(this, "ERROR", vars.getLanguage()));
    }
}

From source file:ru.org.linux.exception.ExceptionResolver.java

/**
 * ? E-mail ?./*from   w  ww . ja va 2s . c o  m*/
 *
 * @param request    ?  web-
 * @param exception ?
 * @return , ? ??? ? ?
 */
private String sendEmailToAdmin(HttpServletRequest request, Exception exception) {
    InternetAddress mail;
    String adminEmailAddress = configuration.getAdminEmailAddress();

    try {
        mail = new InternetAddress(adminEmailAddress, true);
    } catch (AddressException e) {
        return EMAIL_NOT_SENT + " ? e-mail ?: " + adminEmailAddress;
    }
    StringBuilder text = new StringBuilder();

    if (exception.getMessage() == null) {
        text.append(exception.getClass().getName());
    } else {
        text.append(exception.getMessage());
    }
    text.append("\n\n");

    Template tmpl = Template.getTemplate(request);
    //    text.append("Main URL: ").append(tmpl.getMainUrl()).append(request.getAttribute("javax.servlet.error.request_uri"));
    String mainUrl = "<unknown>";

    mainUrl = configuration.getMainUrl();

    text.append("Main URL: ").append(mainUrl).append(request.getServletPath());

    if (request.getQueryString() != null) {
        text.append('?').append(request.getQueryString()).append('\n');
    }
    text.append('\n');

    text.append("IP: " + request.getRemoteAddr() + '\n');

    text.append(" Headers: ");
    Enumeration enu = request.getHeaderNames();
    while (enu.hasMoreElements()) {
        String paramName = (String) enu.nextElement();
        text.append("\n         ").append(paramName).append(": ").append(request.getHeader(paramName));
    }
    text.append("\n\n");

    StringWriter exceptionStackTrace = new StringWriter();
    exception.printStackTrace(new PrintWriter(exceptionStackTrace));
    text.append(exceptionStackTrace.toString());

    Properties props = new Properties();
    props.put("mail.smtp.host", "localhost");
    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage emailMessage = new MimeMessage(mailSession);
    try {
        emailMessage.setFrom(new InternetAddress("no-reply@linux.org.ru"));
        emailMessage.addRecipient(Message.RecipientType.TO, mail);
        emailMessage.setSubject("Linux.org.ru: " + exception.getClass());
        emailMessage.setSentDate(new Date());
        emailMessage.setText(text.toString(), "UTF-8");
    } catch (Exception e) {
        logger.error("An error occured while creating e-mail!", e);
        return EMAIL_NOT_SENT;
    }
    try {
        Transport.send(emailMessage);
        return EMAIL_SENT;
    } catch (Exception e) {
        return EMAIL_NOT_SENT;
    }
}

From source file:com.concursive.connect.web.controller.hooks.SecurityHook.java

/**
 * Checks to see if a User session object exists, if not then the security
 * check fails.//from w  w  w.j a v  a2  s.com
 *
 * @param servlet  Description of the Parameter
 * @param request  Description of the Parameter
 * @param response Description of the Parameter
 * @return Description of the Return Value
 */
public String beginRequest(Servlet servlet, HttpServletRequest request, HttpServletResponse response) {
    LOG.debug("Security request made");
    ServletConfig config = servlet.getServletConfig();
    ServletContext context = config.getServletContext();
    // Application wide preferences
    ApplicationPrefs prefs = (ApplicationPrefs) context.getAttribute(Constants.APPLICATION_PREFS);
    // Get the intended action, if going to the login module, then let it proceed
    String s = request.getServletPath();
    int slash = s.lastIndexOf("/");
    s = s.substring(slash + 1);
    // If not setup then go to setup
    if (!s.startsWith("Setup") && !prefs.isConfigured()) {
        return "NotSetupError";
    }
    // External calls
    if (s.startsWith("Service")) {
        return null;
    }
    // Set the layout relevant to this request
    if ("text".equals(request.getParameter("out")) || "text".equals(request.getAttribute("out"))) {
        // do not use a layout, send the raw output
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_POPUP))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else if ("true".equals(request.getParameter(Constants.REQUEST_PARAM_STYLE))) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
    } else {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, context.getAttribute(Constants.REQUEST_TEMPLATE));
    }
    // If going to Setup then allow
    if (s.startsWith("Setup")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // If going to Upgrade then allow
    if (s.startsWith("Upgrade")) {
        request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layout1.jsp");
        return null;
    }
    // Detect mobile users and mobile formatting
    //    ClientType clientType = (ClientType) request.getSession().getAttribute(Constants.SESSION_CLIENT_TYPE);
    // @todo introduce when mobile is implemented
    //    if (clientType.getMobile()) {
    //      request.setAttribute(Constants.REQUEST_PAGE_LAYOUT, "/layoutMobile.jsp");
    //    }

    // URL forwarding for MVC requests (*.do, etc.)
    String requestedPath = (String) request.getAttribute("requestedURL");
    if (requestedPath == null && "GET".equals(request.getMethod())
            && request.getParameter("redirectTo") == null) {
        // Save the requestURI to be used downstream
        String contextPath = request.getContextPath();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        requestedPath = uri.substring(contextPath.length()) + (queryString == null ? "" : "?" + queryString);
        LOG.debug("Requested path: " + requestedPath);
        request.setAttribute("requestedURL", requestedPath);

        // It's important the user is using the correct URL for accessing content;
        // The portal has it's own redirect scheme, this is a general catch all
        if (!s.startsWith("Portal") && !uri.contains(".shtml") && prefs.has(ApplicationPrefs.WEB_DOMAIN_NAME)) {
            // Check to see if an old domain name is used
            PortalBean bean = new PortalBean(request);
            String expectedDomainName = prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME);
            if (expectedDomainName != null && requestedPath != null && !"127.0.0.1".equals(bean.getServerName())
                    && !"127.0.0.1".equals(expectedDomainName) && !"localhost".equals(bean.getServerName())
                    && !"localhost".equals(expectedDomainName)
                    && !bean.getServerName().equals(expectedDomainName)
                    && !bean.getServerName().startsWith("10.") && !bean.getServerName().startsWith("172.")
                    && !bean.getServerName().startsWith("192.")) {
                if (uri != null && !uri.substring(1).equals(prefs.get("PORTAL.INDEX"))) {
                    String newUrl = URLFactory.createURL(prefs.getPrefs()) + requestedPath;
                    request.setAttribute("redirectTo", newUrl);
                    LOG.debug("redirectTo: " + newUrl);
                    request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                    return "Redirect301";
                }
            }
        }
    }

    // Version check
    if (!s.startsWith("Login") && ApplicationVersion.isOutOfDate(prefs)) {
        return "UpgradeCheck";
    }
    // Get the user object from the Session Validation...
    if (sessionValidator == null) {
        sessionValidator = SessionValidatorFactory.getInstance()
                .getSessionValidator(servlet.getServletConfig().getServletContext(), request);
        LOG.debug("Found sessionValidator? " + (sessionValidator != null));
    }
    // Check cookie for user's previous location info
    SearchBean searchBean = (SearchBean) request.getSession().getAttribute(Constants.SESSION_SEARCH_BEAN);
    if (searchBean == null) {
        String searchLocation = CookieUtils.getCookieValue(request, Constants.COOKIE_USER_SEARCH_LOCATION);
        if (searchLocation != null) {
            LOG.debug("Setting search location from cookie: " + searchLocation);
            searchBean = new SearchBean();
            searchBean.setLocation(searchLocation);
            request.getSession().setAttribute(Constants.SESSION_SEARCH_BEAN, searchBean);
        }
    }
    // Continue with session creation...
    User userSession = sessionValidator.validateSession(context, request, response);
    ConnectionElement ceSession = (ConnectionElement) request.getSession()
            .getAttribute(Constants.SESSION_CONNECTION_ELEMENT);
    // The user is going to the portal so get them guest credentials if they need them
    if ("true".equals(prefs.get("PORTAL")) || s.startsWith("Register") || s.startsWith("ResetPassword")
            || s.startsWith("LoginAccept") || s.startsWith("LoginReject") || s.startsWith("Search")
            || s.startsWith("ContactUs")) {
        if (userSession == null || ceSession == null) {
            // Allow portal mode to create a default session with guest capabilities
            userSession = UserUtils.createGuestUser();
            request.getSession().setAttribute(Constants.SESSION_USER, userSession);
            // Give them a connection element
            ceSession = new ConnectionElement();
            ceSession.setDriver(prefs.get("SITE.DRIVER"));
            ceSession.setUrl(prefs.get("SITE.URL"));
            ceSession.setUsername(prefs.get("SITE.USER"));
            ceSession.setPassword(prefs.get("SITE.PASSWORD"));
            request.getSession().setAttribute(Constants.SESSION_CONNECTION_ELEMENT, ceSession);
        }
        // Make sure SSL is being used for this connection
        if (userSession.getId() > 0 && "true".equals(prefs.get("SSL"))
                && !"https".equals(request.getScheme())) {
            LOG.info("Redirecting to..." + requestedPath);
            request.setAttribute("redirectTo",
                    "https://" + request.getServerName() + request.getContextPath() + requestedPath);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "Redirect301";
        }
        // Generate global items
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // Load the project languages
                WebSiteLanguageList webSiteLanguageList = new WebSiteLanguageList();
                webSiteLanguageList.setEnabled(Constants.TRUE);
                webSiteLanguageList.buildList(db);
                // If an admin of a language, enable it...
                webSiteLanguageList.add(userSession.getWebSiteLanguageList());
                request.setAttribute("webSiteLanguageList", webSiteLanguageList);

                // Load the menu list
                ProjectList menu = new ProjectList();
                PagedListInfo menuListInfo = new PagedListInfo();
                menuListInfo.setColumnToSortBy("p.portal_default desc, p.level asc, p.title asc");
                menuListInfo.setItemsPerPage(-1);
                menu.setPagedListInfo(menuListInfo);
                menu.setIncludeGuestProjects(false);
                menu.setPortalState(Constants.TRUE);
                menu.setOpenProjectsOnly(true);
                menu.setApprovedOnly(true);
                menu.setBuildLink(true);
                menu.setLanguageId(webSiteLanguageList.getLanguageId(request));
                menu.buildList(db);
                request.setAttribute("menuList", menu);

                // Load the main profile to use throughout
                Project mainProfile = ProjectUtils.loadProject(prefs.get("MAIN_PROFILE"));
                request.setAttribute(Constants.REQUEST_MAIN_PROFILE, mainProfile);

                // Load the project categories for search and tab menus
                ProjectCategoryList categoryList = new ProjectCategoryList();
                categoryList.setEnabled(Constants.TRUE);
                categoryList.setTopLevelOnly(true);
                categoryList.buildList(db);
                request.setAttribute(Constants.REQUEST_TAB_CATEGORY_LIST, categoryList);

                // Determine the tab that needs to be highlighted
                int chosenTabId = -1;
                if (requestedPath != null) {
                    String chosenCategory = null;
                    String chosenTab = null;
                    if (requestedPath.length() > 0) {
                        chosenTab = requestedPath.substring(1);
                    }
                    LOG.debug("chosenTab? " + chosenTab);
                    if (chosenTab == null || "".equals(chosenTab)) {
                        LOG.debug("Setting tab to Home");
                        chosenTab = "home.shtml";
                    } else {
                        boolean foundChosenTab = false;
                        for (ProjectCategory projectCategory : categoryList) {
                            String categoryName = projectCategory.getDescription();
                            String normalizedCategoryTab = projectCategory.getNormalizedCategoryName()
                                    .concat(".shtml");
                            if (chosenTab.startsWith(normalizedCategoryTab)) {
                                foundChosenTab = true;
                                chosenCategory = categoryName;
                                chosenTabId = projectCategory.getId();
                                LOG.debug("found: " + chosenCategory);
                            }
                        }
                        if (!foundChosenTab) {
                            LOG.debug("No tab to highlight");
                            chosenTab = "none";
                        }
                    }
                    request.setAttribute("chosenTab", chosenTab);
                    request.setAttribute("chosenCategory", chosenCategory);
                }

                // Go through the tabs and remove the ones the user shouldn't see, also check permission
                if (!userSession.isLoggedIn()) {
                    boolean allowed = true;
                    Iterator i = categoryList.iterator();
                    while (i.hasNext()) {
                        ProjectCategory projectCategory = (ProjectCategory) i.next();
                        if (projectCategory.getSensitive()) {
                            if (chosenTabId == projectCategory.getId()) {
                                allowed = false;
                            }
                            i.remove();
                        }
                    }
                    if (!allowed) {
                        // Redirect to the login, perhaps the page would exist then
                        String newUrl = URLFactory.createURL(prefs.getPrefs()) + "/login?redirectTo="
                                + requestedPath;
                        request.setAttribute("redirectTo", newUrl);
                        LOG.debug("redirectTo: " + newUrl);
                        request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
                        return "Redirect301";
                    }
                }

                // Category drop-down for search
                HtmlSelect thisSelect = categoryList.getHtmlSelect();
                thisSelect.addItem(-1, prefs.get("TITLE"), 0);
                request.setAttribute(Constants.REQUEST_MENU_CATEGORY_LIST, thisSelect);
            }
        } catch (Exception e) {
            LOG.error("Global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }

    // The user is not going to login, so verify login
    if (!s.startsWith("Login")) {
        if (userSession == null || ceSession == null) {
            // boot them off now
            LOG.debug("Security failed.");
            LoginBean failedSession = new LoginBean();
            failedSession.addError("actionError", "* Please login, your session has expired");
            failedSession.checkURL(request);
            request.setAttribute("LoginBean", failedSession);
            request.removeAttribute(Constants.REQUEST_PAGE_LAYOUT);
            return "SecurityCheck";
        } else {
            // The user should have a valid login now, so let them proceed
            LOG.debug("Security passed: " + userSession.getId() + " (" + userSession.getUsername() + ")");
        }
    }
    // Generate user's global items
    if (userSession != null && userSession.getId() > 0) {
        Connection db = null;
        try {
            db = getConnection(context, request);
            // TODO: Implement cache since every hit needs this list
            if (db != null) {
                // A map for global alerts
                ArrayList<String> alerts = new ArrayList<String>();
                request.setAttribute(Constants.REQUEST_GLOBAL_ALERTS, alerts);

                // Check to see if the application is configured...
                if (userSession.getAccessAdmin()) {
                    String url = URLFactory.createURL(prefs.getPrefs());
                    if (url == null) {
                        alerts.add(
                                "The application configuration requires that the URL properties are updated.  Store <strong>"
                                        + RequestUtils.getAbsoluteServerUrl(request) + "</strong>? <a href=\""
                                        + RequestUtils.getAbsoluteServerUrl(request)
                                        + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    } else if (!url.equals(RequestUtils.getAbsoluteServerUrl(request))) {
                        alerts.add("There is a configuration mismatch -- expected: <strong>"
                                + RequestUtils.getAbsoluteServerUrl(request)
                                + "</strong> but the configuration has <strong><a href=\"" + url + "\">" + url
                                + "</a></strong> <a href=\"" + RequestUtils.getAbsoluteServerUrl(request)
                                + "/AdminUsage.do?command=StoreURL\">Save Changes</a>");
                    }
                }

                // Check the # of invitations
                int invitationCount = InvitationList.queryCount(db, userSession.getId(),
                        userSession.getProfileProjectId());
                request.setAttribute(Constants.REQUEST_INVITATION_COUNT, String.valueOf(invitationCount));

                // Check the # of private messages
                int newMailCount = PrivateMessageList.queryUnreadCountForUser(db, userSession.getId());
                request.setAttribute(Constants.REQUEST_PRIVATE_MESSAGE_COUNT, String.valueOf(newMailCount));

                // NOTE: removed because not currently used
                // Check the number of what's new
                //          int whatsNewCount = ProjectUtils.queryWhatsNewCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_NEW_COUNT, String.valueOf(whatsNewCount));
                // Check the number of assignments
                //          int whatsAssignedCount = ProjectUtils.queryWhatsAssignedCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_WHATS_ASSIGNED_COUNT, String.valueOf(whatsAssignedCount));
                //          int projectCount = ProjectUtils.queryMyProjectCount(db, userSession.getId());
                //          request.setAttribute(Constants.REQUEST_MY_PROJECT_COUNT, String.valueOf(projectCount));
            }
        } catch (Exception e) {
            LOG.error("User's global items error", e);
        } finally {
            this.freeConnection(context, db);
        }
    }
    return null;
}

From source file:com.konakart.actions.BaseAction.java

/**
 * Returns the base redirect URL used in AJAX calls
 * //  w  w  w  .ja  v  a2  s.  c o  m
 * @param request
 *            The HttpServletRequest
 * 
 * @return Returns the base redirect URL used in AJAX calls
 */
public String getRedirectURL(HttpServletRequest request) {
    String redirectURL = request.getRequestURI().toString();
    String servletPath = request.getServletPath();
    redirectURL = redirectURL.substring(0, redirectURL.length() - servletPath.length());
    return redirectURL;
}