List of usage examples for javax.servlet.http HttpServletResponse encodeUrl
@Deprecated
public String encodeUrl(String url);
From source file:org.hyperic.hq.ui.action.resource.common.monitor.alerts.RemoveAction.java
/** * removes alerts/* w w w .j a v a 2s .c o m*/ */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { RemoveForm nwForm = (RemoveForm) form; log.debug("entering removeAlertsAction"); Integer type = nwForm.getType(); Map<String, Object> params = new HashMap<String, Object>(); params.put(Constants.ENTITY_ID_PARAM, nwForm.getEid()); ActionForward forward = checkSubmit(request, mapping, form, params); // if the remove button was clicked, we are coming from // the alerts list page and just want to continue // processing ... if (forward != null && !forward.getName().equals(Constants.REMOVE_URL)) { log.trace("returning " + forward); // if there is no resource type, there is probably no // resource -- go to dashboard on cancel if (forward.getName().equals(Constants.CANCEL_URL) && type.intValue() == 0) { return returnNoResource(request, mapping); } return forward; } Integer[] alertIds = nwForm.getAlerts(); String[] escalatables = nwForm.getEalerts(); if (log.isDebugEnabled()) { if (alertIds != null) { log.debug("acting on alerts: " + Arrays.asList(alertIds)); } if (escalatables != null) { log.debug("acting on ealerts: " + Arrays.asList(escalatables)); } } if ((alertIds == null || alertIds.length == 0) && (escalatables == null || escalatables.length == 0)) { return returnSuccess(request, mapping, params); } Integer sessionId = RequestUtils.getSessionId(request); if (nwForm.isDeleteClicked()) { log.debug("!!!!!!!!!!!!!!!! removing alerts!!!!!!!!!!!!"); eventsBoss.deleteAlerts(sessionId.intValue(), alertIds); } else if (nwForm.getButtonAction() != null) { if ("ACKNOWLEDGE".equals(nwForm.getButtonAction())) { log.debug("Acknowledge alerts"); if (alertIds != null) { for (int i = 0; i < alertIds.length; i++) { // XXX: This only works for classic alert types ATM eventsBoss.acknowledgeAlert(sessionId.intValue(), ClassicEscalationAlertType.CLASSIC, alertIds[i], nwForm.getPauseTime(), nwForm.getAckNote()); } } if (escalatables != null) { log.debug("Escalatable alerts"); for (int i = 0; i < escalatables.length; i++) { StringTokenizer st = new StringTokenizer(escalatables[i], ":"); int code = Integer.parseInt(st.nextToken()); Integer alert = Integer.valueOf(st.nextToken()); eventsBoss.acknowledgeAlert(sessionId.intValue(), EscalationAlertType.findByCode(code), alert, nwForm.getPauseTime(), nwForm.getAckNote()); } } } else if ("FIXED".equals(nwForm.getButtonAction())) { log.debug("Fixed alerts"); if (alertIds != null) { for (int i = 0; i < alertIds.length; i++) { // This only works for classic alert types eventsBoss.fixAlert(sessionId.intValue(), ClassicEscalationAlertType.CLASSIC, alertIds[i], nwForm.getFixedNote(), nwForm.isFixAll()); } } if (escalatables != null) { log.debug("Escalatable alerts"); for (int i = 0; i < escalatables.length; i++) { StringTokenizer st = new StringTokenizer(escalatables[i], ":"); int code = Integer.parseInt(st.nextToken()); Integer alert = Integer.valueOf(st.nextToken()); eventsBoss.fixAlert(sessionId.intValue(), EscalationAlertType.findByCode(code), alert, nwForm.getFixedNote(), nwForm.isFixAll()); } } } } if ("json".equals(nwForm.getOutput())) { JSONObject ajaxJson = new JSONObject(); String requestURI = request.getRequestURI(); // generate a new CSRF token for subsequent requests if needed ajaxJson.put("actionToken", response.encodeURL(requestURI)); request.setAttribute(Constants.AJAX_JSON, ajaxJson); return constructForward(request, mapping, "json"); } else if (nwForm.getEid() == null) { return returnNoResource(request, mapping); } else { return returnSuccess(request, mapping, params); } }
From source file:org.apache.struts2.views.util.DefaultUrlHelper.java
public String buildUrl(String action, HttpServletRequest request, HttpServletResponse response, Map<String, Object> params, String scheme, boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort, boolean escapeAmp) { StringBuilder link = new StringBuilder(); boolean changedScheme = false; // FIXME: temporary hack until class is made a properly injected bean Container cont = ActionContext.getContext().getContainer(); int httpPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTP_PORT)); int httpsPort = Integer.parseInt(cont.getInstance(String.class, StrutsConstants.STRUTS_URL_HTTPS_PORT)); // only append scheme if it is different to the current scheme *OR* // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true if (forceAddSchemeHostAndPort) { String reqScheme = request.getScheme(); changedScheme = true;//from w w w . j ava2 s .co m link.append(scheme != null ? scheme : reqScheme); link.append("://"); link.append(request.getServerName()); if (scheme != null) { // If switching schemes, use the configured port for the particular scheme. if (!scheme.equals(reqScheme)) { if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT)) || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) { link.append(":"); link.append(scheme.equals("http") ? httpPort : httpsPort); } // Else use the port from the current request. } else { int reqPort = request.getServerPort(); if ((scheme.equals("http") && (reqPort != DEFAULT_HTTP_PORT)) || (scheme.equals("https") && reqPort != DEFAULT_HTTPS_PORT)) { link.append(":"); link.append(reqPort); } } } } else if ((scheme != null) && !scheme.equals(request.getScheme())) { changedScheme = true; link.append(scheme); link.append("://"); link.append(request.getServerName()); if ((scheme.equals("http") && (httpPort != DEFAULT_HTTP_PORT)) || (scheme.equals("https") && httpsPort != DEFAULT_HTTPS_PORT)) { link.append(":"); link.append(scheme.equals("http") ? httpPort : httpsPort); } } if (action != null) { // Check if context path needs to be added // Add path to absolute links if (action.startsWith("/") && includeContext) { String contextPath = request.getContextPath(); if (!contextPath.equals("/")) { link.append(contextPath); } } else if (changedScheme) { // (Applicable to Servlet 2.4 containers) // If the request was forwarded, the attribute below will be set with the original URL String uri = (String) request.getAttribute("javax.servlet.forward.request_uri"); // If the attribute wasn't found, default to the value in the request object if (uri == null) { uri = request.getRequestURI(); } link.append(uri.substring(0, uri.lastIndexOf('/') + 1)); } // Add page link.append(action); } else { // Go to "same page" String requestURI = (String) request.getAttribute("struts.request_uri"); // (Applicable to Servlet 2.4 containers) // If the request was forwarded, the attribute below will be set with the original URL if (requestURI == null) { requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri"); } // If neither request attributes were found, default to the value in the request object if (requestURI == null) { requestURI = request.getRequestURI(); } link.append(requestURI); } //if the action was not explicitly set grab the params from the request if (escapeAmp) { buildParametersString(params, link, AMP); } else { buildParametersString(params, link, "&"); } String result = link.toString(); if (StringUtils.containsIgnoreCase(result, "<script")) { result = StringEscapeUtils.escapeEcmaScript(result); } try { result = encodeResult ? response.encodeURL(result) : result; } catch (Exception ex) { if (LOG.isDebugEnabled()) { LOG.debug("Could not encode the URL for some reason, use it unchanged", ex); } result = link.toString(); } return result; }
From source file:org.hyperic.hq.ui.action.resource.ResourceController.java
protected AppdefEntityID setResource(HttpServletRequest request, HttpServletResponse response, AppdefEntityID entityId, boolean config) throws Exception { Integer sessionId = RequestUtils.getSessionId(request); AppdefEntityTypeID aetid;/*from w w w .j av a 2s .c om*/ if (null == entityId || entityId instanceof AppdefEntityTypeID) { // this can happen if we're an auto-group of platforms request.setAttribute(Constants.CONTROL_ENABLED_ATTR, Boolean.FALSE); request.setAttribute(Constants.PERFORMANCE_SUPPORTED_ATTR, Boolean.FALSE); try { if (entityId != null) { aetid = (AppdefEntityTypeID) entityId; } else { aetid = new AppdefEntityTypeID( RequestUtils.getStringParameter(request, Constants.APPDEF_RES_TYPE_ID)); } AppdefResourceTypeValue resourceTypeVal = appdefBoss.findResourceTypeById(sessionId.intValue(), aetid); request.setAttribute(Constants.RESOURCE_TYPE_ATTR, resourceTypeVal); // Set the title parameters request.setAttribute(Constants.TITLE_PARAM_ATTR, resourceTypeVal.getName()); } catch (Exception e) { log.debug("Error setting resource attributes", e); } } else { try { log.trace("finding resource [" + entityId + "]"); AppdefResourceValue resource = appdefBoss.findById(sessionId.intValue(), entityId); log.trace("finding owner for resource [" + entityId + "]"); AuthzSubject owner = authzBoss.findSubjectByNameNoAuthz(sessionId, resource.getOwner()); log.trace("finding most recent modifier for resource [" + entityId + "]"); AuthzSubject modifier = authzBoss.findSubjectByNameNoAuthz(sessionId, resource.getModifiedBy()); RequestUtils.setResource(request, resource); request.setAttribute(Constants.RESOURCE_OWNER_ATTR, owner); request.setAttribute(Constants.RESOURCE_MODIFIER_ATTR, modifier); request.setAttribute(Constants.TITLE_PARAM_ATTR, resource.getName()); if (resource instanceof AppdefGroupValue) { request.setAttribute(Constants.GROUP_TYPE_ATTR, ((AppdefGroupValue) resource).getGroupType()); } // set the resource controllability flag if (!entityId.isApplication()) { // We were doing group Specific isGroupControlEnabled for // groups. // We should just see if the group control is supported // regardless of whether control is enabled or not. Also we // should be calling isControlSupported on entity and not // controlEnabled. boolean isControllable = controlBoss.isControlSupported(sessionId.intValue(), resource); request.setAttribute(Constants.CONTROL_ENABLED_ATTR, new Boolean(isControllable)); } // Set additional flags UIUtils utils = (UIUtils) ProductProperties.getPropertyInstance("hyperic.hq.ui.utils"); utils.setResourceFlags(resource, config, request, getServlet().getServletContext()); // Get the custom properties Properties cprops = appdefBoss.getCPropDescEntries(sessionId.intValue(), entityId); Resource resourceObj = Bootstrap.getBean(ResourceManager.class).findResource(entityId); if ((entityId.isPlatform() || entityId.isServer()) && appdefBoss.hasVirtualResourceRelation(resourceObj)) { Collection mastheadAttachments = Bootstrap.getBean(ProductBoss.class) .findAttachments(sessionId.intValue(), AttachType.MASTHEAD); Map pluginLinkMap = new HashMap(); for (Iterator i = mastheadAttachments.iterator(); i.hasNext();) { AttachmentDescriptor descriptor = (AttachmentDescriptor) i.next(); if (descriptor.getAttachment().getView().getPlugin().getName().equals("vsphere")) { ResourceEdge parent = Bootstrap.getBean(ResourceManager.class).getParentResourceEdge( resourceObj, Bootstrap.getBean(ResourceManager.class).getVirtualRelation()); // TODO This is ugly and I hate putting it in, but there's no easy way to link into a // plugin right now... if (parent != null && parent.getTo().getPrototype().getName() .equals(AuthzConstants.platformPrototypeVmwareVsphereVm)) { UriTemplate uriTemplate = new UriTemplate( "/mastheadAttach.do?typeId={typeId}&sn={sn}"); cprops.put("VM Instance", "<a href='" + response .encodeURL( uriTemplate .expand(descriptor.getAttachment().getId(), parent.getTo().getId()) .toASCIIString()) + "'>" + parent.getTo().getName() + "</a>"); } else { pluginLinkMap.put("pluginId", descriptor.getAttachment().getId()); pluginLinkMap.put("selectedId", resourceObj.getId()); request.setAttribute("pluginLinkInfo", pluginLinkMap); } break; } } } // Set the properties in the request if (cprops.size() > 0) { request.setAttribute("cprops", cprops); } // Add this resource to the recently used preference WebUser user = RequestUtils.getWebUser(request); ConfigResponse userPrefs = user.getPreferences(); if (DashboardUtils.addEntityToPreferences(Constants.USERPREF_KEY_RECENT_RESOURCES, userPrefs, entityId, 10)) { authzBoss.setUserPrefs(user.getSessionId(), user.getSubject().getId(), userPrefs); } } catch (AppdefEntityNotFoundException aenf) { RequestUtils.setError(request, Constants.ERR_RESOURCE_NOT_FOUND); throw aenf; } catch (PermissionException e) { throw e; } catch (Exception e) { log.error("Unable to find resource", e); throw AppdefEntityNotFoundException.build(entityId, e); } } return entityId; }
From source file:org.sakaiproject.login.tool.LoginTool.java
/** * Send the login form//from w w w. j a v a 2 s . com * * @param req * Servlet request. * @param res * Servlet response. * @throws IOException */ protected void sendForm(HttpServletRequest req, HttpServletResponse res) throws IOException { final String headHtml = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">" + " <head>" + " <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />" + " <link href=\"SKIN_ROOT/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />" + " <link href=\"SKIN_ROOT/DEFAULT_SKIN/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />" + " <meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />" + " <title>UI.SERVICE</title>" + " <script type=\"text/javascript\" language=\"JavaScript\" src=\"/library/js/headscripts.js\"></script>" + " </head>" + " <body onload=\"if ((document.getElementById('pw').passwordfocus != true)) document.getElementById('eid').focus() ;parent.updCourier(doubleDeep, ignoreCourier);\" class=\"servletBody\">"; final String tailHtml = "</body></html>"; final String loginHtml = "<table class=\"login\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\" summary=\"layout\">" + " <tr>" + " <th colspan=\"2\">" + " Login Required" + " </th>" + " </tr>" + " <tr>" + " <td class=\"logo\">" + " </td>" + " <td class=\"form\">" + " <form method=\"post\" action=\"ACTION\" enctype=\"application/x-www-form-urlencoded\">" + " MSG" + " <table border=\"0\" class=\"loginform\" summary=\"layout\">" + " <tr>" + " <td>" + " <label for=\"eid\">EID</label>" + " </td>" + " <td class=\"shorttext\">" + " <input name=\"eid\" id=\"eid\" type=\"text\" size=\"15\"/>" + " </td>" + " </tr>" + " <tr>" + " <td>" + " <label for=\"pw\">PW</label>" + " </td>" + " <td class=\"shorttext\">" + " <input name=\"pw\" id=\"pw\" type=\"password\" size=\"15\" onFocus=\"this.passwordfocus = true; \" />" + " </td>" + " </tr>" + " <tr>" + " <td colspan=\"2\">" + " <input name=\"submit\" type=\"submit\" id=\"submit\" value=\"LoginSubmit\"/>" + " </td>" + " </tr>" + " </table>" + " </form>" + " </td>" + " </tr>" + " </table>"; // get the Sakai session Session session = SessionManager.getCurrentSession(); // get my tool registration Tool tool = (Tool) req.getAttribute(Tool.TOOL); // fragment or not? boolean fragment = Boolean.TRUE.toString().equals(req.getAttribute(Tool.FRAGMENT)); // PDA or not? String portalUrl = (String) session.getAttribute(Tool.HELPER_DONE_URL); boolean isPDA = false; if (portalUrl != null) isPDA = portalUrl.endsWith(PDA_PORTAL_SUFFIX); String eidWording = rb.getString("userid"); String pwWording = rb.getString("log.pass"); String loginRequired = rb.getString("log.logreq"); String loginWording = rb.getString("log.login"); if (!fragment) { // set our response type res.setContentType("text/html; charset=UTF-8"); res.addDateHeader("Expires", System.currentTimeMillis() - (1000L * 60L * 60L * 24L * 365L)); res.addDateHeader("Last-Modified", System.currentTimeMillis()); res.addHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0"); res.addHeader("Pragma", "no-cache"); } String defaultSkin = ServerConfigurationService.getString("skin.default"); String skinRoot = ServerConfigurationService.getString("skin.repo"); String uiService = ServerConfigurationService.getString("ui.service"); // get our response writer PrintWriter out = res.getWriter(); if (!fragment) { // start our complete document String head = headHtml; if (isPDA) { head = head.replaceAll("</title>", "</title><link href=\"SKIN_ROOT/DEFAULT_SKIN/pda.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" /> <meta name=\"viewport\" content=\"width=device-width, user-scalable=yes, initial-scale=1.0, maximum-scale=1.0\"/>"); } head = head.replaceAll("DEFAULT_SKIN", defaultSkin); head = head.replaceAll("SKIN_ROOT", skinRoot); head = head.replaceAll("UI.SERVICE", uiService); out.println(head); } // if we are in helper mode, there might be a helper message if (session.getAttribute(Tool.HELPER_MESSAGE) != null) { out.println("<p>" + session.getAttribute(Tool.HELPER_MESSAGE) + "</p>"); } // add our return URL String returnUrl = res.encodeURL(Web.returnUrl(req, null)); String html = loginHtml.replaceAll("ACTION", res.encodeURL(returnUrl)); // add our wording html = html.replaceAll("EID", eidWording); html = html.replaceAll("PW", pwWording); html = html.replaceAll("Login Required", loginRequired); html = html.replaceAll("LoginSubmit", loginWording); // add the default skin html = html.replaceAll("DEFAULT_SKIN", defaultSkin); html = html.replaceAll("SKIN_ROOT", skinRoot); if (isPDA) { html = html.replaceAll("class=\"login\"", "class=\"loginPDA\""); html = html.replaceAll("</title>", "</title><link href=\"SKIN_ROOT/DEFAULT_SKIN/pda.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />"); } // write a message if present String msg = (String) session.getAttribute(ATTR_MSG); if (msg != null) { html = html.replaceAll("MSG", "<div class=\"alertMessage\">" + rb.getString("gen.alert") + " " + msg + "</div>"); session.removeAttribute(ATTR_MSG); } else { html = html.replaceAll("MSG", ""); } // write the login screen out.println(html); if (!fragment) { // close the complete document out.println(tailHtml); } }
From source file:edu.ucsd.library.xdre.web.CollectionOperationController.java
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String message = ""; Map<String, String[]> paramsMap = null; if (ServletFileUpload.isMultipartContent(request)) { paramsMap = new HashMap<String, String[]>(); paramsMap.putAll(request.getParameterMap()); FileItemFactory factory = new DiskFileItemFactory(); //Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); List items = null;/*from w w w . ja v a 2s . c o m*/ InputStream in = null; ByteArrayOutputStream out = null; byte[] buf = new byte[4096]; List<String> dataItems = new ArrayList<String>(); List<String> fileNames = new ArrayList<String>(); try { items = upload.parseRequest(request); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); out = new ByteArrayOutputStream(); if (item.isFormField()) { paramsMap.put(item.getFieldName(), new String[] { item.getString() }); } else { fileNames.add(item.getName()); in = item.getInputStream(); int bytesRead = -1; while ((bytesRead = in.read(buf)) > 0) { out.write(buf, 0, bytesRead); } dataItems.add(out.toString()); } } } catch (FileUploadException e) { throw new ServletException(e.getMessage()); } finally { if (in != null) { in.close(); in = null; } if (out != null) { out.close(); out = null; } } if (dataItems.size() > 0) { String[] a = new String[dataItems.size()]; paramsMap.put("data", dataItems.toArray(a)); paramsMap.put("fileName", fileNames.toArray(new String[dataItems.size()])); } } else paramsMap = request.getParameterMap(); String collectionId = getParameter(paramsMap, "category"); String activeButton = getParameter(paramsMap, "activeButton"); boolean dataConvert = getParameter(paramsMap, "dataConvert") != null; boolean isIngest = getParameter(paramsMap, "ingest") != null; boolean isDevUpload = getParameter(paramsMap, "devUpload") != null; boolean isBSJhoveReport = getParameter(paramsMap, "bsJhoveReport") != null; boolean isSolrDump = getParameter(paramsMap, "solrDump") != null || getParameter(paramsMap, "solrRecordsDump") != null; boolean isSerialization = getParameter(paramsMap, "serialize") != null; boolean isMarcModsImport = getParameter(paramsMap, "marcModsImport") != null; boolean isExcelImport = getParameter(paramsMap, "excelImport") != null; boolean isCollectionRelease = getParameter(paramsMap, "collectionRelease") != null; boolean isFileUpload = getParameter(paramsMap, "fileUpload") != null; String fileStore = getParameter(paramsMap, "fs"); if (activeButton == null || activeButton.length() == 0) activeButton = "validateButton"; HttpSession session = request.getSession(); session.setAttribute("category", collectionId); session.setAttribute("user", request.getRemoteUser()); String ds = getParameter(paramsMap, "ts"); if (ds == null || ds.length() == 0) ds = Constants.DEFAULT_TRIPLESTORE; if (fileStore == null || (fileStore = fileStore.trim()).length() == 0) fileStore = null; String forwardTo = "/controlPanel.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : ""); if (dataConvert) forwardTo = "/pathMapping.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : ""); else if (isIngest) { String unit = getParameter(paramsMap, "unit"); forwardTo = "/ingest.do?ts=" + ds + (fileStore != null ? "&fs=" + fileStore : "") + (unit != null ? "&unit=" + unit : ""); } else if (isDevUpload) forwardTo = "/devUpload.do?" + (fileStore != null ? "&fs=" + fileStore : ""); else if (isSolrDump) forwardTo = "/solrDump.do" + (StringUtils.isBlank(collectionId) ? "" : "#colsTab"); else if (isSerialization) forwardTo = "/serialize.do?" + (fileStore != null ? "&fs=" + fileStore : ""); else if (isMarcModsImport) forwardTo = "/marcModsImport.do?"; else if (isExcelImport) forwardTo = "/excelImport.do?"; else if (isCollectionRelease) forwardTo = "/collectionRelease.do?"; else if (isFileUpload) forwardTo = "/fileUpload.do?"; String[] emails = null; String user = request.getRemoteUser(); if ((!(getParameter(paramsMap, "solrRecordsDump") != null || isBSJhoveReport || isDevUpload || isFileUpload) && getParameter(paramsMap, "rdfImport") == null && getParameter(paramsMap, "externalImport") == null && getParameter(paramsMap, "dataConvert") == null) && getParameter(paramsMap, "marcModsImport") == null && getParameter(paramsMap, "excelImport") == null && (collectionId == null || (collectionId = collectionId.trim()).length() == 0)) { message = "Please choose a collection ..."; } else { String servletId = getParameter(paramsMap, "progressId"); boolean vRequest = false; try { vRequest = RequestOrganizer.setReferenceServlet(session, servletId, Thread.currentThread()); } catch (Exception e) { message = e.getMessage(); } if (!vRequest) { if (isSolrDump || isCollectionRelease || isFileUpload) session.setAttribute("message", message); else { forwardTo += "&activeButton=" + activeButton; forwardTo += "&message=" + message; } forwordPage(request, response, response.encodeURL(forwardTo)); return null; } session.setAttribute("status", "Processing request ..."); DAMSClient damsClient = null; try { //user = getUserName(request); //email = getUserEmail(request); damsClient = new DAMSClient(Constants.DAMS_STORAGE_URL); JSONArray mailArr = (JSONArray) damsClient.getUserInfo(user).get("mail"); if (mailArr != null && mailArr.size() > 0) { emails = new String[mailArr.size()]; mailArr.toArray(emails); } message = handleProcesses(paramsMap, request.getSession()); } catch (Exception e) { e.printStackTrace(); //throw new ServletException(e.getMessage()); message += "<br />Internal Error: " + e.getMessage(); } finally { if (damsClient != null) damsClient.close(); } } System.out.println("XDRE Manager execution for " + request.getRemoteUser() + " from IP " + request.getRemoteAddr() + ": "); System.out.println(message.replace("<br />", "\n")); try { int count = 0; String result = (String) session.getAttribute("result"); while (result != null && result.length() > 0 && count++ < 10) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } result = (String) session.getAttribute("result"); } RequestOrganizer.clearSession(session); } catch (IllegalStateException e) { //e.printStackTrace(); } //send email try { String sender = Constants.MAILSENDER_DAMSSUPPORT; if (emails == null && user != null) { emails = new String[1]; emails[0] = user + "@ucsd.edu"; } if (emails == null) DAMSClient.sendMail(sender, new String[] { sender }, "DAMS Manager Invocation Result - " + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""), message, "text/html", "smtp.ucsd.edu"); else DAMSClient.sendMail(sender, emails, "DAMS Manager Invocation Result - " + Constants.CLUSTER_HOST_NAME.replace("http://", "").replace(".ucsd.edu/", ""), message, "text/html", "smtp.ucsd.edu"); } catch (AddressException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } if (isSolrDump || isMarcModsImport || isExcelImport || isCollectionRelease || isFileUpload) { session.setAttribute("message", message.replace("\n", "<br />")); if (collectionId != null && (isMarcModsImport || isExcelImport || isCollectionRelease)) forwardTo += "category=" + collectionId; } else { forwardTo += "&activeButton=" + activeButton; if (collectionId != null) forwardTo += "&category=" + collectionId; forwardTo += "&message=" + URLEncoder.encode(message.replace("\n", "<br />"), "UTF-8"); } System.out.println(forwardTo); //String forwardToUrl = "/controlPanel.do?category=" + collectionId + "&message=" + message + "&activeButton=" + activeButton; forwordPage(request, response, response.encodeURL(forwardTo)); return null; }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/*from w ww. ja v a 2 s .c o m*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {//from ww w . j a v a2 s. c o m throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.unitime.timetable.action.PersonalizedExamReportAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PersonalizedExamReportForm myForm = (PersonalizedExamReportForm) form; String back = (String) request.getSession().getAttribute("loginPage"); if (back == null) back = "back"; try {/* w w w . j av a 2 s . c om*/ sessionContext.checkPermission(Right.PersonalSchedule); } catch (AccessDeniedException e) { request.setAttribute("message", e.getMessage()); return mapping.findForward(back); } if (request.getParameter("q") != null) { String[] params = QueryEncoderBackend.decode(request.getParameter("q")).split(":"); if (params != null && params.length == 2) { myForm.setUid(params[0]); myForm.setSessionId(Long.valueOf(params[1])); } } String externalId = sessionContext.getUser().getExternalUserId(); String userName = sessionContext.getUser().getName(); myForm.setAdmin(sessionContext.hasPermission(Right.PersonalScheduleLookup)); myForm.setLogout(!"back".equals(back)); if (sessionContext.hasPermission(Right.PersonalScheduleLookup) && myForm.getUid() != null && !myForm.getUid().isEmpty()) { externalId = myForm.getUid(); userName = (myForm.getLname() == null || myForm.getLname().length() == 0 ? "" : " " + Constants.toInitialCase(myForm.getLname())) + (myForm.getFname() == null || myForm.getFname().length() == 0 ? "" : " " + myForm.getFname().substring(0, 1).toUpperCase()) + (myForm.getMname() == null || myForm.getMname().length() == 0 ? "" : " " + myForm.getMname().substring(0, 1).toUpperCase()); } if (externalId == null || externalId.length() == 0) { request.setAttribute("message", "No user id provided."); return mapping.findForward(back); } if ("Log Out".equals(myForm.getOp())) { SecurityContextHolder.getContext().setAuthentication(null); return mapping.findForward(back); } if ("classes".equals(back)) { if (myForm.getSessionId() == null) { myForm.setSessionId((Long) request.getSession().getAttribute("Classes.session")); } else { request.getSession().setAttribute("Classes.session", myForm.getSessionId()); } } else if ("exams".equals(back)) { if (myForm.getSessionId() == null) { myForm.setSessionId((Long) request.getSession().getAttribute("Exams.session")); } else { request.getSession().setAttribute("Exams.session", myForm.getSessionId()); } } HashSet<Session> sessions = new HashSet(); DepartmentalInstructor instructor = null; for (Iterator i = new DepartmentalInstructorDAO().getSession() .createQuery("select i from DepartmentalInstructor i where i.externalUniqueId=:externalId") .setString("externalId", translate(externalId, Source.Staff)).setCacheable(true).list() .iterator(); i.hasNext();) { DepartmentalInstructor s = (DepartmentalInstructor) i.next(); if (!canDisplay(s.getDepartment().getSession())) continue; sessions.add(s.getDepartment().getSession()); if (myForm.getSessionId() == null) { if (instructor == null || instructor.getDepartment().getSession().compareTo(s.getDepartment().getSession()) < 0) instructor = s; } else if (myForm.getSessionId().equals(s.getDepartment().getSession().getUniqueId())) { instructor = s; } } Student student = null; for (Iterator i = new StudentDAO().getSession() .createQuery("select s from Student s where s.externalUniqueId=:externalId") .setString("externalId", translate(externalId, Source.Student)).setCacheable(true).list() .iterator(); i.hasNext();) { Student s = (Student) i.next(); if (!canDisplay(s.getSession())) continue; sessions.add(s.getSession()); if (myForm.getSessionId() == null) { if (student == null || student.getSession().compareTo(s.getSession()) < 0) student = s; } else if (myForm.getSessionId().equals(s.getSession().getUniqueId())) student = s; } if (instructor == null && student == null) { if (myForm.getAdmin()) { back = "back"; myForm.setLogout(false); } else { if ("classes".equals(back)) request.setAttribute("message", "No classes found."); else if ("exams".equals(back)) request.setAttribute("message", "No examinations found."); else request.setAttribute("message", "No schedule found."); sLog.info("No matching instructor or student found for " + userName + " (" + translate(externalId, Source.Student) + "), forwarding back (" + back + ")."); return mapping.findForward(back); } } myForm.setCanExport(false); if (instructor != null && student != null && !instructor.getDepartment().getSession().equals(student.getSession())) { if (instructor.getDepartment().getSession().compareTo(student.getSession()) < 0) instructor = null; else student = null; } long t0 = System.currentTimeMillis(); if (instructor != null) { sLog.info("Requesting schedule for " + instructor.getName(DepartmentalInstructor.sNameFormatShort) + " (instructor)"); } else if (student != null) { sLog.info("Requesting schedule for " + student.getName(DepartmentalInstructor.sNameFormatShort) + " (student)"); } HashSet<ExamOwner> studentExams = new HashSet<ExamOwner>(); if (student != null) { /* for (Iterator i=student.getClassEnrollments().iterator();i.hasNext();) { StudentClassEnrollment sce = (StudentClassEnrollment)i.next(); studentExams.addAll(Exam.findAllRelated("Class_", sce.getClazz().getUniqueId())); } */ studentExams.addAll(new ExamDAO().getSession().createQuery( "select distinct o from Student s inner join s.classEnrollments ce, ExamOwner o inner join o.course co " + "inner join co.instructionalOffering io " + "inner join io.instrOfferingConfigs ioc " + "inner join ioc.schedulingSubparts ss " + "inner join ss.classes c where " + "s.uniqueId=:studentId and c=ce.clazz and (" + "(o.ownerType=" + ExamOwner.sOwnerTypeCourse + " and o.ownerId=co.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeOffering + " and o.ownerId=io.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeConfig + " and o.ownerId=ioc.uniqueId) or " + "(o.ownerType=" + ExamOwner.sOwnerTypeClass + " and o.ownerId=c.uniqueId) " + ")") .setLong("studentId", student.getUniqueId()).setCacheable(true).list()); for (Iterator<ExamOwner> i = studentExams.iterator(); i.hasNext();) { Exam exam = i.next().getExam(); DepartmentStatusType type = exam.effectiveStatusType(); if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal ? DepartmentStatusType.Status.ReportExamsFinal : DepartmentStatusType.Status.ReportExamsMidterm)) i.remove(); } } HashSet<Exam> instructorExams = new HashSet<Exam>(); if (instructor != null) { instructorExams.addAll(instructor.getAllExams()); for (Iterator<Exam> i = instructorExams.iterator(); i.hasNext();) { Exam exam = i.next(); DepartmentStatusType type = exam.effectiveStatusType(); if (type == null || !type.can(exam.getExamType().getType() == ExamType.sExamTypeFinal ? DepartmentStatusType.Status.ReportExamsFinal : DepartmentStatusType.Status.ReportExamsMidterm)) i.remove(); } } WebTable.setOrder(sessionContext, "exams.o0", request.getParameter("o0"), 1); WebTable.setOrder(sessionContext, "exams.o1", request.getParameter("o1"), 1); WebTable.setOrder(sessionContext, "exams.o2", request.getParameter("o2"), 1); WebTable.setOrder(sessionContext, "exams.o3", request.getParameter("o3"), 1); WebTable.setOrder(sessionContext, "exams.o4", request.getParameter("o4"), 1); WebTable.setOrder(sessionContext, "exams.o5", request.getParameter("o5"), 1); WebTable.setOrder(sessionContext, "exams.o6", request.getParameter("o6"), 1); WebTable.setOrder(sessionContext, "exams.o7", request.getParameter("o7"), 1); boolean hasClasses = false; if (student != null && student.getSession().canNoRoleReportClass() && !student.getClassEnrollments().isEmpty()) { PdfWebTable table = getStudentClassSchedule(true, student); if (!table.getLines().isEmpty()) { request.setAttribute("clsschd", table.printTable(WebTable.getOrder(sessionContext, "exams.o6"))); hasClasses = true; myForm.setCanExport(true); } } if (instructor != null && instructor.getDepartment().getSession().canNoRoleReportClass()) { PdfWebTable table = getInstructorClassSchedule(true, instructor); if (!table.getLines().isEmpty()) { request.setAttribute("iclsschd", table.printTable(Math.abs(WebTable.getOrder(sessionContext, "exams.o7")))); hasClasses = true; myForm.setCanExport(true); } } if (instructor != null && sessions.size() > 1) { PdfWebTable table = getSessions(true, sessions, instructor.getName(DepartmentalInstructor.sNameFormatLastFist), instructor.getDepartment().getSession().getUniqueId()); request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0"))); } else if (student != null && sessions.size() > 1) { PdfWebTable table = getSessions(true, sessions, student.getName(DepartmentalInstructor.sNameFormatLastFist), student.getSession().getUniqueId()); request.setAttribute("sessions", table.printTable(WebTable.getOrder(sessionContext, "exams.o0"))); } if (!hasClasses && instructorExams.isEmpty() && studentExams.isEmpty()) { if ("classes".equals(back)) myForm.setMessage("No classes found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if ("exams".equals(back)) myForm.setMessage("No examinations found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if (student != null || instructor != null) myForm.setMessage("No classes or examinations found in " + (instructor != null ? instructor.getDepartment().getSession() : student.getSession()) .getLabel() + "."); else if (sessionContext.hasPermission(Right.PersonalScheduleLookup)) myForm.setMessage( "No classes or examinations found in " + SessionDAO.getInstance() .get(sessionContext.getUser().getCurrentAcademicSessionId()).getLabel() + "."); else myForm.setMessage("No classes or examinations found for " + userName + "."); sLog.info("No classes or exams found for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName)); } boolean useCache = ApplicationProperty.ExaminationCacheConflicts.isTrue(); if ("Export PDF".equals(myForm.getOp())) { sLog.info(" Generating PDF for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student.getName(DepartmentalInstructor.sNameFormatShort))); OutputStream out = ExportUtils.getPdfOutputStream(response, "schedule"); if (!instructorExams.isEmpty()) { TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (Exam exam : instructorExams) { if (exam.getAssignedPeriod() == null) continue; exams.add(new ExamAssignmentInfo(exam, useCache)); } InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out, instructor.getDepartment().getSession(), null, null, exams); ir.setM2d(true); ir.setDirect(true); ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass()); ir.printHeader(); ir.printReport(ExamInfo.createInstructorInfo(instructor), exams); ir.lastPage(); ir.close(); } else if (!studentExams.isEmpty()) { TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); TreeSet<ExamSectionInfo> sections = new TreeSet<ExamSectionInfo>(); for (ExamOwner examOwner : studentExams) { if (examOwner.getExam().getAssignedPeriod() == null) continue; ExamAssignmentInfo x = new ExamAssignmentInfo(examOwner, student, studentExams); exams.add(x); sections.addAll(x.getSectionsIncludeCrosslistedDummies()); } StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out, student.getSession(), null, null, exams); sr.setM2d(true); sr.setBtb(true); sr.setDirect(true); sr.setClassSchedule(student.getSession().canNoRoleReportClass()); sr.printHeader(); sr.printReport(student, sections); sr.lastPage(); sr.close(); } else if (hasClasses) { if (instructor != null) { InstructorExamReport ir = new InstructorExamReport(InstructorExamReport.sModeNormal, out, instructor.getDepartment().getSession(), null, null, new TreeSet<ExamAssignmentInfo>()); ir.setM2d(true); ir.setDirect(true); ir.setClassSchedule(instructor.getDepartment().getSession().canNoRoleReportClass()); ir.printHeader(); ir.printReport(ExamInfo.createInstructorInfo(instructor), new TreeSet<ExamAssignmentInfo>()); ir.lastPage(); ir.close(); } else if (student != null) { StudentExamReport sr = new StudentExamReport(StudentExamReport.sModeNormal, out, student.getSession(), null, null, new TreeSet<ExamAssignmentInfo>()); sr.setM2d(true); sr.setBtb(true); sr.setDirect(true); sr.setClassSchedule(student.getSession().canNoRoleReportClass()); sr.printHeader(); sr.printReport(student, new TreeSet<ExamSectionInfo>()); sr.lastPage(); sr.close(); } } out.flush(); out.close(); return null; } if ("iCalendar".equals(myForm.getOp())) { Long sid = (instructor != null ? instructor.getDepartment().getSession().getUniqueId() : student.getSession().getUniqueId()); response.sendRedirect(response.encodeURL("export?q=" + QueryEncoderBackend.encode( "output=events.ics&type=person&ext=" + externalId + (sid == null ? "" : "&sid=" + sid)))); return null; } /* if ("iCalendar".equals(myForm.getOp())) { sLog.info(" Generating calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort))); try { File file = ApplicationProperties.getTempFile("schedule", "ics"); if (instructor!=null) { printInstructorSchedule(file, instructor, instructorExams); } else { printStudentSchedule(file, student, studentExams); } request.setAttribute(Constants.REQUEST_OPEN_URL, "temp/"+file.getName()); } catch (Exception e) { sLog.error("Unable to generate calendar for "+(instructor!=null?instructor.getName(DepartmentalInstructor.sNameFormatShort):student.getName(DepartmentalInstructor.sNameFormatShort)),e); } } */ if (!studentExams.isEmpty()) { myForm.setCanExport(true); TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (ExamOwner examOwner : studentExams) exams.add(new ExamAssignmentInfo(examOwner, student, studentExams)); PdfWebTable table = getStudentExamSchedule(true, exams, student); request.setAttribute("schedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o1"))); table = getStudentConflits(true, exams, student); if (!table.getLines().isEmpty()) request.setAttribute("conf", table.printTable(WebTable.getOrder(sessionContext, "exams.o3"))); } if (!instructorExams.isEmpty()) { myForm.setCanExport(true); TreeSet<ExamAssignmentInfo> exams = new TreeSet<ExamAssignmentInfo>(); for (Exam exam : instructorExams) exams.add(new ExamAssignmentInfo(exam, useCache)); PdfWebTable table = getInstructorExamSchedule(true, exams, instructor); request.setAttribute("ischedule", table.printTable(WebTable.getOrder(sessionContext, "exams.o2"))); table = getInstructorConflits(true, exams, instructor); if (!table.getLines().isEmpty()) request.setAttribute("iconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o4"))); table = getStudentConflits(true, exams, instructor); if (!table.getLines().isEmpty()) request.setAttribute("sconf", table.printTable(WebTable.getOrder(sessionContext, "exams.o5"))); } long t1 = System.currentTimeMillis(); sLog.info("Request processed in " + new DecimalFormat("0.00").format(((double) (t1 - t0)) / 1000.0) + " s for " + (instructor != null ? instructor.getName(DepartmentalInstructor.sNameFormatShort) : student != null ? student.getName(DepartmentalInstructor.sNameFormatShort) : userName)); return mapping.findForward("show"); }