Example usage for javax.servlet.http HttpServletRequest setCharacterEncoding

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

Introduction

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

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:cn.edu.henu.rjxy.lms.controller.TeaController.java

@RequestMapping(value = "courselist", method = RequestMethod.GET)
public @ResponseBody List<TeacherCourseResult> courselist(HttpServletRequest request,
        @RequestParam("xueqi") String xueqi) throws UnsupportedEncodingException {
    request.setCharacterEncoding("utf-8");
    String sn = getCurrentUsername();
    Teacher tec = TeacherDao.getTeacherBySn(sn);
    System.out.println(tec.getTeacherSn());
    return TeacherDao.getTeacherCourseByTermSn(Integer.parseInt(xueqi), tec.getTeacherSn());
}

From source file:org.apache.click.Context.java

/**
 * Create a new request context./*w  w  w .jav  a  2s  .c o  m*/
 *
 * @param context the servlet context
 * @param config the servlet config
 * @param request the servlet request
 * @param response the servlet response
 * @param isPost the servlet request is a POST
 * @param clickServlet the click servlet instance
 */
public Context(ServletContext context, ServletConfig config, HttpServletRequest request,
        HttpServletResponse response, boolean isPost, ClickServlet clickServlet) {

    this.clickServlet = clickServlet;
    this.context = context;
    this.config = config;
    this.isPost = isPost;

    ContextStack contextStack = getContextStack();

    if (contextStack.size() == 0) {

        // CLK-312. Apply request.setCharacterEncoding before wrapping
        // request in ClickRequestWrapper
        String charset = clickServlet.getConfigService().getCharset();
        if (charset != null) {

            try {
                request.setCharacterEncoding(charset);

            } catch (UnsupportedEncodingException ex) {
                String msg = "The character encoding " + charset + " is invalid.";
                LogService logService = clickServlet.getConfigService().getLogService();
                logService.warn(msg, ex);
            }
        }

        FileUploadService fus = clickServlet.getConfigService().getFileUploadService();

        this.request = new ClickRequestWrapper(request, fus);

    } else {
        this.request = request;
    }
    this.response = response;
}

From source file:org.oclc.oai.server.OAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is taken from the request and
 * used to invoke an OAIVerb object of the corresponding kind to do the actual work of the verb.
 *
 * @param request  the servlet's request information
 * @param response the servlet's response information
 * @throws IOException an I/O error occurred
 *//*from  ww  w . ja v a 2  s .  c  om*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Map attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    //      log.debug("attributes=" + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    Map serverVerbs = ServerVerb.getVerbs(properties);
    Map extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    // try {
    request.setCharacterEncoding("UTF-8");
    // } catch (UnsupportedEncodingException e) {
    // e.printStackTrace();
    // throw new IOException(e.getMessage());
    // }
    Date then = null;
    if (monitor)
        then = new Date();
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        System.out.println("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            System.out.print(headerName);
            System.out.print(": ");
            System.out.println(request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || (userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                        /* && userAgent.indexOf("netscape/7") == -1 */)) {
                    serverTransformer = transformer;
                }
            }
            String result = getResult(attributes, request, response, serverTransformer, serverVerbs,
                    extensionVerbs, extensionPath);
            // log.debug("result=" + result);

            // if (serverTransformer) { // render on the server
            // response.setContentType("text/html; charset=UTF-8");
            // StringReader stringReader = new StringReader(getResult(request));
            // StreamSource streamSource = new StreamSource(stringReader);
            // StringWriter stringWriter = new StringWriter();
            // transformer.transform(streamSource, new StreamResult(stringWriter));
            // result = stringWriter.toString();
            // } else { // render on the client
            // response.setContentType("text/xml; charset=UTF-8");
            // result = getResult(request);
            // }

            Writer out = getWriter(request, response);
            out.write(result);
            out.close();
        } catch (FileNotFoundException e) {
            if (debug) {
                e.printStackTrace();
                System.out.println("SC_NOT_FOUND: " + e.getMessage());
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (TransformerException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (OAIInternalServerError e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (SocketException e) {
            System.out.println(e.getMessage());
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        //Runtime rt = Runtime.getRuntime();
        //System.out.println(rt.freeMemory() + "/" + rt.totalMemory() + " " + ((new Date()).getTime() - then.getTime()) + "ms: " + reqUri.toString());
    }
}

From source file:com.esri.gpt.control.rest.ManageDocumentServlet.java

/**
 * Processes the HTTP request./*from   w ww .j a  v a  2s  . c  o  m*/
 * @param request the HTTP request
 * @param response HTTP response
 * @param context request context
 * @param method the method to executeUpdate GET|PUT|POST|DELETE
 * @throws ServletException if the request cannot be handled
 * @throws IOException if an I/O error occurs while handling the request 
 */
private void execute(HttpServletRequest request, HttpServletResponse response, String method)
        throws ServletException, IOException {

    RequestContext context = null;
    try {
        String msg = "HTTP " + method + ", " + request.getRequestURL().toString();
        if ((request.getQueryString() != null) && (request.getQueryString().length() > 0)) {
            msg += "?" + request.getQueryString();
        }
        getLogger().fine(msg);

        String sEncoding = request.getCharacterEncoding();
        if ((sEncoding == null) || (sEncoding.trim().length() == 0)) {
            request.setCharacterEncoding("UTF-8");
        }
        context = RequestContext.extract(request);

        //redirect to new method for list parameter without any authentication
        if (method.equals("GET") && request.getParameter("list") != null) {
            this.executeGetList(request, response, context);
            return;
        }
        if (method.equals("GET") && request.getParameter("download") != null) {
            this.executeGetPackage(request, response, context);
            return;
        }

        /// estabish the publisher
        StringAttributeMap params = context.getCatalogConfiguration().getParameters();
        String autoAuthenticate = Val.chkStr(params.getValue("BaseServlet.autoAuthenticate"));
        if (!autoAuthenticate.equalsIgnoreCase("false")) {
            Credentials credentials = getCredentials(request);
            if (credentials != null) {
                this.authenticate(context, credentials);
            }
        }
        Publisher publisher = new Publisher(context);

        // executeUpdate the appropriate action
        if (method.equals("GET")) {
            this.executeGet(request, response, context, publisher);
        } else if (method.equals("POST")) {
            this.executePost(request, response, context, publisher);
        } else if (method.equals("PUT")) {
            this.executePut(request, response, context, publisher);
        } else if (method.equals("DELETE")) {
            this.executeDelete(request, response, context, publisher);
        }

    } catch (CredentialsDeniedException e) {
        String sRealm = this.getRealm(context);
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (NotAuthorizedException e) {
        String sRealm = this.getRealm(context);
        response.setHeader("WWW-Authenticate", "Basic realm=\"" + sRealm + "\"");
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (ValidationException e) {
        String sMsg = e.toString();
        if (sMsg.contains("XSD violation.")) {
            sMsg = "XSD violation.";
        } else if (sMsg.contains("Invalid metadata document.")) {
            sMsg = "Invalid metadata document.";
        } else {
            sMsg = "Invalid metadata document.";
        }
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            FacesContextBroker fcb = new FacesContextBroker(request, response);
            MessageBroker msgBroker = fcb.extractMessageBroker();

            ArrayList<String> validationMessages = new ArrayList<String>();
            e.getValidationErrors().buildMessages(msgBroker, validationMessages, true);

            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: 409,\r\n");
            sb.append("errors: [\r\n");
            for (int i = 0; i < validationMessages.size(); i++) {
                if (i > 0) {
                    sb.append(",\r\n");
                }
                sb.append("\"").append(Val.escapeStrForJson(validationMessages.get(i))).append("\"");
            }
            if (validationMessages.size() > 0) {
                sb.append("\r\n");
            }
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else {
            response.sendError(409, sMsg);
        }
    } catch (ServletException e) {
        String sMsg = e.getMessage();
        int nCode = Val.chkInt(sMsg.substring(0, 3), 500);
        sMsg = Val.chkStr(sMsg.substring(4));
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: ").append(nCode).append(",\r\n");
            sb.append("errors: [\r\n");
            sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else {
            response.sendError(nCode, sMsg);
        }
    } catch (Throwable t) {
        String sMsg = t.toString();
        String json = Val.chkStr(request.getParameter("errorsAsJson"));
        if (json.length() > 0) {
            json = Val.escapeXmlForBrowser(json);
            StringBuilder sb = new StringBuilder();
            sb.append(json).append(" = {\r\n");
            sb.append("message: \"").append(Val.escapeStrForJson(sMsg)).append("\",\r\n");
            sb.append("code: ").append(500).append(",\r\n");
            sb.append("errors: [\r\n");
            sb.append("\"").append(Val.escapeStrForJson(sMsg)).append("\"");
            sb.append("]}");

            LOGGER.log(Level.SEVERE, sb.toString());
            response.getWriter().print(sb.toString());
        } else if (sMsg.contains("The document is owned by another user:")) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "The document is owned by another user.");
        } else {
            //String sErr = "Exception occured while processing servlet request.";
            //getLogger().log(Level.SEVERE,sErr,t);
            //response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
            //    sMsg + sErr);
        }
    } finally {
        if (context != null)
            context.onExecutionPhaseCompleted();
    }
}

From source file:com.extjs.djn.ioc.servlet.BaseDirectJNgineServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    assert request != null;
    assert response != null;

    NDC.push("rid=" + Long.toString(getUniqueRequestId()));
    try {/*from   www  .  j a  v a 2s  .c  o  m*/
        Timer timer = new Timer();
        try {
            attachThreadLocalData(request, response);
            try {
                if (logger.isTraceEnabled()) {
                    String requestInfo = ServletUtils.getDetailedRequestInformation(request);
                    logger.trace("Request info: " + requestInfo);
                }

                response.setContentType("text/html"); // MUST be "text/html" for uploads to work!
                String requestEncoding = request.getCharacterEncoding();
                // If we don't know what the request encoding is, assume it to be UTF-8
                if (StringUtils.isEmpty(requestEncoding)) {
                    request.setCharacterEncoding(EncodingUtils.UTF8);
                }
                response.setCharacterEncoding(EncodingUtils.UTF8);

                RequestType type = getFromRequestContentType(request);
                switch (type) {
                case FORM_SIMPLE_POST:
                    this.processor.processSimpleFormPostRequest(request.getReader(), response.getWriter());
                    break;
                case FORM_UPLOAD_POST:
                    processUploadFormPost(request, response);
                    break;
                case JSON:
                    this.processor.processJsonRequest(request.getReader(), response.getWriter());
                    break;
                case POLL:
                    this.processor.processPollRequest(request.getReader(), response.getWriter(),
                            request.getPathInfo());
                    break;
                }
            } finally {
                detachThreadLocalData();
            }
        } finally {
            timer.stop();
            timer.logDebugTimeInMilliseconds("Total servlet processing time");
        }

    } finally {
        NDC.pop();
    }
}

From source file:org.apache.click.extras.filter.PerformanceFilter.java

/**
 * Perform the filter operation applying any necessary Expire headers and
 * compressing the response content.//from w w  w  .j  av a  2  s  . c  om
 *
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 *
 * @param servletRequest the servlet request
 * @param servletResponse the servlet response
 * @param chain the filter chain
 * @throws IOException if an I/O error occurs
 * @throws ServletException if a servlet error occurs
 */
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {

    if (!configured) {
        loadConfiguration();
    }

    if (!getConfigService().isProductionMode() && !getConfigService().isProfileMode()) {
        chain.doFilter(servletRequest, servletResponse);
        return;
    }

    final HttpServletRequest request = (HttpServletRequest) servletRequest;
    final HttpServletResponse response = (HttpServletResponse) servletResponse;

    final String path = ClickUtils.getResourcePath(request);

    if (isExcludePath(path)) {
        chain.doFilter(servletRequest, servletResponse);
        return;
    }

    // Enable resource versioning in Click
    request.setAttribute(ClickUtils.ENABLE_RESOURCE_VERSION, "true");

    if (useForeverCacheHeader(path)) {
        setHeaderExpiresCache(response, FOREVER_CACHE_MAX_AGE);

    } else if (useConfiguredCacheHeader(path)) {
        setHeaderExpiresCache(response, cacheMaxAge);
    }

    // Set the character set
    String charset = getConfigService().getCharset();
    if (charset != null) {
        try {
            request.setCharacterEncoding(charset);

        } catch (UnsupportedEncodingException ex) {
            String msg = "The character encoding " + charset + " is invalid.";
            getConfigService().getLogService().warn(msg, ex);
        }
    }

    final String realPath = stripResourceVersionIndicator(path);
    final boolean isVersionedResourcePath = (realPath.length() != path.length());

    // Apply response compression
    if (useGzipCompression(request, response, path)) {

        CompressionServletResponseWrapper wrappedResponse = new CompressionServletResponseWrapper(response,
                request);

        wrappedResponse.setCompressionThreshold(compressionThreshold);

        try {
            // If a versioned resource path, forward request to real resource path
            if (isVersionedResourcePath) {
                request.getRequestDispatcher(realPath).forward(request, wrappedResponse);

                // Else chain filter
            } else {
                chain.doFilter(request, wrappedResponse);
            }

        } finally {
            wrappedResponse.finishResponse();
        }

    } else {
        // If a versioned resource path, forward request to real resource path
        if (isVersionedResourcePath) {
            request.getRequestDispatcher(realPath).forward(request, response);

            // Else chain filter
        } else {
            chain.doFilter(request, response);
        }
    }
}

From source file:org.akaza.openclinica.control.core.SecureController.java

License:asdf

private void process(HttpServletRequest request, HttpServletResponse response)
        throws OpenClinicaException, UnsupportedEncodingException {
    request.setCharacterEncoding("UTF-8");
    session = request.getSession();//from w  w w.j  av  a2  s.c om
    // BWP >> 1/8/2008
    try {
        // YW 10-03-2007 <<
        session.setMaxInactiveInterval(Integer.parseInt(SQLInitServlet.getField("max_inactive_interval")));
        String smURL = CoreResources.getField("smURL");
        if (StringUtils.isNotEmpty(smURL)) {

            int index = smURL.indexOf("//");
            String protocol = smURL.substring(0, index) + "//";
            String subDomain = smURL.substring(smURL.indexOf("//") + 2, smURL.indexOf("/", protocol.length()));
            String crossStorageURL = protocol + subDomain + "/hub/hub.html";
            session.setAttribute("crossStorageURL", crossStorageURL);
        }
        // YW >>
    } catch (NumberFormatException nfe) {
        // BWP>>3600 is the datainfo.properties maxInactiveInterval on
        // 1/8/2008
        session.setMaxInactiveInterval(3600);
    }

    // If the session already has a value with key SUPPORT_URL don't reset
    if (session.getAttribute(SUPPORT_URL) == null) {
        session.setAttribute(SUPPORT_URL, SQLInitServlet.getSupportURL());
    }

    // If the session already has a value with key WALKME_URL don't reset
    if (session.getAttribute(WALKME_URL) == null) {
        session.setAttribute(WALKME_URL, CoreResources.getField("walkme.url"));
    }

    // If the session already has a value with key PIWIK_URL don't reset
    if (session.getAttribute(PIWIK_URL) == null) {
        session.setAttribute(PIWIK_URL, CoreResources.getField("piwik.url"));
    }

    ub = (UserAccountBean) session.getAttribute(USER_BEAN_NAME);
    currentStudy = (StudyBean) session.getAttribute("study");
    currentPublicStudy = (StudyBean) session.getAttribute("publicStudy");
    currentRole = (StudyUserRoleBean) session.getAttribute("userRole");

    // Set current language preferences
    Locale locale = LocaleResolver.getLocale(request);
    ResourceBundleProvider.updateLocale(locale);
    resadmin = ResourceBundleProvider.getAdminBundle(locale);
    resaudit = ResourceBundleProvider.getAuditEventsBundle(locale);
    resexception = ResourceBundleProvider.getExceptionsBundle(locale);
    resformat = ResourceBundleProvider.getFormatBundle(locale);
    restext = ResourceBundleProvider.getTextsBundle(locale);
    resterm = ResourceBundleProvider.getTermsBundle(locale);
    resword = ResourceBundleProvider.getWordsBundle(locale);
    respage = ResourceBundleProvider.getPageMessagesBundle(locale);
    resworkflow = ResourceBundleProvider.getWorkflowBundle(locale);

    local_df = I18nFormatUtil.getDateFormat(locale);

    try {
        String userName = request.getRemoteUser();
        // BWP 1/8/08<< the sm variable may already be set with a mock
        // object,
        // from the perspective of
        // JUnit servlets tests
        /*
         * if(sm==null && (!StringUtil.isBlank(userName))) {//check if user logged in, then create a new
         * sessionmanger to
         * get ub //create a new sm in order to get a new ub object sm = new SessionManager(ub, userName); }
         */
        // BWP 01/08 >>
        // sm = new SessionManager(ub, userName);
        sm = new SessionManager(ub, userName, SpringServletAccess.getApplicationContext(context));
        if (ub == null || StringUtils.isEmpty(ub.getName())) {
            UserAccountDAO uDAO = new UserAccountDAO(sm.getDataSource());
            ub = (UserAccountBean) uDAO.findByEmail(userName);
            session.setAttribute("userBean", ub);
        }
        request.setAttribute("userBean", ub);
        StudyDAO sdao = new StudyDAO(sm.getDataSource());
        if (currentPublicStudy == null || currentPublicStudy.getId() <= 0) {
            UserAccountDAO uDAO = new UserAccountDAO(sm.getDataSource());
            ub = (UserAccountBean) uDAO.findByUserName(ub.getName());
            session.setAttribute(USER_BEAN_NAME, ub);
            if (ub.getId() > 0 && ub.getActiveStudyId() > 0) {
                CoreResources.setRequestSchema(request, "public");
                StudyParameterValueDAO spvdao = new StudyParameterValueDAO(sm.getDataSource());
                currentPublicStudy = (StudyBean) sdao.findByPK(ub.getActiveStudyId());

                ArrayList studyParameters = spvdao.findParamConfigByStudy(currentPublicStudy);

                currentPublicStudy.setStudyParameters(studyParameters);

                // set up the panel here, tbh
                panel.reset();
                /*
                 * panel.setData("Study", currentPublicStudy.getName()); panel.setData("Summary",
                 * currentPublicStudy.getSummary());
                 * panel.setData("Start Date", sdf.format(currentPublicStudy.getDatePlannedStart()));
                 * panel.setData("End Date",
                 * sdf.format(currentPublicStudy.getDatePlannedEnd())); panel.setData("Principal Investigator",
                 * currentPublicStudy.getPrincipalInvestigator());
                 */
                session.setAttribute(STUDY_INFO_PANEL, panel);
            } else {
                currentPublicStudy = new StudyBean();
            }
            session.setAttribute("publicStudy", currentPublicStudy);
            request.setAttribute("requestSchema", currentPublicStudy.getSchemaName());
            currentStudy = (StudyBean) sdao.findByUniqueIdentifier(currentPublicStudy.getIdentifier());
            if (currentStudy != null) {
                currentStudy.setParentStudyName(currentPublicStudy.getParentStudyName());
                StudyConfigService scs = new StudyConfigService(sm.getDataSource());
                if (currentStudy.getParentStudyId() <= 0) {// top study
                    scs.setParametersForStudy(currentStudy);

                } else {
                    // YW <<
                    currentStudy.setParentStudyName(
                            ((StudyBean) sdao.findByPK(currentStudy.getParentStudyId())).getName());
                    // YW >>
                    scs.setParametersForSite(currentStudy);
                }
            }
            request.setAttribute("requestSchema", "public");
            session.setAttribute("study", currentStudy);
        } else if (currentPublicStudy.getId() > 0) {
            // YW 06-20-2007<< set site's parentstudy name when site is
            // restored
            if (currentPublicStudy.getParentStudyId() > 0) {
                currentPublicStudy.setParentStudyName(
                        ((StudyBean) sdao.findByPK(currentPublicStudy.getParentStudyId())).getName());
                request.setAttribute("requestSchema", currentPublicStudy.getSchemaName());
                currentStudy.setParentStudyName(
                        ((StudyBean) sdao.findByPK(currentStudy.getParentStudyId())).getName());
                request.setAttribute("requestSchema", "public");
            }
            // YW >>
        }

        if (currentPublicStudy.getParentStudyId() > 0) {
            /*
             * The Role decription will be set depending on whether the user logged in at study lever or site level.
             * issue-2422
             */
            List roles = Role.toArrayList();
            for (Iterator it = roles.iterator(); it.hasNext();) {
                Role role = (Role) it.next();
                switch (role.getId()) {
                case 2:
                    role.setDescription("site_Study_Coordinator");
                    break;
                case 3:
                    role.setDescription("site_Study_Director");
                    break;
                case 4:
                    role.setDescription("site_investigator");
                    break;
                case 5:
                    role.setDescription("site_Data_Entry_Person");
                    break;
                case 6:
                    role.setDescription("site_monitor");
                    break;
                case 7:
                    role.setDescription("site_Data_Entry_Person2");
                    break;
                default:
                    // logger.info("No role matched when setting role description");
                }
            }
        } else {
            /*
             * If the current study is a site, we will change the role description. issue-2422
             */
            List roles = Role.toArrayList();
            for (Iterator it = roles.iterator(); it.hasNext();) {
                Role role = (Role) it.next();
                switch (role.getId()) {
                case 2:
                    role.setDescription("Study_Coordinator");
                    break;
                case 3:
                    role.setDescription("Study_Director");
                    break;
                case 4:
                    role.setDescription("Investigator");
                    break;
                case 5:
                    role.setDescription("Data_Entry_Person");
                    break;
                case 6:
                    role.setDescription("Monitor");
                    break;
                default:
                    // logger.info("No role matched when setting role description");
                }
            }
        }

        if (currentRole == null || currentRole.getId() <= 0) {
            // if (ub.getId() > 0 && currentPublicStudy.getId() > 0) {
            // if current study has been "removed", current role will be
            // kept as "invalid" -- YW 06-21-2007
            if (ub.getId() > 0 && currentPublicStudy.getId() > 0
                    && !currentPublicStudy.getStatus().getName().equals("removed")) {
                currentRole = ub.getRoleByStudy(currentPublicStudy.getId());
                if (currentPublicStudy.getParentStudyId() > 0) {
                    // Checking if currentPublicStudy has been removed or not will
                    // ge good enough -- YW 10-17-2007
                    StudyUserRoleBean roleInParent = ub.getRoleByStudy(currentPublicStudy.getParentStudyId());
                    // inherited role from parent study, pick the higher
                    // role
                    currentRole.setRole(Role.max(currentRole.getRole(), roleInParent.getRole()));
                }
                // logger.info("currentRole:" + currentRole.getRoleName());
            } else {
                currentRole = new StudyUserRoleBean();
            }
            session.setAttribute("userRole", currentRole);
        }
        // YW << For the case that current role is not "invalid" but current
        // active study has been removed.
        else if (currentRole.getId() > 0 && (currentPublicStudy.getStatus().equals(Status.DELETED)
                || currentPublicStudy.getStatus().equals(Status.AUTO_DELETED))) {
            currentRole.setRole(Role.INVALID);
            currentRole.setStatus(Status.DELETED);
            session.setAttribute("userRole", currentRole);
        }
        // YW 06-19-2007 >>

        request.setAttribute("isAdminServlet", getAdminServlet());

        this.request = request;
        this.response = response;

        // java.util.Enumeration en_session = session.getAttributeNames();
        // java.util.Enumeration en_request = request.getAttributeNames();
        //
        // // logging added to find problems with adding subjects, tbh
        // 102007
        // String ss_names = "session names: ";
        // while (en_session.hasMoreElements()) {
        // ss_names += " - " + en_session.nextElement();
        // }
        // logger.info(ss_names);
        //
        // // also added tbh, 102007
        // String rq_names = "request names: ";
        // while (en_request.hasMoreElements()) {
        // rq_names += " - " + en_request.nextElement();
        // }
        // logger.info(rq_names);
        if (!request.getRequestURI().endsWith("ResetPassword")) {
            passwdTimeOut();
        }
        request.setAttribute("requestSchema", getRequestSchema(request));
        mayProceed();
        // pingJobServer(request);
        processRequest();
    } catch (InconsistentStateException ise) {
        ise.printStackTrace();
        logger.warn("InconsistentStateException: org.akaza.openclinica.control.SecureController: "
                + ise.getMessage());

        addPageMessage(ise.getOpenClinicaMessage());
        forwardPage(ise.getGoTo());
    } catch (InsufficientPermissionException ipe) {
        ipe.printStackTrace();
        logger.warn("InsufficientPermissionException: org.akaza.openclinica.control.SecureController: "
                + ipe.getMessage());

        // addPageMessage(ipe.getOpenClinicaMessage());
        forwardPage(ipe.getGoTo());
    } catch (OutOfMemoryError ome) {
        ome.printStackTrace();
        long heapSize = Runtime.getRuntime().totalMemory();
        session.setAttribute("ome", "yes");
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(SecureController.getStackTrace(e));

        forwardPage(Page.ERROR);
    }
}

From source file:org.logger.event.web.service.EventServiceImpl.java

@Override
@Async/*w w  w .j  a  v a 2s .  c  o m*/
public void eventLogging(HttpServletRequest request, HttpServletResponse response, String fields,
        String apiKey) {
    boolean isValid = ensureValidRequest(request, response);
    if (!isValid) {
        sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, INVALID_API_KEY);
        return;
    }
    EventData eventData = null;
    JsonElement jsonElement = null;
    JsonArray eventJsonArr = null;
    if (!fields.isEmpty()) {

        try {
            // validate JSON
            jsonElement = new JsonParser().parse(fields);
            eventJsonArr = jsonElement.getAsJsonArray();
        } catch (JsonParseException e) {
            // Invalid.
            sendErrorResponse(request, response, HttpServletResponse.SC_BAD_REQUEST, INVALID_JSON);
            logger.error(INVALID_JSON, e);
            return;
        }

    } else {
        sendErrorResponse(request, response, HttpServletResponse.SC_BAD_REQUEST, BAD_REQUEST);
        return;
    }

    try {
        request.setCharacterEncoding("UTF-8");
        Long timeStamp = System.currentTimeMillis();
        String userAgent = request.getHeader("User-Agent");

        String userIp = request.getHeader("X-FORWARDED-FOR");
        if (userIp == null) {
            userIp = request.getRemoteAddr();
        }

        for (JsonElement eventJson : eventJsonArr) {
            JsonObject eventObj = eventJson.getAsJsonObject();
            String eventString = eventObj.toString();
            if (eventObj.get(VERSION) == null) {
                eventData = new EventData();
                eventData.setStartTime(timeStamp);
                eventData.setEndTime(timeStamp);
                eventData.setApiKey(apiKey);
                eventData.setUserAgent(userAgent);
                eventData.setUserIp(userIp);
                eventData.setEventSource(EVENT_SOURCE);
                eventData.setFields(eventString);
                createEventData(eventData, eventObj);
            } else {
                Event event = gson.fromJson(eventObj, Event.class);
                JSONObject field = new JSONObject(eventString);
                if (StringUtils.isNotBlank(event.getUser())) {
                    JSONObject user = new JSONObject(event.getUser());
                    user.put(USER_IP, userIp);
                    user.put(USER_AGENT, userAgent);
                    field.put(USER, user.toString());
                }
                event.setFields(field.toString());
                event.setApiKey(apiKey);
                processMessage(event);
            }
        }
    } catch (Exception e) {
        logger.error("Exception : ", e);
    }

}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb.//w  w w .  j av a  2s  .  c  o m
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

From source file:cms.service.app.ServiceController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HashMap<String, String> userdata;
    AccessToken access = null;/* www. ja va2s  . co  m*/
    AccessToken regaccess = null;
    RequestDispatcher rd;
    String strNextPage = null;
    boolean isvalidtoken = false;
    boolean subscription = false;
    String reguser = "registration";
    String regpassword = "reg$56*123";
    String baseurl = request.getRequestURL().toString().split("/service")[0];
    String remotehost = request.getRemoteHost();
    String remoteaddress = request.getRemoteAddr();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String useraction = request.getParameter("useraction");
    String adminuser = request.getParameter("adminuser");
    String usertoken = request.getParameter("usertoken");
    String servicekey = request.getParameter("servicekey");
    String amount = request.getParameter("amount");
    String objid = request.getParameter("refobjid");
    String description = request.getParameter("description");
    String leadactions = "campaign whitepapers contactus training";
    String sendreference = request.getParameter("sendreference");
    ;

    Date date = new Date();

    //set remote address
    request.setCharacterEncoding("UTF-8");

    /*if(custom!=null&&!custom.equals("")){
      custom="dan@softlean.com#-1624640437#127.0.0.1";
      item_name="xyx";
      item_number="899";
    }
            
    subscription=(custom!=null&&!custom.equals(""))?true:false;
    logger.info(date.toString()+":-subscription="+subscription+" custom="+custom);
    if(subscription){
            
      custret=custom.split("-");
      if(custret.length==6)
      username=custret[3];
      usertoken=custret[4];
             
      tu.updatePayment(custret);
    }
    */
    //first verify remote client whether the request is from same client
    if (!tu.isEmptyValue(servicekey)) {
        try {
            String val = new String(Base64Util.decode(servicekey.getBytes()));
            logger.info("servicekey=" + val);
            if (!tu.isEmptyValue(val)) {
                String[] items = val.split(CONST.IPSEPERATOR);
                if (items.length >= 2) {
                    username = items[0];
                    password = items[1];
                }
                if (items.length == 3) {
                    useraction = items[2];
                    if (useraction.equalsIgnoreCase("campaign") && tu.isEmptyValue(sendreference)) {
                        sendreference = "2";
                    }
                }

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    //logger.info("\n"+date.toString()+":-username="+username+ " password="+password+" useraction="+useraction);

    if (CONST.GENERATE_LOG) {
        logger.info("\n" + date.toString() + ":-URI=" + request.getRequestURI());
        logger.info("\n" + date.toString() + ":-Request Remote address=" + remoteaddress + " Remote Host="
                + remotehost);
    }
    //Identify the current page as login page
    if (!tu.isEmptyValue(username) && !tu.isEmptyValue(password)) {

        //Do not check license for hosting solution
        access = m_service.verifyLogin(username, password, remoteaddress);

    } else {
        regaccess = m_service.verifyLogin(reguser, regpassword, remoteaddress);

    }

    if (access != null && tu.isEmptyValue(useraction)) {
        logger.info("\n" + date.toString() + " Loged in User:=" + username + " " + ":-Assigned Token="
                + access.getToken() + ":-Assigned Modules=" + access.getModules());
        //access token is appended with Client IP in the indexpage
        strNextPage = "/src/index.jsp?username=" + username + "&firstname=" + access.getFirstname()
                + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR
                + username + "&baseurl=" + baseurl + "&modules=" + access.getModules();
    } else if (access != null && !tu.isEmptyValue(useraction)
            && leadactions.toLowerCase().contains(useraction.toLowerCase())) {
        strNextPage = "/src/campaign/" + useraction + ".jsp?username=" + username + "&firstname="
                + access.getFirstname() + "&usertoken=" + access.getToken() + CONST.IPSEPERATOR + remoteaddress
                + CONST.IPSEPERATOR + username + "&baseurl=" + baseurl + "&campaignid=" + objid
                + "&sendreference=" + sendreference;
        //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage);
        //}else if(access!=null && !tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("whitepapers")){  
        //strNextPage="/src/campaign/white_paper.jsp?username="+username+"&firstname="+access.getFirstname()+"&usertoken="+access.getToken()+CONST.IPSEPERATOR+remoteaddress+CONST.IPSEPERATOR+username+"&baseurl="
        //         +baseurl+"&campaignid="+objid;
        //logger.info("\n"+date.toString()+"strNextPage:="+strNextPage);     
    } else if (subscription) {
        userdata = m_service.verifyUserToken(usertoken);
        isvalidtoken = usertoken != null && !usertoken.equals("") && userdata != null;
        if (isvalidtoken) {
            strNextPage = "/src/index.jsp?username=" + username + "&usertoken=" + usertoken + "&baseurl="
                    + baseurl;
        }
    } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("missingpassword")) {

        strNextPage = "/src/password.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress
                + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl;
    } else if (!tu.isEmptyValue(useraction) && useraction.equalsIgnoreCase("demoregistration")) {

        strNextPage = "/src/demologin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress
                + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl;

    } else if (!tu.isEmptyValue(adminuser) && adminuser.equals("sa")) {
        strNextPage = "/src/admin.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress
                + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl;

    } else if (!tu.isEmptyValue(amount) && !tu.isEmptyValue(objid)) {
        userdata = m_service.verifyUserToken(usertoken);
        if (userdata != null && !userdata.isEmpty()) {
            strNextPage = "/src/java_sim/payment.jsp?email=" + username + "&objid=" + objid + "&amount="
                    + amount + "&description=" + description;

        }

    } else if (regaccess != null) {
        strNextPage = "/src/login.jsp?token=" + regaccess.getToken() + CONST.IPSEPERATOR + remoteaddress
                + CONST.IPSEPERATOR + reguser + "&baseurl=" + baseurl;
    } else {
        strNextPage = "/src/error.jsp?token=null" + CONST.IPSEPERATOR + remoteaddress + CONST.IPSEPERATOR
                + reguser + "&baseurl=" + baseurl;
    }

    if (CONST.GENERATE_LOG) {
        logger.info("\n" + date.toString() + ":-Mapped Filename : " + strNextPage);
    }
    if (!strNextPage.equals("")) {
        rd = m_autoContext.getRequestDispatcher(strNextPage);
        // Forward the request to the target page
        try {
            if (rd != null) {

                rd.forward(request, response);
            }
        } catch (Exception e) {

            logger.info("ControllerServlet.doPost():  error in rd.forward");
            e.printStackTrace();
        }
    } else {
        // This should be logged.
        logger.info("Next Page is null");
        super.doPost(request, response);
    }

}