Example usage for javax.servlet.http HttpServletRequest getRemoteHost

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

Introduction

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

Prototype

public String getRemoteHost();

Source Link

Document

Returns the fully qualified name of the client or the last proxy that sent the request.

Usage

From source file:siddur.solidtrust.site.APIController.java

@RequestMapping(value = "/fault")
public @ResponseBody Object fault(@RequestParam("id") String id,
        @RequestParam(value = "rate", defaultValue = "false", required = false) boolean rate,
        HttpServletRequest request) {
    AccessItem ai = new AccessItem();
    ai.setIp(request.getRemoteHost());
    ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
    ai.setService(Product.FAULT.getId());
    ai.setRequest(id);//  w w  w.j  ava 2  s  .  co  m

    AzureCar entity = null;
    if (!StringUtils.isEmpty(id)) {
        try {
            entity = azureService.findByLicensePlate(id.trim());
        } catch (Exception e) {
            ai.setStatus(-1);
            log4j.error(e.getMessage(), e);
            ai.setResponse(e.getMessage());
        }
    }

    Fault fault = null;
    if (entity != null) {
        Fault f = faultService.entity2Fault(entity);
        List<Object[]> list = null;
        try {
            list = faultService.search(1, f, "2");
        } catch (Exception e) {
            log4j.error(e.getMessage(), e);
            ai.setStatus(-1);
            ai.setResponse(e.getMessage());
        }
        fault = (list == null || list.isEmpty()) ? null : (Fault) list.get(0)[1];
        boolean needOldVersion = false;
        boolean needMerge = false;

        if (fault != null) {
            ai.setResponse(fault.getId() + "");
            log4j.info("find fault with id:" + ai.getResponse());
            if (StringUtils.isEmpty(fault.getChassis())) {
                needOldVersion = true;
                needMerge = true;
            }
        } else {
            needOldVersion = true;
            needMerge = false;
        }
        if (needOldVersion) {
            try {
                list = faultService.search(1, f, "1");
            } catch (Exception e) {
                log4j.error(e.getMessage(), e);
                ai.setStatus(-1);
                ai.setResponse(e.getMessage());
            }
            Fault old = (list == null || list.isEmpty()) ? null : (Fault) list.get(0)[1];
            if (old != null) {
                if (needMerge) {
                    fault.merge(old);
                    ai.setResponse(ai.getResponse() + "," + old.getId());
                } else {
                    fault = old;
                    ai.setResponse(fault.getId() + "");
                }

                log4j.info("find fault with ids:" + ai.getResponse());
            }
        }

        if (fault == null) {
            fault = f;
        }
    }

    //clean up
    if (fault != null) {
        fault.format();
        if (!rate) {
            fault.setBodywork(null);
            fault.setBrakeSystem(null);
            fault.setChassis(null);
            fault.setElectrics(null);
            fault.setEngine(null);
            fault.setFaultIndex(null);
        } else {
            if (fault.getBodywork() == null) {
                fault.setBodywork("");
            }
            if (fault.getBrakeSystem() == null) {
                fault.setBrakeSystem("");
            }
            if (fault.getChassis() == null) {
                fault.setChassis("");
            }
            if (fault.getElectrics() == null) {
                fault.setElectrics("");
            }
            if (fault.getEngine() == null) {
                fault.setEngine("");
            }
            if (fault.getFaultIndex() == null) {
                fault.setFaultIndex("");
            }
        }
    } else {
        ai.setStatus(0);
    }
    free.save(ai);
    return fault;
}

From source file:gsn.http.OneShotQueryHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());

    String vsName = request.getParameter("name");
    String vsCondition = request.getParameter("condition");

    if (vsCondition == null || vsCondition.trim().length() == 0)
        vsCondition = " ";
    else/*from w w  w. ja v  a 2 s.  c  om*/
        vsCondition = " where " + vsCondition;
    String vsFields = request.getParameter("fields");
    if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*"))
        vsFields = "*";
    else
        vsFields += " , pk, timed";
    String windowSize = request.getParameter("window");
    if (windowSize == null || windowSize.trim().length() == 0)
        windowSize = "1";
    StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition
            + " order by timed DESC limit " + windowSize + " offset 0");
    DataEnumerator result;
    try {
        result = Main.getStorage(vsName).executeQuery(query, true);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query + " from " + request.getRemoteAddr() + "- "
                + request.getRemoteHost() + ": " + e.getMessage());
        return;
    }

    Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs();
    HashMap<String, String> fieldToUnitMap = new HashMap<String, String>();
    while (vsIterator.hasNext()) {
        VSensorConfig sensorConfig = vsIterator.next();
        if (vsName.equalsIgnoreCase(sensorConfig.getName())) {
            DataField[] dataFieldArray = sensorConfig.getOutputStructure();
            for (DataField df : dataFieldArray) {
                String unit = df.getUnit();
                if (unit == null || unit.trim().length() == 0)
                    unit = "";

                fieldToUnitMap.put(df.getName().toLowerCase(), unit);
            }
            break;
        }
    }

    StringBuilder sb = new StringBuilder("<result>\n");
    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();
        sb.append("<stream-element>\n");
        sb.append("<field name=\"time\" unit=\"\">").append(sdf.format(new Date(se.getTimeStamp())))
                .append("</field>\n");
        for (int i = 0; i < se.getFieldNames().length; i++) {
            sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\"");
            sb.append(" unit=\"").append(fieldToUnitMap.get(se.getFieldNames()[i].toLowerCase()))
                    .append("\" >");
            if (se.getData()[i] != null)
                if (se.getFieldTypes()[i] == DataTypes.BINARY)
                    sb.append(se.getData()[i].toString());
                else
                    sb.append(StringEscapeUtils.escapeXml(se.getData()[i].toString()));
            sb.append("</field>\n");
        }

        sb.append("</stream-element>\n");
    }
    result.close();
    sb.append("</result>");

    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}

From source file:gsn.http.OneShotQueryWithAddressingHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());

    String vsName = request.getParameter("name");
    String vsCondition = request.getParameter("condition");
    if (vsCondition == null || vsCondition.trim().length() == 0)
        vsCondition = " ";
    else/*from  ww w .  j av  a2 s.  c  o m*/
        vsCondition = " where " + vsCondition;
    String vsFields = request.getParameter("fields");
    if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*"))
        vsFields = "*";
    else
        vsFields += " , pk, timed";
    String windowSize = request.getParameter("window");
    if (windowSize == null || windowSize.trim().length() == 0)
        windowSize = "1";
    StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition
            + " order by timed DESC limit " + windowSize + " offset 0");
    DataEnumerator result;
    try {
        result = Main.getStorage(vsName).executeQuery(query, true);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query + " from " + request.getRemoteAddr() + "- "
                + request.getRemoteHost() + ": " + e.getMessage());
        return;
    }

    Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs();
    HashMap<String, String> fieldToUnitMap = new HashMap<String, String>();
    while (vsIterator.hasNext()) {
        VSensorConfig sensorConfig = vsIterator.next();
        if (vsName.equalsIgnoreCase(sensorConfig.getName())) {
            DataField[] dataFieldArray = sensorConfig.getOutputStructure();
            for (DataField df : dataFieldArray) {
                String unit = df.getUnit();
                if (unit == null || unit.trim().length() == 0)
                    unit = "";

                fieldToUnitMap.put(df.getName().toLowerCase(), unit);
            }
            break;
        }
    }

    StringBuilder sb = new StringBuilder("<result>\n");
    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();
        sb.append("<stream-element>\n");
        sb.append("<field name=\"time\" unit=\"\">").append(sdf.format(new Date(se.getTimeStamp())))
                .append("</field>\n");
        for (int i = 0; i < se.getFieldNames().length; i++) {
            sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\"");
            sb.append(" unit=\"").append(fieldToUnitMap.get(se.getFieldNames()[i].toLowerCase()))
                    .append("\" >");
            if (se.getFieldTypes()[i] == DataTypes.BINARY)
                sb.append(se.getData()[i].toString()).append("</field>\n");
            else
                sb.append(StringEscapeUtils.escapeXml(se.getData()[i].toString())).append("</field>\n");
        }
        VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
        logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.")
                .toString());
        //StringBuilder statement = new StringBuilder( "<virtual-sensor name=\"" ).append( vsName ).append( "\" last-modified=\"" ).append( new File( sensorConfig.getFileName( ) ).lastModified( ) ).append( "\">\n" );
        for (KeyValue df : sensorConfig.getAddressing())
            sb.append("<field name=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString()))
                    .append("\">").append(StringEscapeUtils.escapeXml(df.getValue().toString()))
                    .append("</field>\n");
        sb.append("</stream-element>\n");
    }
    result.close();
    sb.append("</result>");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}

From source file:siddur.solidtrust.site.APIController.java

@RequestMapping(value = "/mileage")
public @ResponseBody Object mileage(@RequestParam("key") String key,
        @RequestParam(value = "type", required = false, defaultValue = "0") int type,
        HttpServletRequest request) {
    AccessItem ai = new AccessItem();
    ai.setIp(request.getRemoteHost());
    ai.setUsername(request.getAttribute(SolidtrustConstants.CLIENT_ID) + "");
    ai.setService(Product.MILE_AGE.getId());
    ai.setRequest(key);//from  w w  w  .ja  v  a  2 s  .c  om

    int i = 0;
    key = key.replace("-", "");
    Map<String, Object> result = new HashMap<String, Object>();
    if (key.length() == 6) {
        if (type == 0) { //both autorola and marktplaats
            String jpql = "from Autorola a where a.licensePlate='" + key + "'";
            List<Autorola> list = em.createQuery(jpql, Autorola.class).getResultList();
            for (Autorola a : list) {
                if (i == 0) {
                    result.put("brand", a.getBrand());
                    result.put("model", a.getModel());
                    result.put("licensePlate", a.getLicensePlate());
                    result.put("mileage", a.getMileAge());
                    result.put("source", "AR");
                    result.put("date", a.getScrapedAt());
                } else {
                    result.put("mileage" + i, a.getMileAge());
                    result.put("source" + i, "AR");
                    result.put("date" + i, a.getScrapedAt());
                }
                i++;
            }
            jpql = "from NewMarktplaats m where m.licensePlate='" + key + "'";
            List<NewMarktplaats> list1 = em.createQuery(jpql, NewMarktplaats.class).getResultList();
            for (NewMarktplaats a : list1) {
                if (i == 0) {
                    result.put("brand", a.getBrand());
                    result.put("model", a.getModel());
                    result.put("licensePlate", a.getLicensePlate());
                    result.put("mileage", a.getMileage());
                    result.put("source", "MP");
                    result.put("date", a.getDateScraped());
                } else {
                    result.put("mileage" + i, a.getMileage());
                    result.put("source" + i, "MP");
                    result.put("date" + i, a.getDateScraped());
                }
                i++;
            }
        } else if (type == 1) { //Autorola
            String jpql = "from Autorola a where a.licensePlate='" + key + "'";
            List<Autorola> list = em.createQuery(jpql, Autorola.class).getResultList();
            for (Autorola a : list) {
                if (i == 0) {
                    result.put("brand", a.getBrand());
                    result.put("model", a.getModel());
                    result.put("licensePlate", a.getLicensePlate());
                    result.put("mileage", a.getMileAge());
                    result.put("source", "AR");
                    result.put("date", a.getScrapedAt());
                } else {
                    result.put("mileage" + i, a.getMileAge());
                    result.put("source" + i, "AR");
                    result.put("date" + i, a.getScrapedAt());
                }
                i++;
            }
        } else if (type == 2) {//NewMarktplaats
            String jpql = "from NewMarktplaats m where m.licensePlate='" + key + "'";
            List<NewMarktplaats> list1 = em.createQuery(jpql, NewMarktplaats.class).getResultList();
            for (NewMarktplaats a : list1) {
                if (i == 0) {
                    result.put("brand", a.getBrand());
                    result.put("model", a.getModel());
                    result.put("licensePlate", a.getLicensePlate());
                    result.put("mileage", a.getMileage());
                    result.put("source", "MP");
                    result.put("date", a.getDateScraped());
                } else {
                    result.put("mileage" + i, a.getMileage());
                    result.put("source" + i, "MP");
                    result.put("date" + i, a.getDateScraped());
                }
                i++;
            }
        }
    } else if (type == 0 || type == 1) {
        String jpql = "from Autorola a where a.chassisNumber='" + key + "'";
        List<Autorola> list = em.createQuery(jpql, Autorola.class).getResultList();
        for (Autorola a : list) {
            if (i == 0) {
                result.put("brand", a.getBrand());
                result.put("model", a.getModel());
                result.put("licensePlate", a.getLicensePlate());
                result.put("mileage", a.getMileAge());
                result.put("source", "AR");
                result.put("date", a.getScrapedAt());
            } else {
                result.put("mileage" + i, a.getMileAge());
                result.put("source" + i, "AR");
                result.put("date" + i, a.getScrapedAt());
            }
            i++;
        }
    }
    if (result.size() > 0) {
        ai.setResponse("brand=" + result.get("brand") + ",model=" + result.get("model") + ",mileage="
                + result.get("mileage") + ",licnese plate=" + result.get("licensePlate"));
        free.save(ai);
        return result;
    }
    String r = "Not found:" + key;
    ai.setResponse(r);
    ai.setStatus(0);
    free.save(ai);
    return r;
}

From source file:PrintCGI.java

/**
     * Prints CGI Environment Variables in a table
     * /*from   w  ww  . j a va 2 s  . c  o  m*/
     * @param request
     * @param response
     * @throws IOException
     */

    public void printCGIValues(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String headers = null;
        String htmlHeader = "<HTML><HEAD><TITLE> CGI Environment Variables </TITLE></HEAD><BODY>";
        String htmlFooter = "</BODY></HTML>";

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();

        out.println(htmlHeader);
        out.println("<TABLE ALIGN=CENTER BORDER=1>");
        out.println("<tr><th> CGI Variable </th><th> Value </th>");

        out.println("<tr><td align=center>Authentication Type</td>");
        out.println("<td align=center>" + request.getAuthType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type</td>");
        out.println("<td align=center>" + request.getContentType() + "</td></tr>");

        out.println("<tr><td align=center>Content Type Length</td>");
        out.println("<td align=center>" + request.getContentLength() + "</td></tr>");

        out.println("<tr><td align=center>Query String</td>");
        out.println("<td align=center>" + request.getMethod() + "</td></tr>");

        out.println("<tr><td align=center>IP Address</td>");
        out.println("<td align=center>" + request.getRemoteAddr() + "</td></tr>");

        out.println("<tr><td align=center>Host Name</td>");
        out.println("<td align=center>" + request.getRemoteHost() + "</td></tr>");

        out.println("<tr><td align=center>Request URL</td>");
        out.println("<td align=center>" + request.getRequestURI() + "</td></tr>");

        out.println("<tr><td align=center>Servlet Path</td>");
        out.println("<td align=center>" + request.getServletPath() + "</td></tr>");

        out.println("<tr><td align=center>Server's Name</td>");
        out.println("<td align=center>" + request.getServerName() + "</td></tr>");

        out.println("<tr><td align=center>Server's Port</td>");
        out.println("<td align=center>" + request.getServerPort() + "</td></tr>");

        out.println("</TABLE><BR>");
        out.println(htmlFooter);

    }

From source file:org.openiot.gsn.http.OneShotQueryHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());

    String vsName = request.getParameter("name");
    String vsCondition = request.getParameter("condition");
    if (vsCondition == null || vsCondition.trim().length() == 0)
        vsCondition = " ";
    else/* ww  w  .  java  2 s  .  co  m*/
        vsCondition = " where " + vsCondition;
    String vsFields = request.getParameter("fields");
    if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*"))
        vsFields = "*";
    else
        vsFields += " , pk, timed";
    String windowSize = request.getParameter("window");
    if (windowSize == null || windowSize.trim().length() == 0)
        windowSize = "1";
    StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition
            + " order by timed DESC limit " + windowSize + " offset 0");
    DataEnumerator result;
    try {
        result = Main.getStorage(vsName).executeQuery(query, true);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query);
        logger.error(e.getMessage(), e);
        logger.error("Query is from " + request.getRemoteAddr() + "- " + request.getRemoteHost());
        return;
    }
    StringBuilder sb = new StringBuilder("<result>\n");
    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();
        sb.append("<stream-element>\n");
        for (int i = 0; i < se.getFieldNames().length; i++) {
            sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\" >");
            if (se.getData()[i] != null)
                if (se.getFieldTypes()[i] == DataTypes.BINARY)
                    sb.append(se.getData()[i].toString());
                else
                    sb.append(StringEscapeUtils.escapeXml(se.getData()[i].toString()));
            sb.append("</field>\n");
        }
        sb.append("<field name=\"timed\" >").append(sdf.format(new Date(se.getTimeStamp())))
                .append("</field>\n");
        sb.append("</stream-element>\n");
    }
    result.close();
    sb.append("</result>");

    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}

From source file:org.n52.v3d.terrainserver.povraywts.WebTerrainServlet.java

private void logGetViewInfo(String pTmpName, VgElevationGrid pTerrain, T3dTimeList pTimeProt,
        HttpServletRequest pRequest, String pOutputInfo) {
    try {/*  ww  w . j a  v a  2 s. c  om*/
        PrintWriter lDat = new PrintWriter(new FileWriter(mWorkingDirectory + "/" + pTmpName + ".log"));

        // Berarbeitungszeit und weitere Infos protokollieren:
        lDat.println("REMOTE HOST: " + pRequest.getRemoteHost());
        lDat.println("REMOTE ADDRESS: " + pRequest.getRemoteAddr());
        //lDat.println("REMOTE USER: " + pRequest.getRemoteUser());
        lDat.println("QUERY STRING: " + pRequest.getQueryString());
        lDat.println("SESSION-ID: " + pRequest.getRequestedSessionId());
        lDat.println("BBOX: " + pTerrain.getGeometry().envelope());
        lDat.println("BBOX-SIZE: " + pTerrain.getGeometry().envelope().areaXY());
        lDat.println("CELLSIZE: " + ((GmSimple2dGridGeometry) pTerrain.getGeometry()).getDeltaX()); // quidist.
        lDat.println("OUTPUT FORMAT: " + pOutputInfo);
        lDat.println("PROCESSING_TIMES [msec]: ");
        String[] lTimeProtStr = pTimeProt.protocol();
        for (int i = 0; i < lTimeProtStr.length; i++)
            lDat.println(lTimeProtStr[i]);

        lDat.close();
    } catch (IOException e) {
        throw new T3dException(e.getMessage());
    }
}

From source file:com.adito.core.actions.AuthenticatedAction.java

public final ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // Setup mode
    boolean installMode = isInstallMode();
    if (installMode) {
        if ((getNavigationContext(mapping, form, request, response) & SessionInfo.SETUP_CONSOLE_CONTEXT) == 0) {
            return mapping.findForward("setup");
        } else {// w  w w  . j av  a2 s.c om
            /*
             * Make the mapping and form available, this helps with reusing
             * some JSP pages
             */
            request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
            request.setAttribute(Constants.REQ_ATTR_FORM, form);

            CoreUtil.checkNavigationContext(this, mapping, form, request, response);
            return onExecute(mapping, form, request, response);
        }
    }

    try {
        try {
            if (!SystemDatabaseFactory.getInstance().verifyIPAddress(request.getRemoteAddr())) {
                String link = null;
                log.error(request.getRemoteHost() + " is not authorized");
                if (log.isInfoEnabled())
                    log.info("Logging off, IP address verification failed.");
                if (LogonControllerFactory.getInstance().hasClientLoggedOn(request,
                        response) == LogonController.LOGGED_ON) {
                    LogonControllerFactory.getInstance().logoffSession(request, response);
                }

                if (link != null) {
                    return new ActionForward(link, true);
                } else {
                    // Do not direct to logon page for Ajax requests
                    if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                        return null;
                    }
                    return mapping.findForward("logon");
                }

            } else {

                int logonStatus = LogonControllerFactory.getInstance().hasClientLoggedOn(request, response);
                if (logonStatus == LogonController.INVALID_TICKET) {
                    ActionMessages msgs = new ActionMessages();
                    msgs.add(Globals.ERROR_KEY, new ActionMessage("login.invalidTicket"));
                    saveErrors(request, msgs);
                } else if (logonStatus == LogonController.LOGGED_ON) {

                    User currentUser = LogonControllerFactory.getInstance().getUser(request);

                    // Set the logon ticket / domain logon ticket again
                    LogonControllerFactory.getInstance().addCookies(new ServletRequestAdapter(request),
                            new ServletResponseAdapter(response),
                            (String) request.getSession().getAttribute(Constants.LOGON_TICKET),
                            getSessionInfo(request));

                    if (!LogonControllerFactory.getInstance().isAdministrator(getSessionInfo(request).getUser())
                            && requiresAdministrator) {
                        response.sendError(403, "You do not have permission to access this area");
                        return null;
                    } else {
                        /*
                         * Make the mapping and form available, this helps
                         * with reusing some JSP pages
                         */
                        request.setAttribute(Constants.REQ_ATTR_ACTION_MAPPING, mapping);
                        request.setAttribute(Constants.REQ_ATTR_FORM, form);

                        // Check for intercepts, but don't forward if the
                        // result of an Ajax action

                        ActionForward fwd = checkIntercept(mapping, request, response);
                        if (fwd != null) {
                            return fwd;
                        }

                        /*
                         * Make sure the current navigation context is
                         * correct. If not, then check the user can switch
                         * to the correct and switch it.
                         */
                        CoreUtil.checkNavigationContext(this, mapping, form, request, response);

                        // Check the user has the permissions to access this
                        // page
                        if (resourceType != null) {
                            if (!PolicyDatabaseFactory.getInstance().isPermitted(resourceType, permissions,
                                    currentUser, false)) {
                                throw new NoPermissionException("Action denied for current user");
                            }
                        }

                        if (request.getSession().getAttribute(Constants.SESSION_LOCKED) == null
                                || isIgnoreSessionLock()) {
                            if (requiresProfile()) {
                                PropertyProfile profile = (PropertyProfile) request.getSession()
                                        .getAttribute(Constants.SELECTED_PROFILE);
                                if (profile == null) {
                                    request.getSession().setAttribute(Constants.ORIGINAL_REQUEST,
                                            Util.getOriginalRequest(request));
                                    return mapping.findForward("selectPropertyProfile");
                                }
                            }
                            return onExecute(mapping, form, request, response);
                        }
                    }
                }
            }
        } catch (NoPermissionException e) {
            if (log.isDebugEnabled())
                log.debug("User attempted to access page they do have have permission for. Resource type = "
                        + resourceType
                        + ". Now attempting to find the first valid item in the current menu tree to display.",
                        e);
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return null;
        } catch (SecurityException ex) {
            // Not logged in or expired
        } catch (ServletException ex) {
            throw ex;
        }

        // Do not direct to logon page for Ajax requests
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return null;
        }

        return gotoLogon(mapping, form, request, response);
    } catch (Throwable t) {
        log.error("Failed to process authenticated request.", t);
        throw t instanceof Exception ? (Exception) t : new Exception(t);
    }
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static void setInitialRequestInfo(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (UtilValidate.isNotEmpty(session.getAttribute("_WEBAPP_NAME_"))) {
        // oops, info already in place...
        return;//from w w  w  .java 2  s .  co  m
    }

    String fullRequestUrl = getFullRequestUrl(request);

    session.setAttribute("_WEBAPP_NAME_", getApplicationName(request));
    session.setAttribute("_CLIENT_LOCALE_", request.getLocale());
    session.setAttribute("_CLIENT_REQUEST_", fullRequestUrl);
    session.setAttribute("_CLIENT_USER_AGENT_",
            request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : "");
    session.setAttribute("_CLIENT_REFERER_",
            request.getHeader("Referer") != null ? request.getHeader("Referer") : "");

    session.setAttribute("_CLIENT_FORWARDED_FOR_", request.getHeader("X-Forwarded-For"));
    session.setAttribute("_CLIENT_REMOTE_ADDR_", request.getRemoteAddr());
    session.setAttribute("_CLIENT_REMOTE_HOST_", request.getRemoteHost());
    session.setAttribute("_CLIENT_REMOTE_USER_", request.getRemoteUser());
}

From source file:org.openiot.gsn.http.OneShotQueryWithAddressingHandler.java

public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException {

    SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat());

    String vsName = request.getParameter("name");
    String vsCondition = request.getParameter("condition");
    if (vsCondition == null || vsCondition.trim().length() == 0)
        vsCondition = " ";
    else//w ww.  j a  v a2  s  . c o  m
        vsCondition = " where " + vsCondition;
    String vsFields = request.getParameter("fields");
    if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*"))
        vsFields = "*";
    else
        vsFields += " , pk, timed";
    String windowSize = request.getParameter("window");
    if (windowSize == null || windowSize.trim().length() == 0)
        windowSize = "1";
    StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition
            + " order by timed DESC limit " + windowSize + " offset 0");
    DataEnumerator result;
    try {
        result = Main.getStorage(vsName).executeQuery(query, true);
    } catch (SQLException e) {
        logger.error("ERROR IN EXECUTING, query: " + query);
        logger.error(e.getMessage(), e);
        logger.error("Query is from " + request.getRemoteAddr() + "- " + request.getRemoteHost());
        return;
    }
    StringBuilder sb = new StringBuilder("<result>\n");
    while (result.hasMoreElements()) {
        StreamElement se = result.nextElement();
        sb.append("<stream-element>\n");
        for (int i = 0; i < se.getFieldNames().length; i++)
            if (se.getFieldTypes()[i] == DataTypes.BINARY)
                sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\">")
                        .append(se.getData()[i].toString()).append("</field>\n");
            else
                sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\">")
                        .append(StringEscapeUtils.escapeXml(se.getData()[i].toString())).append("</field>\n");
        sb.append("<field name=\"timed\" >").append(sdf.format(new Date(se.getTimeStamp())))
                .append("</field>\n");
        VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName);
        if (logger.isInfoEnabled())
            logger.info(new StringBuilder().append("Structure request for *").append(vsName)
                    .append("* received.").toString());
        //StringBuilder statement = new StringBuilder( "<virtual-sensor name=\"" ).append( vsName ).append( "\" last-modified=\"" ).append( new File( sensorConfig.getFileName( ) ).lastModified( ) ).append( "\">\n" );
        for (KeyValue df : sensorConfig.getAddressing())
            sb.append("<field name=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString()))
                    .append("\">").append(StringEscapeUtils.escapeXml(df.getValue().toString()))
                    .append("</field>\n");
        sb.append("</stream-element>\n");
    }
    result.close();
    sb.append("</result>");
    response.setHeader("Cache-Control", "no-store");
    response.setDateHeader("Expires", 0);
    response.setHeader("Pragma", "no-cache");
    response.getWriter().write(sb.toString());
}