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:org.appcelerator.transport.AjaxServiceTransportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ///* w  ww  .j a  v a2 s. c o m*/
    // make sure we check the integrity of the request before we continue
    //
    if (!validate(req, resp)) {
        LOG.warn("security validation failed for request=" + req + " from " + req.getRemoteAddr());
        return;
    }

    String type = req.getContentType();
    int idx = type.indexOf(';');

    if (idx > 0) {
        type = type.substring(0, idx);
    }

    try {
        // decode the incoming request
        ArrayList<Message> requests = new ArrayList<Message>(1);
        ArrayList<Message> responses = new ArrayList<Message>(1);

        ServiceMarshaller.getMarshaller(type).decode(req.getInputStream(), requests);

        if (requests.isEmpty()) {
            // no incoming messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        HttpSession session = req.getSession();
        InetAddress address = InetAddress.getByName(req.getRemoteAddr());
        //String instanceid = req.getParameter("instanceid");

        for (Message request : requests) {
            request.setUser(req.getUserPrincipal());
            request.setSession(session);
            request.setAddress(address);
            request.setServletRequest(req);

            //FIXME => refactor this out
            if (request.getType().equals(MessageType.APPCELERATOR_STATUS_REPORT)) {
                IMessageDataObject data = (IMessageDataObject) request.getData();
                data.put("remoteaddr", req.getRemoteAddr());
                data.put("remotehost", req.getRemoteHost());
                data.put("remoteuser", req.getRemoteUser());
            }

            ServiceRegistry.dispatch(request, responses);
        }

        if (responses.isEmpty()) {
            // no response messages, just return accepted header
            resp.setHeader("Content-Length", "0");
            resp.setContentType("text/plain;charset=UTF-8");
            resp.setStatus(HttpServletResponse.SC_ACCEPTED);
            return;
        }

        // setup the response
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setHeader("Connection", "Keep-Alive");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-control", "no-cache, no-store, private, must-revalidate");
        resp.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        // encode the responses
        ServletOutputStream output = resp.getOutputStream();
        ByteArrayOutputStream bout = new ByteArrayOutputStream(1000);
        String responseType = ServiceMarshaller.getMarshaller(type).encode(responses, req.getSession().getId(),
                bout);
        byte buf[] = bout.toByteArray();
        ByteArrayInputStream bin = new ByteArrayInputStream(buf);

        resp.setContentType(responseType);

        // do gzip encoding if browser supports it and if length > 1000 bytes
        String ae = req.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1 && buf.length > 1000) {
            resp.setHeader("Content-Encoding", "gzip");
            //a Vary: Accept-Encoding HTTP response header to alert proxies that a cached response should be sent only to 
            //clients that send the appropriate Accept-Encoding request header. This prevents compressed content from being sent 
            //to a client that will not understand it.
            resp.addHeader("Vary", "Accept-Encoding");
            GZIPOutputStream gzip = new GZIPOutputStream(output, buf.length);
            Util.copy(bin, gzip);
            gzip.flush();
            gzip.finish();
        } else {
            resp.setContentLength(buf.length);
            Util.copy(bin, output);
        }
        output.flush();
    } catch (Throwable e) {
        LOG.error("Error handling incoming POST request", e);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:edu.umich.its.lti.google.GoogleLtiServlet.java

/**
 * Forwards the request to open owner (container) JSP /view/root.jsp,
 * loading the given JSP page as container's contents.
 * //  w  ww.  j ava 2s. co  m
 * @param request
 *            HttpServletRequest storing the JSP page for use by owner
 * @param response
 *            HttpServletResponse for forward
 * @param tcSessionData
 * @param jspPage
 *            JspPage enum containing page-specific settings
 * @throws ServletException
 * @throws IOException
 */
private void loadJspPage(HttpServletRequest request, HttpServletResponse response, TcSessionData tcSessionData,
        JspPage jspPage) throws ServletException, IOException {
    if (jspPage.verifyAllowedRoles(tcSessionData.getUserRoleArray())) {
        request.setAttribute("jspPage", jspPage);
        retrieveGoogleDriveConfigFromSession(tcSessionData, request);

        Map<String, String> applicationProperties = convertResourceBundleToMap(resource);

        request.setAttribute("applicationProperties", applicationProperties);
        request.setAttribute("applicationPropertiesJson", new JacksonFactory().toString(applicationProperties));
        request.setAttribute("contextLabel", tcSessionData.getContextLabel());

        request.setAttribute("contextUrl", getGoogleServiceAccount(request.getRemoteHost()).getContextURL());
        if (request.getMethod().equals("POST")) {
            getGoogleAccessToken(request, response, tcSessionData);
        }
        request.setAttribute("userEmailAddress", tcSessionData.getUserEmailAddress());
        getServletContext().getRequestDispatcher("/view/root.jsp").forward(request, response);
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("Unauthorized attempt to acces JSP page ");
        sb.append(jspPage);
        sb.append(" requiring roles ");
        sb.append(Arrays.toString(jspPage.getRoles()));
        sb.append(" by ");
        sb.append(tcSessionData.getUserNameFull());
        sb.append(" <");
        sb.append(tcSessionData.getUserEmailAddress());
        sb.append("> with roles ");
        sb.append(Arrays.toString(tcSessionData.getUserRoleArray()));
        M_log.warn(sb.toString());
        loadJspPage(request, response, tcSessionData, JspPage.Home);
    }
}

From source file:nl.strohalm.cyclos.utils.LoginHelper.java

/**
 * Perform the login itself/*from w  w  w.java  2 s .c  o  m*/
 */
public User login(final Class<? extends User> requiredUserClass, final String principalTypeString,
        final String memberUsername, final String principal, final String password, final String channel,
        final HttpServletRequest request, final HttpServletResponse response) throws LoginException {
    final String remoteAddress = request.getRemoteAddr();

    final PrincipalType principalType = channelService.resolvePrincipalType(channel, principalTypeString);

    // Validate the user
    String usernameToVerify = principal;
    if (principalType.getPrincipal() != Principal.USER) {
        try {
            Member member;
            member = elementService.loadByPrincipal(principalType, principal, Element.Relationships.USER,
                    Element.Relationships.GROUP);
            usernameToVerify = member.getUsername();
        } catch (final EntityNotFoundException e) {
            usernameToVerify = "";
        }
    }
    final User user = accessService.verifyLogin(memberUsername, usernameToVerify, remoteAddress);
    if (!requiredUserClass.isInstance(user)) {
        throw new AccessDeniedException();
    }

    // Find the user nature
    final Group group = user.getElement().getGroup();
    final boolean isAdmin = group instanceof AdminGroup;
    final boolean isMember = group instanceof MemberGroup;
    final boolean isBroker = group instanceof BrokerGroup;
    final boolean isOperator = group instanceof OperatorGroup;
    final boolean isPosWeb = RequestHelper.isPosWeb(request);

    final AccessSettings accessSettings = settingsService.getAccessSettings();

    // Check if the administrator is allowed to login
    if (isAdmin && !accessSettings.getAdministrationWhitelistValidator().isAllowed(request.getRemoteHost(),
            request.getRemoteAddr())) {
        throw new AccessDeniedException();
    }

    // According to the cyclos.properties flag, create a new session or use the current one
    HttpSession session;
    if (newSessionAfterLogin) {
        session = createNewSessionForlogin(request);
    } else {
        session = request.getSession();
    }

    // Login the user
    accessService.login(user, password, channel, isPosWeb, remoteAddress, session.getId());

    // Apply the session timeout
    final TimePeriod timeout = isPosWeb ? accessSettings.getPoswebTimeout()
            : isMember ? accessSettings.getMemberTimeout() : accessSettings.getAdminTimeout();
    int timeoutSeconds = (int) timeout.getValueIn(TimePeriod.Field.SECONDS);
    if (timeoutSeconds <= 0) {
        timeoutSeconds = -1;
    }
    session.setMaxInactiveInterval(timeoutSeconds);

    // If is a member, determine if the member has accounts, documents, loan groups and memberPos
    boolean hasAccounts = false;
    boolean singleAccount = false;
    boolean hasDocuments = false;
    boolean hasLoanGroups = false;
    boolean hasGeneralReferences = false;
    boolean hasTransactionFeedbacks = false;
    boolean hasPin = false;
    boolean hasExternalChannels = false;
    boolean hasCards = false;
    boolean hasPos = false;
    boolean hasCommissionContracts = false;
    if (isMember || isOperator) {
        Member member;
        if (isMember) {
            member = ((MemberUser) user).getMember();

            // Get the accessible channels
            final MemberGroup memberGroup = groupService.load(member.getMemberGroup().getId(),
                    MemberGroup.Relationships.CHANNELS);
            hasPin = groupService.usesPin(memberGroup);
            for (final Channel current : memberGroup.getChannels()) {
                if (!Channel.WEB.equals(current.getInternalName())) {
                    hasExternalChannels = true;
                    break;
                }
            }

            if (!member.getPosDevices().isEmpty()) {
                hasPos = true;
                if (member.getPosDevices().size() == 1) {
                    final Collection<MemberPos> memberPos = member.getPosDevices();
                    for (final MemberPos mpos : memberPos) {
                        session.setAttribute("uniqueMemberPosId ", mpos.getPos().getId());
                    }
                }
            }

        } else {
            member = ((OperatorUser) user).getOperator().getMember();
        }
        // Fetch broker
        member = elementService.load(member.getId(), Member.Relationships.BROKER);
        final MemberGroup memberGroup = member.getMemberGroup();

        // Check if the member has accounts
        final List<? extends Account> accounts = accountService.getAccounts(member);
        hasAccounts = !accounts.isEmpty();
        singleAccount = accounts.size() == 1;
        if (isMember) {
            // Check if the member has documents
            if (permissionService.hasPermission(MemberPermission.DOCUMENTS_VIEW)) {
                hasDocuments = true;
            } else {
                final DocumentQuery documentQuery = new DocumentQuery();
                documentQuery.setNatures(Collections.singleton(Document.Nature.MEMBER));
                documentQuery.setMember(member);
                documentQuery.setPageForCount();
                hasDocuments = PageHelper.hasResults(documentService.search(documentQuery));
            }
            // Check if the member has loan groups
            final LoanGroupQuery lgq = new LoanGroupQuery();
            lgq.setPageForCount();
            lgq.setMember(member);
            hasLoanGroups = PageHelper.hasResults(loanGroupService.search(lgq));

            // Check if the member has commission contracts
            hasCommissionContracts = commissionService.hasBrokerCommissionContracts();
        }
        // Check if the user has references
        final Collection<Nature> referenceNatures = referenceService.getNaturesByGroup(memberGroup);
        hasGeneralReferences = referenceNatures.contains(Nature.GENERAL);
        hasTransactionFeedbacks = referenceNatures.contains(Nature.TRANSACTION);

        // Check if the user can have guarantees
        try {
            final Collection<GuaranteeType.Model> guaranteeModels = guaranteeService
                    .getRelatedGuaranteeModels();
            session.setAttribute("loggedMemberHasGuarantees", guaranteeModels.size() > 0);
        } catch (final Exception e) {
            // Ignore
        }

        // Check if the user has cards
        hasCards = member.getCards().isEmpty() ? false : true;
    }

    if (isAdmin || isBroker) {
        // Retrieve the member record types the logged user can see on the menu
        final MemberRecordTypeQuery query = new MemberRecordTypeQuery();
        if (isAdmin) {
            query.setViewableByAdminGroup((AdminGroup) group);
        } else {
            query.setViewableByBrokerGroup((BrokerGroup) group);
        }
        query.setShowMenuItem(true);
        final List<MemberRecordType> types = memberRecordTypeService.search(query);
        session.setAttribute("memberRecordTypesInMenu", types);
    }

    // When a receipt printer cookie is set, and the printer no longer exists, or belongs to someone else, clear the cookie
    final String receiptPrinterId = RequestHelper.getCookieValue(request, "receiptPrinterId");
    if (StringUtils.isNotEmpty(receiptPrinterId)) {
        final Long id = IdConverter.instance().valueOf(receiptPrinterId);
        if (!receiptPrinterSettingsService.belongsToTheLoggedUser(id)) {
            final Cookie cookie = new Cookie("receiptPrinterId", "");
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    final String actionPrefix = "/" + (isAdmin ? "admin" : isMember ? "member" : "operator");

    // Set the request attributes
    request.setAttribute("loggedUser", user);
    request.setAttribute("loggedElement", user.getElement());

    // Set the session attributes
    session.setAttribute("loggedUserId", user.getId());
    session.setAttribute("isAdmin", isAdmin);
    session.setAttribute("isMember", isMember);
    session.setAttribute("isBroker", isBroker);
    session.setAttribute("isOperator", isOperator);
    session.setAttribute("isBuyer", guaranteeService.isBuyer());
    session.setAttribute("isSeller", guaranteeService.isSeller());
    session.setAttribute("isIssuer", guaranteeService.isIssuer());
    session.setAttribute("loggedMemberHasAccounts", hasAccounts);
    session.setAttribute("loggedMemberHasSingleAccount", singleAccount);
    session.setAttribute("loggedMemberHasDocuments", hasDocuments);
    session.setAttribute("loggedMemberHasLoanGroups", hasLoanGroups);
    session.setAttribute("loggedMemberHasGeneralReferences", hasGeneralReferences);
    session.setAttribute("loggedMemberHasTransactionFeedbacks", hasTransactionFeedbacks);
    session.setAttribute("hasPin", hasPin);
    session.setAttribute("hasCards", hasCards);
    session.setAttribute("hasPos", hasPos);
    session.setAttribute("hasCommissionContracts", hasCommissionContracts);
    session.setAttribute("hasExternalChannels", hasExternalChannels);
    session.setAttribute("actionPrefix", actionPrefix);
    session.setAttribute("pathPrefix", "/do" + actionPrefix);
    session.setAttribute("navigation", Navigation.get(session));

    // Return the logged user
    return user;
}

From source file:nl.b3p.commons.security.aselect.ASelectAuthorizationFilter.java

private boolean verifyCredentials(HttpServletRequest request, String rid, String credentials)
        throws ServletException, ASelectAuthorizationException {

    Map params = new Hashtable();
    params.put("request", "verify_credentials");
    params.put("rid", rid);
    params.put("aselect_credentials", credentials);

    Map asResponse = null;/*  w w  w.  jav  a 2  s.c  om*/
    try {
        asResponse = client.performRequest(params);
    } catch (IOException e) {
        throw new ServletException(e);
    }

    String asResult = (String) asResponse.get("result_code");
    String asTicket = (String) asResponse.get("ticket");
    String asTicketExpTime = (String) asResponse.get("ticket_exp_time");
    String asUid = (String) asResponse.get("uid");
    String asOrganization = (String) asResponse.get("organization");
    String asAuthSPLevel = (String) asResponse.get("authsp_level");
    String asAuthSP = (String) asResponse.get("authsp");
    String asAttributes = (String) asResponse.get("attributes");

    if (!ASELECT_OK.equals(asResult)) {
        /* Indien user error naar errorpage met melding ala
         *  "Uw sessie is verlopen of ongeldig of U heeft te lang gewacht
         *   met inloggen. Probeer het opnieuw."
         * Eventueel met link of met refresh na aantal seconden
         *
         * TODO bij request.getSession().isNew() error met "Uw browser moet
         * cookies accepteren" oid
         *
         * Bij andere errors ServletException
         */
        log.info("Received error code \"" + asResult + "\" from A-Select when verifying credentials (from IP: "
                + request.getRemoteHost() + ")");
        if (isUserError(asResult)) {
            /* FIXME foutmelding afhankelijk van result code */
            return false;
        } else {
            throw new ServletException("A-Select communication error");
        }
    } else {
        Date startTime, expTime;

        /* De Agent geeft ticket_start_time mee maar de Server niet omdat
         * bij de server api je zelf bij moet houden wanneer het ticket is
         * verlopen zoals de agent doet.
         *
         * Een tekortkoming van het A-Select protocol is dat indien de systeemtijd
         * van de A-Select server en de client niet overeenkomen het ticket
         * meteen expired of de duur van het ticket verkeerd is (te  kort
         * danwel te lang).
         *
         * Nou is in een webapplicatie omgeving de systeemtijd van de server
         * die de echte eindtijd van het ticket bepaalt natuurlijk wel te
         * synchronizeren met die van de A-Select server die de originele
         * eindtijd van het ticket bepaalt.
         */

        if (api == ASELECT_API_AGENT) {
            startTime = new Date(Long.parseLong((String) asResponse.get("ticket_start_time")));
        } else {
            startTime = new Date();
        }

        try {
            expTime = new Date(Long.parseLong(asTicketExpTime));

            log.debug("Ticket start date/time:      " + startTime);
            log.debug("Ticket expiration date/time: " + expTime);

            if (startTime.compareTo(expTime) > 0) {
                throw new ServletException("A-Select server specified ticket expiration time in the past");
            }

        } catch (NumberFormatException nfe) {
            log.error("invalid date received from A-Select server", nfe);
            throw new ServletException("A-Select communication error");
        }

        ASelectTicket ticket;

        if (api == ASELECT_API_AGENT) {
            ticket = new ASelectAgentTicket(asTicket, appId, startTime, expTime, asUid, asOrganization,
                    asAuthSPLevel, asAuthSP, asAttributes, (ASelectAgentClient) client);
        } else {
            /* api == ASELECT_API_SERVER */
            // TODO impl deze ticket, die adv expTime verify() implementeert
            ticket = null;
            //ticket = new ASelectServerTicket(asTicket, startTime, expTime,
            //    asUid, asOrganization, asAuthSPLevel, asAuthSP, asAttributes);
        }
        ticket.putOnSession(request.getSession());
        return true;
    }
}

From source file:fsi_admin.JSmtpConn.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ERROR = null, codErr = null;

    try {/*from  w w w. ja va 2s  .  co m*/
        Properties parametros = new Properties();
        Vector archivos = new Vector();
        DiskFileUpload fu = new DiskFileUpload();
        List items = fu.parseRequest(request);
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField())
                parametros.put(item.getFieldName(), item.getString());
            else
                archivos.addElement(item);
        }

        if (parametros.getProperty("SERVER") == null || parametros.getProperty("DATABASE") == null
                || parametros.getProperty("USER") == null || parametros.getProperty("PASSWORD") == null
                || parametros.getProperty("BODY") == null || parametros.getProperty("MIMETYPE") == null
                || parametros.getProperty("SUBJECT") == null || parametros.getProperty("EMAIL") == null
                || parametros.getProperty("SOURCEMAIL") == null) {
            System.out.println("No recibi parametros de conexin antes del correo a enviar");
            ERROR = "ERROR: El servidor no recibi todos los parametros de conexion (SERVER,DATABASE,USER,PASSWORD) antes del correo a enviar";
            codErr = "3";
            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                    parametros.getProperty("PASSWORD"), request, ERROR, 3);
        }

        //Hasta aqui se han enviado todos los parametros ninguno nulo
        if (ERROR == null) {
            StringBuffer msj = new StringBuffer(), SMTPHOST = new StringBuffer(), SMTPPORT = new StringBuffer(),
                    SMTPUSR = new StringBuffer(), SMTPPASS = new StringBuffer();
            MutableBoolean COBRAR = new MutableBoolean(false);
            MutableDouble COSTO = new MutableDouble(0.0), SALDO = new MutableDouble(0.0);
            // Primero obtiene info del SMTP
            if (!obtenInfoSMTP(request.getRemoteAddr(), request.getRemoteHost(),
                    parametros.getProperty("SERVER"), parametros.getProperty("DATABASE"),
                    parametros.getProperty("USER"), parametros.getProperty("PASSWORD"), SMTPHOST, SMTPPORT,
                    SMTPUSR, SMTPPASS, msj, COSTO, SALDO, COBRAR)) {
                System.out.println("El usuario y contrasea de servicio estan mal");
                ERROR = msj.toString();
                codErr = "2";
                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                        parametros.getProperty("PASSWORD"), request, ERROR, 2);

            } else {
                if (COBRAR.booleanValue() && SALDO.doubleValue() < COSTO.doubleValue()) {
                    System.out.println("El servicio tiene un costo que no alcanza en el saldo");
                    ERROR = "El servicio SMTP tiene un costo que no alcanza en el saldo";
                    codErr = "2";
                    ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                            parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                            parametros.getProperty("PASSWORD"), request, ERROR, 2);

                } else {
                    Properties props;

                    props = System.getProperties();
                    props.put("mail.transport.protocol", "smtp");
                    props.put("mail.smtp.port", Integer.parseInt(SMTPPORT.toString()));

                    // Set properties indicating that we want to use STARTTLS to encrypt the connection.
                    // The SMTP session will begin on an unencrypted connection, and then the client
                    // will issue a STARTTLS command to upgrade to an encrypted connection.
                    props.put("mail.smtp.auth", "true");
                    props.put("mail.smtp.starttls.enable", "true");
                    props.put("mail.smtp.starttls.required", "true");

                    // Create a Session object to represent a mail session with the specified properties. 
                    Session session = Session.getDefaultInstance(props);
                    MimeMessage mmsg = new MimeMessage(session);
                    BodyPart messagebodypart = new MimeBodyPart();
                    MimeMultipart multipart = new MimeMultipart();

                    if (!prepareMsg(parametros.getProperty("SOURCEMAIL"), parametros.getProperty("EMAIL"),
                            parametros.getProperty("SUBJECT"), parametros.getProperty("MIMETYPE"),
                            parametros.getProperty("BODY"), msj, props, session, mmsg, messagebodypart,
                            multipart)) {
                        System.out.println("No se permiti preparar el mensaje");
                        ERROR = msj.toString();
                        codErr = "3";
                        ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                parametros.getProperty("PASSWORD"), request, ERROR, 3);

                    } else {
                        if (!adjuntarArchivo(msj, messagebodypart, multipart, archivos)) {
                            System.out.println("No se permiti adjuntar archivos al mensaje");
                            ERROR = msj.toString();
                            codErr = "3";
                            ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                    parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                    parametros.getProperty("PASSWORD"), request, ERROR, 3);

                        } else {
                            if (!sendMsg(SMTPHOST.toString(), SMTPUSR.toString(), SMTPPASS.toString(), msj,
                                    session, mmsg, multipart)) {
                                System.out.println("No se permiti enviar el mensaje");
                                ERROR = msj.toString();
                                codErr = "3";
                                ingresarRegistroFallido(request.getRemoteAddr(), request.getRemoteHost(),
                                        parametros.getProperty("SERVER"), parametros.getProperty("USER"),
                                        parametros.getProperty("PASSWORD"), request, ERROR, 3);
                            } else {
                                ingresarRegistroExitoso(parametros.getProperty("SERVER"),
                                        parametros.getProperty("DATABASE"), parametros.getProperty("SUBJECT"),
                                        COSTO, SALDO, COBRAR);

                                //Devuelve la respuesta al cliente
                                Element Correo = new Element("Correo");
                                Correo.setAttribute("Subject", parametros.getProperty("SUBJECT"));
                                Correo.setAttribute("MsjError", "");
                                Document Reporte = new Document(Correo);

                                Format format = Format.getPrettyFormat();
                                format.setEncoding("utf-8");
                                format.setTextMode(TextMode.NORMALIZE);
                                XMLOutputter xmlOutputter = new XMLOutputter(format);
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                xmlOutputter.output(Reporte, out);

                                byte[] data = out.toByteArray();
                                ByteArrayInputStream istream = new ByteArrayInputStream(data);

                                String destino = "Correo.xml";
                                JBajarArchivo fd = new JBajarArchivo();
                                fd.doDownload(response, getServletConfig().getServletContext(), istream,
                                        "text/xml", data.length, destino);

                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        ERROR = "ERROR DE EXCEPCION EN SERVIDOR PAC: " + e.getMessage();
    }

    //Genera el archivo XML de error para ser devuelto al Servidor
    if (ERROR != null) {
        Element SIGN_ERROR = new Element("SIGN_ERROR");
        SIGN_ERROR.setAttribute("CodError", codErr);
        SIGN_ERROR.setAttribute("MsjError", ERROR);
        Document Reporte = new Document(SIGN_ERROR);

        Format format = Format.getPrettyFormat();
        format.setEncoding("utf-8");
        format.setTextMode(TextMode.NORMALIZE);
        XMLOutputter xmlOutputter = new XMLOutputter(format);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        xmlOutputter.output(Reporte, out);

        byte[] data = out.toByteArray();
        ByteArrayInputStream istream = new ByteArrayInputStream(data);

        String destino = "SIGN_ERROR.xml";
        JBajarArchivo fd = new JBajarArchivo();
        fd.doDownload(response, getServletConfig().getServletContext(), istream, "text/xml", data.length,
                destino);

    }
}

From source file:org.dbflute.saflute.web.servlet.filter.RequestLoggingFilter.java

protected void buildRequestInfo(StringBuilder sb, HttpServletRequest request, HttpServletResponse response,
        boolean showResponse) {
    sb.append("Request class=" + request.getClass().getName());
    sb.append(", RequestedSessionId=").append(request.getRequestedSessionId());

    sb.append(LF).append(IND);/*from   w  w w .java2s  .c  om*/
    sb.append(", REQUEST_URI=").append(request.getRequestURI());
    sb.append(", SERVLET_PATH=").append(request.getServletPath());
    sb.append(", CharacterEncoding=" + request.getCharacterEncoding());
    sb.append(", ContentLength=").append(request.getContentLength());

    sb.append(LF).append(IND);
    sb.append(", ContentType=").append(request.getContentType());
    sb.append(", Locale=").append(request.getLocale());
    sb.append(", Locales=");
    final Enumeration<?> locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        final Locale locale = (Locale) locales.nextElement();
        if (first) {
            first = false;
        } else {
            sb.append(", ");
        }
        sb.append(locale.toString());
    }
    sb.append(", Scheme=").append(request.getScheme());
    sb.append(", isSecure=").append(request.isSecure());

    sb.append(LF).append(IND);
    sb.append(", SERVER_PROTOCOL=").append(request.getProtocol());
    sb.append(", REMOTE_ADDR=").append(request.getRemoteAddr());
    sb.append(", REMOTE_HOST=").append(request.getRemoteHost());
    sb.append(", SERVER_NAME=").append(request.getServerName());
    sb.append(", SERVER_PORT=").append(request.getServerPort());

    sb.append(LF).append(IND);
    sb.append(", ContextPath=").append(request.getContextPath());
    sb.append(", REQUEST_METHOD=").append(request.getMethod());
    sb.append(", PathInfo=").append(request.getPathInfo());
    sb.append(", RemoteUser=").append(request.getRemoteUser());

    sb.append(LF).append(IND);
    sb.append(", REQUEST_URL=").append(request.getRequestURL());
    sb.append(LF).append(IND);
    sb.append(", QUERY_STRING=").append(request.getQueryString());
    if (showResponse) {
        sb.append(LF).append(IND);
        buildResponseInfo(sb, request, response);
    }

    sb.append(LF);
    buildRequestHeaders(sb, request);
    buildRequestParameters(sb, request);
    buildCookies(sb, request);
    buildRequestAttributes(sb, request);
    buildSessionAttributes(sb, request);
}

From source file:org.hoteia.qalingo.core.web.util.RequestUtil.java

public void addClickstream(final HttpServletRequest request) throws Exception {
    ClickstreamSession clickstream = getClickstreamSession(request);
    Date lastRequest = new Date();
    clickstream.setLastRequest(lastRequest);
    clickstream.setHostname(request.getRemoteHost());

    clickstream.getRequests().add(new ClickstreamRequest(request, lastRequest));

    request.getSession().setAttribute(Constants.ENGINE_CLICKSTREAM, clickstream);
}

From source file:edu.umich.its.lti.google.GoogleLtiServlet.java

/**
 * This verifies the post has expected parameters from valid LTI client, and
 * the request has matching signature. If not verified, this sends error to
 * client; caller should not attempt to proceed.
 *//*  ww w .  j a  v  a  2 s . c o  m*/
private boolean verifyPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ResourceBundle properties = ResourceBundle.getBundle("ltis");
    // 1 - verify the expected parameters exist
    boolean result = EXPECTED_LTI_MESSAGE_TYPE.equals(request.getParameter("lti_message_type"))
            && EXPECTED_LTI_VERSION.equals(request.getParameter("lti_version"))
            && !getIsEmpty(request.getParameter("oauth_consumer_key"))
            && !getIsEmpty(request.getParameter("resource_link_id"));
    if (!result) {
        doError(request, response,
                "Post apparently not from LTI Consumer, as parameters are missing or invalid.");
    }
    // 2 - verify signature
    result = RequestSignatureUtils.verifySignature(request, request.getParameter("oauth_consumer_key"),
            getGoogleServiceAccount(request.getRemoteHost()).getLtiSecret(),
            getGoogleServiceAccount(request.getRemoteHost()).getLtiUrl());
    if (!result) {
        doError(request, response, "Request signature is invalid.");
    }
    return result;
}

From source file:org.apache.nifi.processors.standard.HandleHttpRequest.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    try {/*from  w ww.ja v a2 s  .c o m*/
        if (!initialized.get()) {
            initializeServer(context);
        }
    } catch (Exception e) {
        context.yield();
        throw new ProcessException("Failed to initialize the server", e);
    }

    final HttpRequestContainer container = containerQueue.poll();
    if (container == null) {
        return;
    }

    final long start = System.nanoTime();
    final HttpServletRequest request = container.getRequest();
    FlowFile flowFile = session.create();
    try {
        flowFile = session.importFrom(request.getInputStream(), flowFile);
    } catch (final IOException e) {
        getLogger().error("Failed to receive content from HTTP Request from {} due to {}",
                new Object[] { request.getRemoteAddr(), e });
        session.remove(flowFile);
        return;
    }

    final String charset = request.getCharacterEncoding() == null
            ? context.getProperty(URL_CHARACTER_SET).getValue()
            : request.getCharacterEncoding();

    final String contextIdentifier = UUID.randomUUID().toString();
    final Map<String, String> attributes = new HashMap<>();
    try {
        putAttribute(attributes, HTTPUtils.HTTP_CONTEXT_ID, contextIdentifier);
        putAttribute(attributes, "mime.type", request.getContentType());
        putAttribute(attributes, "http.servlet.path", request.getServletPath());
        putAttribute(attributes, "http.context.path", request.getContextPath());
        putAttribute(attributes, "http.method", request.getMethod());
        putAttribute(attributes, "http.local.addr", request.getLocalAddr());
        putAttribute(attributes, HTTPUtils.HTTP_LOCAL_NAME, request.getLocalName());
        final String queryString = request.getQueryString();
        if (queryString != null) {
            putAttribute(attributes, "http.query.string", URLDecoder.decode(queryString, charset));
        }
        putAttribute(attributes, HTTPUtils.HTTP_REMOTE_HOST, request.getRemoteHost());
        putAttribute(attributes, "http.remote.addr", request.getRemoteAddr());
        putAttribute(attributes, "http.remote.user", request.getRemoteUser());
        putAttribute(attributes, HTTPUtils.HTTP_REQUEST_URI, request.getRequestURI());
        putAttribute(attributes, "http.request.url", request.getRequestURL().toString());
        putAttribute(attributes, "http.auth.type", request.getAuthType());

        putAttribute(attributes, "http.requested.session.id", request.getRequestedSessionId());
        final DispatcherType dispatcherType = request.getDispatcherType();
        if (dispatcherType != null) {
            putAttribute(attributes, "http.dispatcher.type", dispatcherType.name());
        }
        putAttribute(attributes, "http.character.encoding", request.getCharacterEncoding());
        putAttribute(attributes, "http.locale", request.getLocale());
        putAttribute(attributes, "http.server.name", request.getServerName());
        putAttribute(attributes, HTTPUtils.HTTP_PORT, request.getServerPort());

        final Enumeration<String> paramEnumeration = request.getParameterNames();
        while (paramEnumeration.hasMoreElements()) {
            final String paramName = paramEnumeration.nextElement();
            final String value = request.getParameter(paramName);
            attributes.put("http.param." + paramName, value);
        }

        final Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (final Cookie cookie : cookies) {
                final String name = cookie.getName();
                final String cookiePrefix = "http.cookie." + name + ".";
                attributes.put(cookiePrefix + "value", cookie.getValue());
                attributes.put(cookiePrefix + "domain", cookie.getDomain());
                attributes.put(cookiePrefix + "path", cookie.getPath());
                attributes.put(cookiePrefix + "max.age", String.valueOf(cookie.getMaxAge()));
                attributes.put(cookiePrefix + "version", String.valueOf(cookie.getVersion()));
                attributes.put(cookiePrefix + "secure", String.valueOf(cookie.getSecure()));
            }
        }

        if (queryString != null) {
            final String[] params = URL_QUERY_PARAM_DELIMITER.split(queryString);
            for (final String keyValueString : params) {
                final int indexOf = keyValueString.indexOf("=");
                if (indexOf < 0) {
                    // no =, then it's just a key with no value
                    attributes.put("http.query.param." + URLDecoder.decode(keyValueString, charset), "");
                } else {
                    final String key = keyValueString.substring(0, indexOf);
                    final String value;

                    if (indexOf == keyValueString.length() - 1) {
                        value = "";
                    } else {
                        value = keyValueString.substring(indexOf + 1);
                    }

                    attributes.put("http.query.param." + URLDecoder.decode(key, charset),
                            URLDecoder.decode(value, charset));
                }
            }
        }
    } catch (final UnsupportedEncodingException uee) {
        throw new ProcessException("Invalid character encoding", uee); // won't happen because charset has been validated
    }

    final Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        final String headerValue = request.getHeader(headerName);
        putAttribute(attributes, "http.headers." + headerName, headerValue);
    }

    final Principal principal = request.getUserPrincipal();
    if (principal != null) {
        putAttribute(attributes, "http.principal.name", principal.getName());
    }

    final X509Certificate certs[] = (X509Certificate[]) request
            .getAttribute("javax.servlet.request.X509Certificate");
    final String subjectDn;
    if (certs != null && certs.length > 0) {
        final X509Certificate cert = certs[0];
        subjectDn = cert.getSubjectDN().getName();
        final String issuerDn = cert.getIssuerDN().getName();

        putAttribute(attributes, HTTPUtils.HTTP_SSL_CERT, subjectDn);
        putAttribute(attributes, "http.issuer.dn", issuerDn);
    } else {
        subjectDn = null;
    }

    flowFile = session.putAllAttributes(flowFile, attributes);

    final HttpContextMap contextMap = context.getProperty(HTTP_CONTEXT_MAP)
            .asControllerService(HttpContextMap.class);
    final boolean registered = contextMap.register(contextIdentifier, request, container.getResponse(),
            container.getContext());

    if (!registered) {
        getLogger().warn(
                "Received request from {} but could not process it because too many requests are already outstanding; responding with SERVICE_UNAVAILABLE",
                new Object[] { request.getRemoteAddr() });

        try {
            container.getResponse().setStatus(Status.SERVICE_UNAVAILABLE.getStatusCode());
            container.getResponse().flushBuffer();
            container.getContext().complete();
        } catch (final Exception e) {
            getLogger().warn("Failed to respond with SERVICE_UNAVAILABLE message to {} due to {}",
                    new Object[] { request.getRemoteAddr(), e });
        }

        session.remove(flowFile);
        return;
    }

    final long receiveMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start);
    session.getProvenanceReporter().receive(flowFile, HTTPUtils.getURI(attributes),
            "Received from " + request.getRemoteAddr() + (subjectDn == null ? "" : " with DN=" + subjectDn),
            receiveMillis);
    session.transfer(flowFile, REL_SUCCESS);
    getLogger().info("Transferring {} to 'success'; received from {}",
            new Object[] { flowFile, request.getRemoteAddr() });
}

From source file:org.sakaiproject.portal.util.ErrorReporter.java

@SuppressWarnings("rawtypes")
private String requestDisplay(HttpServletRequest request) {
    ResourceBundle rb = rbDefault;
    StringBuilder sb = new StringBuilder();
    try {/* w  ww . j  a  v  a 2s.c om*/
        sb.append(rb.getString("bugreport.request")).append("\n");
        sb.append(rb.getString("bugreport.request.authtype")).append(request.getAuthType()).append("\n");
        sb.append(rb.getString("bugreport.request.charencoding")).append(request.getCharacterEncoding())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contentlength")).append(request.getContentLength())
                .append("\n");
        sb.append(rb.getString("bugreport.request.contenttype")).append(request.getContentType()).append("\n");
        sb.append(rb.getString("bugreport.request.contextpath")).append(request.getContextPath()).append("\n");
        sb.append(rb.getString("bugreport.request.localaddr")).append(request.getLocalAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.localname")).append(request.getLocalName()).append("\n");
        sb.append(rb.getString("bugreport.request.localport")).append(request.getLocalPort()).append("\n");
        sb.append(rb.getString("bugreport.request.method")).append(request.getMethod()).append("\n");
        sb.append(rb.getString("bugreport.request.pathinfo")).append(request.getPathInfo()).append("\n");
        sb.append(rb.getString("bugreport.request.protocol")).append(request.getProtocol()).append("\n");
        sb.append(rb.getString("bugreport.request.querystring")).append(request.getQueryString()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteaddr")).append(request.getRemoteAddr()).append("\n");
        sb.append(rb.getString("bugreport.request.remotehost")).append(request.getRemoteHost()).append("\n");
        sb.append(rb.getString("bugreport.request.remoteport")).append(request.getRemotePort()).append("\n");
        sb.append(rb.getString("bugreport.request.requesturl")).append(request.getRequestURL()).append("\n");
        sb.append(rb.getString("bugreport.request.scheme")).append(request.getScheme()).append("\n");
        sb.append(rb.getString("bugreport.request.servername")).append(request.getServerName()).append("\n");
        sb.append(rb.getString("bugreport.request.headers")).append("\n");
        for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) {
            String headerName = (String) e.nextElement();
            boolean censor = (censoredHeaders.get(headerName) != null);
            for (Enumeration he = request.getHeaders(headerName); he.hasMoreElements();) {
                String headerValue = (String) he.nextElement();
                sb.append(rb.getString("bugreport.request.header")).append(headerName).append(":")
                        .append(censor ? "---censored---" : headerValue).append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.parameters")).append("\n");
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();
            boolean censor = (censoredParameters.get(parameterName) != null);
            String[] paramvalues = request.getParameterValues(parameterName);
            for (int i = 0; i < paramvalues.length; i++) {
                sb.append(rb.getString("bugreport.request.parameter")).append(parameterName).append(":")
                        .append(i).append(":").append(censor ? "----censored----" : paramvalues[i])
                        .append("\n");
            }
        }
        sb.append(rb.getString("bugreport.request.attributes")).append("\n");
        for (Enumeration e = request.getAttributeNames(); e.hasMoreElements();) {
            String attributeName = (String) e.nextElement();
            Object attribute = request.getAttribute(attributeName);
            boolean censor = (censoredAttributes.get(attributeName) != null);
            sb.append(rb.getString("bugreport.request.attribute")).append(attributeName).append(":")
                    .append(censor ? "----censored----" : attribute).append("\n");
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            DateFormat serverLocaleDateFormat = DateFormat.getDateInstance(DateFormat.FULL,
                    Locale.getDefault());
            sb.append(rb.getString("bugreport.session")).append("\n");
            sb.append(rb.getString("bugreport.session.creation")).append(session.getCreationTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.lastaccess")).append(session.getLastAccessedTime())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.creationdatetime"))
                    .append(serverLocaleDateFormat.format(session.getCreationTime())).append("\n");
            sb.append(rb.getString("bugreport.session.lastaccessdatetime"))
                    .append(serverLocaleDateFormat.format(session.getLastAccessedTime())).append("\n");
            sb.append(rb.getString("bugreport.session.maxinactive")).append(session.getMaxInactiveInterval())
                    .append("\n");
            sb.append(rb.getString("bugreport.session.attributes")).append("\n");
            for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
                String attributeName = (String) e.nextElement();
                Object attribute = session.getAttribute(attributeName);
                boolean censor = (censoredAttributes.get(attributeName) != null);
                sb.append(rb.getString("bugreport.session.attribute")).append(attributeName).append(":")
                        .append(censor ? "----censored----" : attribute).append("\n");
            }

        }
    } catch (Exception ex) {
        M_log.error("Failed to generate request display", ex);
        sb.append("Error " + ex.getMessage());
    }

    return sb.toString();
}