Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:edu.harvard.i2b2.fhir.server.ws.I2b2FhirWS.java

public Response getQueryResultCore(String resourceName, String basePath, String requestUri, String queryString,
        String rawRequestUrl, List<String> includeResources, String filterf, String acceptHeader,
        HttpHeaders headers, HttpSession session, String serverUriPath) throws IOException {

    String msg = null;/*from w  w  w .java2  s  .c o  m*/
    String mediaType = null;
    Bundle s = null;

    MetaResourceDb md = new MetaResourceDb();

    logger.debug("got request parts: " + requestUri + "?" + queryString);
    logger.trace("basePath:" + basePath);

    try {
        logger.info("Query string:" + queryString);

        String head = "";
        for (String h : headers.getRequestHeaders().keySet()) {
            head += "Header->" + h + ":" + headers.getRequestHeader(h);

        }
        logger.info(head);

        // md = I2b2Helper.getMetaResourceDb(session, sbb);

        Class c = FhirUtil.getResourceClass(resourceName);

        logger.trace("rawRequestUrl:" + rawRequestUrl);
        // String basePath =rawRequestUrl.split(resourceName)[0];
        logger.debug("session id:" + session.getId());

        authService.authenticateSession(
                headers.getRequestHeader(AuthenticationFilter.AUTHENTICATION_HEADER).get(0), session);

        s = I2b2Helper.parsePatientIdToFetchPDO(session, requestUri, queryString, c.getSimpleName(), service,
                ppmMgr, null);

        if (!(c.equals("$everything"))) {

            if (FhirHelper.isPatientDependentResource(c)) {
                md.addBundle(s);
            } else {
                FhirHelper.loadTestResources(md);
            }
            logger.info("running filter...");
            s = FhirUtil.getResourceBundle(md.getAll(c), basePath, "url");
        }
        logger.info("running sophisticated query for:" + queryString);

        if (queryString != null) {
            String fhirQuery = c.getSimpleName() + "?" + queryString;

            // optimization to avoid query search on patient id
            if (false// XXX
                    && !c.equals(Patient.class)) {
                fhirQuery = fhirQuery.replaceAll("\\?patient=(\\d+)", "");
                fhirQuery = fhirQuery.replaceAll("\\?subject=(\\d+)", "");
                logger.trace("bypassing sophisticated query");
            } else {
                s = queryManager.runQueryEngine(fhirQuery, s, basePath);
            }
        }

        logger.info("including...._include:" + includeResources.toString());
        if (s.getEntry().size() > 0) {
            List<Resource> list = md.getIncludedResources(c, FhirUtil.getResourceListFromBundle(s),
                    includeResources);
            logger.trace("includedListsize:" + list.size());
            logger.trace("basePath:" + basePath);
            s = FhirUtil.getResourceBundle(list, basePath, "url");
        }

        s.getLink().add(FhirUtil.createBundleLink("self", serverUriPath + requestUri + "?"
                + ((queryString != null) ? queryString.replaceAll("&page=\\d+", "") : "")));

        // logger.info("getting bundle string..."+JAXBUtil.toXml(s));
        // logger.info("size of db:" + md.getSize());

        int pageNum = 1;
        int countNum = 20;
        if (queryString != null) {
            Pattern p = Pattern.compile(".*page=(\\d+).*");
            Matcher m = p.matcher(queryString);
            if (m.matches()) {
                String pageNumStr = m.group(1);
                logger.info("pageNum=" + pageNumStr);
                try {
                    pageNum = Integer.valueOf(pageNumStr, 10);
                } catch (Exception e) {
                    throw new FhirServerException(
                            "page parameter should be a number: Current value is :" + pageNumStr);
                }
            }

            p = Pattern.compile(".*_count=(\\d+).*");
            m = p.matcher(queryString);
            if (m.matches()) {
                String countNumStr = m.group(1);
                logger.info("countNum=" + countNumStr);
                try {
                    countNum = Integer.valueOf(countNumStr, 10);
                } catch (Exception e) {
                    throw new FhirServerException(
                            "count parameter should be a number: Current value is :" + countNumStr);
                }
            }

        }
        s = FhirUtil.pageBundle(s, countNum, pageNum);

        logger.info("returning response..." + JAXBUtil.toXml(s));
        if (acceptHeader.contains("application/json") || acceptHeader.contains("application/json+fhir")) {
            msg = FhirUtil.bundleToJsonString(s);
            mediaType = "application/json+fhir";
        } else {
            msg = JAXBUtil.toXml(s);
            mediaType = "application/xml+fhir";
        }
        msg = I2b2Helper.removeSpace(msg);
        logger.info("acceptHeader:" + acceptHeader);
        return Response.ok().type(mediaType).header("session_id", session.getId()).entity(msg).build();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        return Response
                .ok(FhirHelper.generateOperationOutcome(e.getMessage(), IssueTypeList.EXCEPTION,
                        IssueSeverityList.FATAL))
                .header("xreason", e.getMessage()).header("session_id", session.getId()).build();

    }

}

From source file:Controller.UserController.java

@RequestMapping(value = "/AccountInfo")
public String getAccountInfo(HttpServletRequest request) {
    try {/*from  ww  w .  j  av  a  2 s  . com*/
        HttpSession session = request.getSession(true);
        AccountSession account = (AccountSession) session.getAttribute("account");
        TripperDTO tripper = tripperService.getTripperAccount(account.getId());
        Gson gson = new Gson();
        List<CountryDTO> countryList = commonService.getAllCountry();
        request.setAttribute("countryList", gson.toJson(countryList));
        request.setAttribute("AccountInfo", gson.toJson(tripper));
        request.setAttribute("page", "Info");
        return "tripper/accountInfo";
    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - getAccountInfo\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:gwtupload.server.UploadServlet.java

/**
 * Method executed each time the client asks the server for the progress status.
 * It uses the listener to generate the adequate response
 *
 * @param request//from w  w  w .j  a v  a  2 s. c  om
 * @param fieldname
 * @return a map of tag/values to be rendered
 */
protected Map<String, String> getUploadStatus(HttpServletRequest request, String fieldname,
        Map<String, String> ret) {
    perThreadRequest.set(request);
    HttpSession session = request.getSession();

    if (ret == null) {
        ret = new HashMap<String, String>();
    }

    long currentBytes = 0;
    long totalBytes = 0;
    long percent = 0;
    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFinished()) {

        } else if (listener.getException() != null) {
            if (listener.getException() instanceof UploadCanceledException) {
                ret.put(TAG_CANCELED, "true");
                ret.put(TAG_FINISHED, TAG_CANCELED);
                logger.error("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                        + " canceled by the user after " + listener.getBytesRead() + " Bytes");
            } else {
                String errorMsg = getMessage("server_error", listener.getException().getMessage());
                ret.put(TAG_ERROR, errorMsg);
                ret.put(TAG_FINISHED, TAG_ERROR);
                logger.error("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                        + " finished with error: " + listener.getException().getMessage());
            }
        } else {
            currentBytes = listener.getBytesRead();
            totalBytes = listener.getContentLength();
            percent = totalBytes != 0 ? currentBytes * 100 / totalBytes : 0;
            // logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname + " " + currentBytes + "/" + totalBytes + " " + percent + "%");
            ret.put(TAG_PERCENT, "" + percent);
            ret.put(TAG_CURRENT_BYTES, "" + currentBytes);
            ret.put(TAG_TOTAL_BYTES, "" + totalBytes);
        }
    } else if (getMySessionFileItems(request) != null) {
        if (fieldname == null) {
            ret.put(TAG_FINISHED, "ok");
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + request.getQueryString()
                    + " finished with files: " + session.getAttribute(getSessionFilesKey(request)));
        } else {
            List<FileItem> sessionFiles = getMySessionFileItems(request);
            for (FileItem file : sessionFiles) {
                if (file.isFormField() == false && file.getFieldName().equals(fieldname)) {
                    ret.put(TAG_FINISHED, "ok");
                    ret.put(UConsts.PARAM_FILENAME, fieldname);
                    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                            + " finished with files: " + session.getAttribute(getSessionFilesKey(request)));
                }
            }
        }
    } else {
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: no listener in session");
        ret.put("wait", "listener is null");
    }
    if (ret.containsKey(TAG_FINISHED)) {
        removeCurrentListener(request);
    }
    perThreadRequest.set(null);
    return ret;
}

From source file:com.tecapro.inventory.common.action.BaseAction.java

@SuppressWarnings("unchecked")
@Override//from ww  w .  j  a  v a  2s  .c  o m
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    BaseForm zform = (BaseForm) form;

    long startTime = startLog(mapping, zform);

    Object objAction = zform.getObjAction();
    InfoValue info = zform.getValue().getInfo();

    byte[] serializeData = null;
    String result = null;
    boolean hasError = false;
    String errorCode = "";
    HashMap<String, List<HashMap<String, Boolean>>> checkListBak = null;

    try {

        /*Detect device*/
        request.setAttribute(Constants.Device.IS_TABLET, detectDevice(request).isTablet());

        String systemError = request.getParameter("system_error");
        if (!strUtil.isNull(systemError) && (Constants.SYSTEM_ERROR_CODE.equals(systemError)
                || Constants.SESSION_TIMEOUT_CODE.equals(systemError))) {

            setError(zform, systemError, null, new ArrayList<String>(), request);
            request.setAttribute(mapping.getName(), zform);

            return mapping.findForward(SYSTEM_ERROR);
        }

        serializeData = (zform.getValueBase64() != null && !"".equals(zform.getValueBase64()))
                ? zform.getValueBase64().getBytes()
                : commonUtil.serialize(zform.getValue());

        // Initialization for uploading and downloading
        initFile(zform);

        // If the session is invalid, I will transition to login screen
        if (!validSession(zform, request, mapping)) {

            setError(zform, Constants.SESSION_TIMEOUT_CODE, null, new ArrayList<String>(), request);
            request.setAttribute(mapping.getName(), zform);

            // check request ajax
            if (Constants.REQUEST_AJAX.equals(zform.getType())) {
                request.setAttribute("type", Constants.REQUEST_AJAX);
                throw new MSException(Constants.SESSION_TIMEOUT_CODE, new String[] {});
            }

            return mapping.findForward(SYSTEM_ERROR);
        } else {

            // check request invalid
            if (isNotAcceptAction(request)) {
                response.sendRedirect(request.getContextPath() + INDEX_PAGE);
                return null;
            }

            copyDataToInfoValue(zform, request);
        }
        // check login
        if (!(mapping.getPath().equalsIgnoreCase("/Login_init")
                || mapping.getPath().equalsIgnoreCase("/Login_login"))) {
            ActionForward actionForward = null;
            result = LOGIN;
            if (info.getUserInfo().getUsername() == null || info.getUserInfo().getUsername().equals("")) {
                // Create action forward
                actionForward = createActionForward(result, request, mapping, zform);
                zform.setPath(actionForward.getPath());

                endLog(mapping, zform, startTime);
                ActionRedirect redirect = new ActionRedirect(actionForward);
                if (!strUtil.isNull(info.getWinName())) {
                    redirect.addParameter(PARAM_WINDOW_NAME, info.getWinName());
                }
                return redirect;
            }
        }
        // check download request
        if (checkDownloadRequest(zform, request, response)) {
            endLog(mapping, zform, startTime);
            return null;
        } else {

            // copy file to work folder
            copyTempFile(form, zform);

            // get remote ip address
            // userInfo.setIpAddress(remoteAddressUtil.getIpddress(request));

            // Form validation
            if (mapping.getValidate()) {

                result = checkValidate(mapping, form, zform, request, objAction, serializeData);
            }

            if (!ERROR_FORWARD.equals(result)) {

                // set error flag is true
                zform.setErrorFlag(false);
                // clear info message
                info.getInfoMsg().clear();

                // process for paging
                processPagingBeforeAction(info, request);

                String[] inputs = (String[]) request.getParameterMap().get(PARAM_WINDOW_NAME);
                if (inputs != null && !strUtil.isNull((String) inputs[0])) {
                    info.setWinName((String) inputs[0]);
                }

                // execute method logic
                result = ((DelegateAction) objAction).execute(info);

                // process for paging
                processPagingAfterAction(info, request);

                // copy info message to BaseForm
                zform.setInfoMsg(info.getInfoMsg());

                // build error message set from logic
                String ret = createErrorFromLogic(zform, serializeData, request);
                if (ret != null && !"".equals(ret) && !SUCCESS_FORWARD.equals(ret)) {
                    result = ret;
                }
            } else {
                // set error flag is true
                zform.setErrorFlag(true);
            }

            if (!ERROR_FORWARD.equals(result)) {
                changeSession(zform, request, mapping);
            }

            // If the file name when download is set from business, the download process
            FileInfoValue fileDown = info.getFile().get(0);

            if (!ERROR_FORWARD.equals(result) && fileDown != null && fileDown.getDownloadFileName() != null
                    && !"".equals(fileDown.getDownloadFileName())) {
                if (!fileDown.getDownloadAfter()) {
                    downloadFile(zform, response);
                    endLog(mapping, zform, startTime);
                    return null;
                } else {
                    fileDown.setDownloadAfter(false);
                    HttpSession session = request.getSession(false);

                    // set fileName of user into http request
                    String dataFile = fileDown.getDownloadFileName();
                    dataFile = session.getId() + DIVIDER_KEY + dataFile;
                    request.setAttribute(Constants.DOWNLOAD_KEY, new String(commonUtil.serialize(dataFile)));
                }
            }
        }
    } catch (Exception ex) {

        result = ERROR_FORWARD;

        // set error flag is true
        zform.setErrorFlag(true);

        if (ex instanceof MSException || ex.getCause() instanceof MSException) {
            String message = "";
            if (ex instanceof DBException) {
                errorLog(zform, request, ex, "execute");
                message = msgUtil.getMessage(((MSException) ex).getCode(), ((MSException) ex).getParam());
            } else if (ex instanceof MSException) {
                message = msgUtil.getMessage(((MSException) ex).getCode(), ((MSException) ex).getParam());
            } else {
                message = msgUtil.getMessage(((MSException) ex.getCause()).getCode(),
                        ((MSException) ex.getCause()).getParam());
            }
            logUtil.infoLog(LOG, BaseAction.class.getSimpleName(), "execute", info, message);

            try {
                result = createErrorMessage(zform, ex, serializeData, request);
            } catch (Exception ex2) {
                hasError = true;
            }
        } else {
            hasError = true;
        }

        if (hasError) {
            errorLog(zform, request, ex, "execute");
            if (ex.getCause() instanceof MSException) {
                errorCode = ((MSException) ex.getCause()).getCode();
            } else if (ex instanceof MSException) {
                errorCode = ((MSException) ex).getCode();
            }
            if ("".equals(errorCode)) {
                errorCode = Constants.SYSTEM_ERROR_CODE;
            }
        }
    } finally {
        try {

            if (Constants.REQUEST_AJAX.equals(zform.getType())) {
                // backup checklist
                checkListBak = (HashMap<String, List<HashMap<String, Boolean>>>) info.getItem().getCheckList()
                        .clone();
            }

            info.getItem().getCheckList().clear();

            // If the file upload is done, I want to delete the temporary files when uploading
            if (form.getMultipartRequestHandler() != null) {
                deleteUploadFile(zform);
            }

            // reset data to after submit
            if (isResetData && info.getResetFlag()) {
                resetData(zform, serializeData, request);
            }
        } catch (Exception ex) {
            logUtil.infoLog(LOG, BaseAction.class.getSimpleName(), "execute", info, ex);
        }
        info.setResetFlag(true);
        //if (ex instanceof Exception) {
        if (hasError) {
            msgUtil.resetErrorList();

            // add message error code
            if (!strUtil.isNull(errorCode)) {
                setError(zform, errorCode, null, null, request);
            }

            result = SYSTEM_ERROR;
        }
    }

    ActionForward forward = null;

    // print data JSON for request AJAX
    if (Constants.REQUEST_AJAX.equals(zform.getType())) {

        // Set header info
        response.setContentType(Constants.CONTENT_TYPE_AJAX);
        response.setCharacterEncoding(Constants.Text.UTF_8);
        PrintWriter out = response.getWriter();

        // get JSON data
        Object objValue = zform.getValue();

        // set checlist
        if (checkListBak != null) {
            ((InfoValueIF) objValue).getInfo().getItem().setCheckList(checkListBak);
        }
        Method method = objValue.getClass().getSuperclass().getDeclaredMethod("getJsonData");
        Object jsonData = method.invoke(objValue);

        String jsonString = "";
        Gson gson = new Gson();

        // create data JSON to response
        Map<String, Object> mapData = new HashMap<String, Object>();
        mapData.put("paging", getPaging(zform, request));
        mapData.put("valueBase64", new String(commonUtil.serialize((InfoValueIF) objValue)));

        // check error
        if (!strUtil.isNull(zform.getError().getErrorId())) {
            mapData.put("value", zform.getError());
        } else if (!strUtil.isNull(jsonData)) {
            mapData.put("value", jsonData);
        }

        jsonString = gson.toJson(mapData);
        out.print(strUtil.isNull(jsonString) ? "" : jsonString);
        out.flush();
        out.close();

        endLog(mapping, zform, startTime);
        return forward;
    } else {

        // Create action forward
        forward = createActionForward(result, request, mapping, zform);
        zform.setPath(forward.getPath());

        endLog(mapping, zform, startTime);
        if (!forward.getRedirect()) {
            return forward;
        }

        ActionRedirect redirect = new ActionRedirect(forward);
        if (!strUtil.isNull(info.getWinName())) {
            redirect.addParameter(PARAM_WINDOW_NAME, info.getWinName());
        }

        return redirect;
    }
}

From source file:org.apache.accumulo.monitor.servlets.ShellServlet.java

@Override
protected void pageBody(HttpServletRequest req, HttpServletResponse response, StringBuilder sb)
        throws IOException {
    HttpSession session = req.getSession(true);
    final String CSRF_TOKEN;
    if (null == session.getAttribute(CSRF_KEY)) {
        // No token, make one
        CSRF_TOKEN = UUID.randomUUID().toString();
        session.setAttribute(CSRF_KEY, CSRF_TOKEN);
    } else {/* w  w  w  .  jav a  2 s .  co m*/
        // Pull the token out of the session
        CSRF_TOKEN = (String) session.getAttribute(CSRF_KEY);
        if (null == CSRF_TOKEN) {
            throw new RuntimeException("No valid CSRF token exists in session");
        }
    }

    String user = (String) session.getAttribute("user");
    if (user == null) {
        // user attribute is null, check to see if username and password are passed as parameters
        user = req.getParameter("user");
        String pass = req.getParameter("pass");
        String mock = req.getParameter("mock");
        if (user == null || pass == null) {
            // username or password are null, re-authenticate
            sb.append(authenticationForm(req.getRequestURI(), CSRF_TOKEN));
            return;
        }
        try {
            // get a new shell for this user
            ShellExecutionThread shellThread = new ShellExecutionThread(user, pass, mock);
            service().submit(shellThread);
            userShells().put(session.getId(), shellThread);
        } catch (IOException e) {
            // error validating user, reauthenticate
            sb.append("<div id='loginError'>Invalid user/password</div>"
                    + authenticationForm(req.getRequestURI(), CSRF_TOKEN));
            return;
        }
        session.setAttribute("user", user);
    }
    if (!userShells().containsKey(session.getId())) {
        // no existing shell for this user, re-authenticate
        sb.append(authenticationForm(req.getRequestURI(), UUID.randomUUID().toString()));
        return;
    }

    ShellExecutionThread shellThread = userShells().get(session.getId());
    shellThread.getOutput();
    shellThread.printInfo();
    sb.append("<div id='shell'>\n");
    sb.append("<pre id='shellResponse'>").append(shellThread.getOutput()).append("</pre>\n");
    sb.append("<form><span id='shellPrompt'>").append(shellThread.getPrompt());
    sb.append(
            "</span><input type='text' name='cmd' id='cmd' onkeydown='return handleKeyDown(event.keyCode);'>\n");
    sb.append("</form>\n</div>\n");
    sb.append("<script type='text/javascript'>\n");
    sb.append("var url = '").append(req.getRequestURL().toString()).append("';\n");
    sb.append("var xmlhttp = new XMLHttpRequest();\n");
    sb.append("var hsize = 1000;\n");
    sb.append("var hindex = 0;\n");
    sb.append("var history = new Array();\n");
    sb.append("\n");
    sb.append("function handleKeyDown(keyCode) {\n");
    sb.append("  if (keyCode==13) {\n");
    sb.append("    submitCmd(document.getElementById('cmd').value);\n");
    sb.append("    hindex = history.length;\n");
    sb.append("    return false;\n");
    sb.append("  } else if (keyCode==38) {\n");
    sb.append("    hindex = hindex==0 ? history.length : hindex - 1;\n");
    sb.append("    if (hindex == history.length)\n");
    sb.append("      document.getElementById('cmd').value = '';\n");
    sb.append("    else\n");
    sb.append("      document.getElementById('cmd').value = history[hindex];\n");
    sb.append("    return false;\n");
    sb.append("  } else if (keyCode==40) {\n");
    sb.append("    hindex = hindex==history.length ? history.length : hindex + 1;\n");
    sb.append("    if (hindex == history.length)\n");
    sb.append("      document.getElementById('cmd').value = '';\n");
    sb.append("    else\n");
    sb.append("      document.getElementById('cmd').value = history[hindex];\n");
    sb.append("    return false;\n");
    sb.append("  }\n");
    sb.append("  return true;\n");
    sb.append("}\n");
    sb.append("\n");
    sb.append("function submitCmd(cmd) {\n");
    sb.append("  if (cmd=='history') {\n");
    sb.append(
            "    document.getElementById('shellResponse').innerHTML += document.getElementById('shellPrompt').innerHTML+cmd+'\\n';\n");
    sb.append("    document.getElementById('shellResponse').innerHTML += history.join('\\n');\n");
    sb.append("    return\n");
    sb.append("  }\n");
    sb.append("  xmlhttp.open('POST',url+'?cmd='+cmd+'&'+'").append(CSRF_KEY).append("=").append(CSRF_TOKEN)
            .append("',false);\n");
    sb.append("  xmlhttp.send();\n");
    sb.append("  var text = xmlhttp.responseText;\n");
    sb.append("  var index = text.lastIndexOf('\\n');\n");
    sb.append("  if (index >= 0) {\n");
    sb.append("    if (index > 0 && document.getElementById('cmd').type == 'text') {\n");
    sb.append("      if (history.length == hsize)\n");
    sb.append("        history.shift()\n");
    sb.append("      history.push(cmd)\n");
    sb.append("    }\n");
    sb.append("    if (text.charAt(text.length-1)=='*') {\n");
    sb.append("      document.getElementById('cmd').type = 'password';\n");
    sb.append("      text = text.substring(0,xmlhttp.responseText.length-2);\n");
    sb.append("    } else {\n");
    sb.append("      document.getElementById('cmd').type = 'text';\n");
    sb.append("    }\n");
    sb.append("    document.getElementById('shellResponse').innerHTML += text.substring(0,index+1);\n");
    sb.append("    document.getElementById('shellPrompt').innerHTML = text.substring(index+1);\n");
    sb.append("    document.getElementById('cmd').value = '';\n");
    sb.append("    document.getElementById('shell').scrollTop = document.getElementById('cmd').offsetTop;\n");
    sb.append("  } else {\n");
    sb.append("    window.location = url;\n");
    sb.append("  }\n");
    sb.append("}\n");
    sb.append("</script>\n");
    sb.append(
            "<script type='text/javascript'>window.onload = function() { document.getElementById('cmd').select(); }</script>\n");
}

From source file:gov.nih.nci.security.upt.actions.CommonDBAction.java

public String loadSearchResult(BaseDBForm baseDBForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDB.isDebugEnabled())
            logDB.debug("||" + baseDBForm.getFormName()
                    + "|loadSearchResult|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from   w w w.j ava  2  s  .co m

    if (session.getAttribute(DisplayConstants.CREATE_WORKFLOW) != null) {
        //session.removeAttribute(DisplayConstants.CREATE_WORKFLOW);
        session.removeAttribute(DisplayConstants.SEARCH_RESULT);
        session.removeAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT);
        return ForwardConstants.LOAD_HOME_SUCCESS;
    } else {
        if (session.getAttribute(DisplayConstants.SEARCH_RESULT) == null
                && session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT) != null) {
            session.setAttribute(DisplayConstants.SEARCH_RESULT,
                    session.getAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT));
            //session.removeAttribute(DisplayConstants.ORIGINAL_SEARCH_RESULT);
        }
    }

    if (logDB.isDebugEnabled())
        logDB.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDBForm.getFormName() + "|loadSearchResult|Success|Loading the Search Result Page||");
    return ForwardConstants.LOAD_SEARCH_RESULT_SUCCESS;
}

From source file:pivotal.au.se.gemfirexdweb.controller.QueryController.java

@RequestMapping(value = "/query", method = RequestMethod.GET)
public String worksheet(Model model, HttpServletResponse response, HttpServletRequest request,
        HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*w  w  w .  j a v a  2 s.co  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to show query worksheet");
    UserPref userPrefs = (UserPref) session.getAttribute("prefs");

    String action = request.getParameter("action");
    if (action != null) {

        CommandResult result = new CommandResult();
        ConnectionManager cm = ConnectionManager.getInstance();
        Connection conn = cm.getConnection(session.getId());

        if (action.trim().equals("commit")) {
            logger.debug("commit action requested");
            result = QueryUtil.runCommitOrRollback(conn, true, "N");
            addCommandToHistory(session, userPrefs, "commit");

            model.addAttribute("result", result);
        } else if (action.trim().equals("rollback")) {
            logger.debug("rollback action requested");
            result = QueryUtil.runCommitOrRollback(conn, false, "N");
            addCommandToHistory(session, userPrefs, "rollback");

            model.addAttribute("result", result);
        } else if (action.trim().equals("export")) {
            logger.debug("export data to CSV action requested");
            String query = request.getParameter("query");
            String exportDataCSV = QueryUtil.runQueryForCSV(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT);

            ServletOutputStream out = response.getOutputStream();
            out.println(exportDataCSV);
            out.close();
            return null;
        } else if (action.trim().equals("export_json")) {
            logger.debug("export data to JSON action requested");
            String query = request.getParameter("query");
            String exportDataJSON = QueryUtil.runQueryForJSON(conn, query);

            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition", "attachment; filename=" + FILENAME_EXPORT_JSON);

            ServletOutputStream out = response.getOutputStream();
            out.println(exportDataJSON);
            out.close();
            return null;
        }

    }

    // Create new QueryWindow and add to model
    // This is the formBackingObject
    model.addAttribute("queryAttribute", new QueryWindow());

    // This will resolve to /WEB-INF/jsp/query.jsp
    return "query";
}

From source file:Controller.UserController.java

@RequestMapping(value = "/ReviewPackage/{PackageID}/{bookingID}")
public String makeReviewPackage(HttpServletRequest request, HttpSession session, @PathVariable int PackageID,
        @PathVariable String bookingID) {
    try {/*from  w w  w  .  j  av a  2  s  . c om*/

        AccountSession account = (AccountSession) session.getAttribute("account");
        if (commonService.checkReviewExist(account.getId(), bookingID)) {
            request.setAttribute("packageID", PackageID);
            request.setAttribute("bookingID", bookingID);
            return "tripper/reviewPackage";
        }
        if (request.getParameter("language") != null) {
            return "redirect:/Common" + "?language=" + request.getParameter("language");
        } else {
            return "redirect:/Common";
        }

    } catch (Exception e) {
        String content = "Function: UserController - makeReviewPackage\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:com.tecapro.inventory.common.action.BaseAction.java

/**
 * get download value//from   w w w  . j  a  v  a 2  s . c  o m
 * @param request
 * @return
 * @throws Exception
 */
private Boolean checkDownloadRequest(BaseForm zform, HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    Boolean result = false;
    String downloadValue = "";
    HttpSession session = request.getSession(false);
    InfoValue info = zform.getValue().getInfo();

    // get download key from request
    String downloadKey = (String) request.getParameter(Constants.DOWNLOAD_KEY);
    if (downloadKey != null && !"".equals(downloadKey)) {

        // decode download key
        downloadValue = (String) commonUtil.deserialize(downloadKey.getBytes());
    }

    // check download value
    if (downloadValue != null && !"".equals(downloadValue) && downloadValue.contains(session.getId())) {
        String fileName = downloadValue
                .substring(downloadValue.lastIndexOf(DIVIDER_KEY) + DIVIDER_KEY.length());

        // init download file
        info.getFile().get(0).setTempFileName(fileName, fileName);
        info.getFile().get(0).setDownloadFileName(fileName);

        // start download file
        downloadFile(zform, response);
        result = true;
    }

    request.removeAttribute(Constants.DOWNLOAD_KEY);
    info.getFile().set(0, new FileInfoValue());

    return result;
}

From source file:Controller.UserController.java

@RequestMapping(value = "/ChatWithProvider/{userID}/{conversationID}")
public String chatwithProvider(HttpServletRequest request, @PathVariable int userID,
        @PathVariable int conversationID) {
    try {/*from www  .j a v  a2  s .  c o m*/
        String conversationList = "";
        HttpSession session = request.getSession(true);
        request.setAttribute("page", "tripperMessage");
        AccountSession account = (AccountSession) session.getAttribute("account");
        String result = "";
        request.setAttribute("conversationID",
                messageService.getConversationID(userID, account.getId(), conversationID));
        conversationList = messageService.getListConversationbyTripperID(account.getId());
        request.setAttribute("conversationList", conversationList);

        return "tripper/chat";
    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - chatwithProvider\n" + "***Input***\n" + "userID: " + userID
                + "\n" + "**********\n" + "****Error****\n" + e.getMessage() + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}