List of usage examples for javax.servlet.http HttpServletRequest getCharacterEncoding
public String getCharacterEncoding();
From source file:org.ofbiz.webapp.event.ServiceEventHandler.java
/** * @see org.ofbiz.webapp.event.EventHandler#invoke(ConfigXMLReader.Event, ConfigXMLReader.RequestMap, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */// w ww .j a v a2s. c o m public String invoke(Event event, RequestMap requestMap, HttpServletRequest request, HttpServletResponse response) throws EventHandlerException { // make sure we have a valid reference to the Service Engine LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); if (dispatcher == null) { throw new EventHandlerException("The local service dispatcher is null"); } DispatchContext dctx = dispatcher.getDispatchContext(); if (dctx == null) { throw new EventHandlerException("Dispatch context cannot be found"); } // get the details for the service(s) to call String mode = SYNC; String serviceName = null; if (UtilValidate.isEmpty(event.path)) { mode = SYNC; } else { mode = event.path; } // make sure we have a defined service to call serviceName = event.invoke; if (serviceName == null) { throw new EventHandlerException("Service name (eventMethod) cannot be null"); } if (Debug.verboseOn()) Debug.logVerbose("[Set mode/service]: " + mode + "/" + serviceName, module); // some needed info for when running the service Locale locale = UtilHttp.getLocale(request); TimeZone timeZone = UtilHttp.getTimeZone(request); HttpSession session = request.getSession(); GenericValue userLogin = (GenericValue) session.getAttribute("userLogin"); // get the service model to generate context ModelService model = null; try { model = dctx.getModelService(serviceName); } catch (GenericServiceException e) { throw new EventHandlerException("Problems getting the service model", e); } if (model == null) { throw new EventHandlerException("Problems getting the service model"); } if (Debug.verboseOn()) { Debug.logVerbose("[Processing]: SERVICE Event", module); Debug.logVerbose("[Using delegator]: " + dispatcher.getDelegator().getDelegatorName(), module); } boolean isMultiPart = ServletFileUpload.isMultipartContent(request); Map<String, Object> multiPartMap = new HashMap<String, Object>(); if (isMultiPart) { // get the http upload configuration String maxSizeStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.size", "-1", dctx.getDelegator()); long maxUploadSize = -1; try { maxUploadSize = Long.parseLong(maxSizeStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the max upload size from general.properties; using default -1", module); maxUploadSize = -1; } // get the http size threshold configuration - files bigger than this will be // temporarly stored on disk during upload String sizeThresholdStr = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.max.sizethreshold", "10240", dctx.getDelegator()); int sizeThreshold = 10240; // 10K try { sizeThreshold = Integer.parseInt(sizeThresholdStr); } catch (NumberFormatException e) { Debug.logError(e, "Unable to obtain the threshold size from general.properties; using default 10K", module); sizeThreshold = -1; } // directory used to temporarily store files that are larger than the configured size threshold String tmpUploadRepository = EntityUtilProperties.getPropertyValue("general.properties", "http.upload.tmprepository", "runtime/tmp", dctx.getDelegator()); String encoding = request.getCharacterEncoding(); // check for multipart content types which may have uploaded items ServletFileUpload upload = new ServletFileUpload( new DiskFileItemFactory(sizeThreshold, new File(tmpUploadRepository))); // create the progress listener and add it to the session FileUploadProgressListener listener = new FileUploadProgressListener(); upload.setProgressListener(listener); session.setAttribute("uploadProgressListener", listener); if (encoding != null) { upload.setHeaderEncoding(encoding); } upload.setSizeMax(maxUploadSize); List<FileItem> uploadedItems = null; try { uploadedItems = UtilGenerics.<FileItem>checkList(upload.parseRequest(request)); } catch (FileUploadException e) { throw new EventHandlerException("Problems reading uploaded data", e); } if (uploadedItems != null) { for (FileItem item : uploadedItems) { String fieldName = item.getFieldName(); //byte[] itemBytes = item.get(); /* Debug.logInfo("Item Info [" + fieldName + "] : " + item.getName() + " / " + item.getSize() + " / " + item.getContentType() + " FF: " + item.isFormField(), module); */ if (item.isFormField() || item.getName() == null) { if (multiPartMap.containsKey(fieldName)) { Object mapValue = multiPartMap.get(fieldName); if (mapValue instanceof List<?>) { checkList(mapValue, Object.class).add(item.getString()); } else if (mapValue instanceof String) { List<String> newList = new LinkedList<String>(); newList.add((String) mapValue); newList.add(item.getString()); multiPartMap.put(fieldName, newList); } else { Debug.logWarning("Form field found [" + fieldName + "] which was not handled!", module); } } else { if (encoding != null) { try { multiPartMap.put(fieldName, item.getString(encoding)); } catch (java.io.UnsupportedEncodingException uee) { Debug.logError(uee, "Unsupported Encoding, using deafault", module); multiPartMap.put(fieldName, item.getString()); } } else { multiPartMap.put(fieldName, item.getString()); } } } else { String fileName = item.getName(); if (fileName.indexOf('\\') > -1 || fileName.indexOf('/') > -1) { // get just the file name IE and other browsers also pass in the local path int lastIndex = fileName.lastIndexOf('\\'); if (lastIndex == -1) { lastIndex = fileName.lastIndexOf('/'); } if (lastIndex > -1) { fileName = fileName.substring(lastIndex + 1); } } multiPartMap.put(fieldName, ByteBuffer.wrap(item.get())); multiPartMap.put("_" + fieldName + "_size", Long.valueOf(item.getSize())); multiPartMap.put("_" + fieldName + "_fileName", fileName); multiPartMap.put("_" + fieldName + "_contentType", item.getContentType()); } } } } // store the multi-part map as an attribute so we can access the parameters request.setAttribute("multiPartMap", multiPartMap); Map<String, Object> rawParametersMap = UtilHttp.getParameterMap(request, null, null); Set<String> urlOnlyParameterNames = UtilHttp.getUrlOnlyParameterMap(request).keySet(); Map<String, Object> requestBodyMap = null; try { requestBodyMap = RequestBodyMapHandlerFactory.extractMapFromRequestBody(request); } catch (IOException ioe) { Debug.logWarning(ioe, module); } if (requestBodyMap != null) { rawParametersMap.putAll(requestBodyMap); } // we have a service and the model; build the context Map<String, Object> serviceContext = new HashMap<String, Object>(); for (ModelParam modelParam : model.getInModelParamList()) { String name = modelParam.name; // don't include userLogin, that's taken care of below if ("userLogin".equals(name)) continue; // don't include locale, that is also taken care of below if ("locale".equals(name)) continue; // don't include timeZone, that is also taken care of below if ("timeZone".equals(name)) continue; Object value = null; if (UtilValidate.isNotEmpty(modelParam.stringMapPrefix)) { Map<String, Object> paramMap = UtilHttp.makeParamMapWithPrefix(request, multiPartMap, modelParam.stringMapPrefix, null); value = paramMap; if (Debug.verboseOn()) Debug.logVerbose("Set [" + modelParam.name + "]: " + paramMap, module); } else if (UtilValidate.isNotEmpty(modelParam.stringListSuffix)) { List<Object> paramList = UtilHttp.makeParamListWithSuffix(request, multiPartMap, modelParam.stringListSuffix, null); value = paramList; } else { // first check the multi-part map value = multiPartMap.get(name); // next check attributes; do this before parameters so that attribute which can be changed by code can override parameters which can't if (UtilValidate.isEmpty(value)) { Object tempVal = request .getAttribute(UtilValidate.isEmpty(modelParam.requestAttributeName) ? name : modelParam.requestAttributeName); if (tempVal != null) { value = tempVal; } } // check the request parameters if (UtilValidate.isEmpty(value)) { ServiceEventHandler.checkSecureParameter(requestMap, urlOnlyParameterNames, name, session, serviceName, dctx.getDelegator()); // if the service modelParam has allow-html="any" then get this direct from the request instead of in the parameters Map so there will be no canonicalization possibly messing things up if ("any".equals(modelParam.allowHtml)) { value = request.getParameter(name); } else { // use the rawParametersMap from UtilHttp in order to also get pathInfo parameters, do canonicalization, etc value = rawParametersMap.get(name); } // make any composite parameter data (e.g., from a set of parameters {name_c_date, name_c_hour, name_c_minutes}) if (value == null) { value = UtilHttp.makeParamValueFromComposite(request, name, locale); } } // then session if (UtilValidate.isEmpty(value)) { Object tempVal = request.getSession() .getAttribute(UtilValidate.isEmpty(modelParam.sessionAttributeName) ? name : modelParam.sessionAttributeName); if (tempVal != null) { value = tempVal; } } // no field found if (value == null) { //still null, give up for this one continue; } if (value instanceof String && ((String) value).length() == 0) { // interpreting empty fields as null values for each in back end handling... value = null; } } // set even if null so that values will get nulled in the db later on serviceContext.put(name, value); } // get only the parameters for this service - converted to proper type // TODO: pass in a list for error messages, like could not convert type or not a proper X, return immediately with messages if there are any List<Object> errorMessages = new LinkedList<Object>(); serviceContext = model.makeValid(serviceContext, ModelService.IN_PARAM, true, errorMessages, timeZone, locale); if (errorMessages.size() > 0) { // uh-oh, had some problems... request.setAttribute("_ERROR_MESSAGE_LIST_", errorMessages); return "error"; } // include the UserLogin value object if (userLogin != null) { serviceContext.put("userLogin", userLogin); } // include the Locale object if (locale != null) { serviceContext.put("locale", locale); } // include the TimeZone object if (timeZone != null) { serviceContext.put("timeZone", timeZone); } // invoke the service Map<String, Object> result = null; try { if (ASYNC.equalsIgnoreCase(mode)) { dispatcher.runAsync(serviceName, serviceContext); } else { result = dispatcher.runSync(serviceName, serviceContext); } } catch (ServiceAuthException e) { // not logging since the service engine already did request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); return "error"; } catch (ServiceValidationException e) { // not logging since the service engine already did request.setAttribute("serviceValidationException", e); if (e.getMessageList() != null) { request.setAttribute("_ERROR_MESSAGE_LIST_", e.getMessageList()); } else { request.setAttribute("_ERROR_MESSAGE_", e.getNonNestedMessage()); } return "error"; } catch (GenericServiceException e) { Debug.logError(e, "Service invocation error", module); throw new EventHandlerException("Service invocation error", e.getNested()); } String responseString = null; if (result == null) { responseString = ModelService.RESPOND_SUCCESS; } else { if (!result.containsKey(ModelService.RESPONSE_MESSAGE)) { responseString = ModelService.RESPOND_SUCCESS; } else { responseString = (String) result.get(ModelService.RESPONSE_MESSAGE); } // set the messages in the request; this will be picked up by messages.ftl and displayed request.setAttribute("_ERROR_MESSAGE_LIST_", result.get(ModelService.ERROR_MESSAGE_LIST)); request.setAttribute("_ERROR_MESSAGE_MAP_", result.get(ModelService.ERROR_MESSAGE_MAP)); request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE)); request.setAttribute("_EVENT_MESSAGE_LIST_", result.get(ModelService.SUCCESS_MESSAGE_LIST)); request.setAttribute("_EVENT_MESSAGE_", result.get(ModelService.SUCCESS_MESSAGE)); // set the results in the request for (Map.Entry<String, Object> rme : result.entrySet()) { String resultKey = rme.getKey(); Object resultValue = rme.getValue(); if (resultKey != null && !ModelService.RESPONSE_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE.equals(resultKey) && !ModelService.ERROR_MESSAGE_LIST.equals(resultKey) && !ModelService.ERROR_MESSAGE_MAP.equals(resultKey) && !ModelService.SUCCESS_MESSAGE.equals(resultKey) && !ModelService.SUCCESS_MESSAGE_LIST.equals(resultKey)) { request.setAttribute(resultKey, resultValue); } } } if (Debug.verboseOn()) Debug.logVerbose("[Event Return]: " + responseString, module); if (("Y").equals(request.getParameter("json"))) { JSONObject json = JSONObject.fromObject(result); String jsonStr = json.toString(); Debug.log(jsonStr); if (jsonStr == null) { // Debug.logError("JSON Object was empty; fatal error!", // module); } // set the X-JSON content type response.setContentType("textml"); // jsonStr.length is not reliable for unicode characters try { response.setCharacterEncoding("UTF-8"); response.setHeader("content-type", "text/html;charset=UTF-8"); response.setContentLength(jsonStr.getBytes("UTF8").length); } catch (UnsupportedEncodingException e) { // Debug.logError("Problems with Json encoding"); } // return the JSON String Writer out; try { out = response.getWriter(); out.write(jsonStr); out.flush(); } catch (IOException e) { // Debug.logError("Unable to get response writer", // module); } return null; } else { return responseString; } }
From source file:org.opencms.main.OpenCmsCore.java
/** * Initializes a {@link CmsObject} with the given users information.<p> * //from www .j av a 2 s. c om * @param request the current http request (or <code>null</code>) * @param user the initialized user * @param siteRoot the users current site * @param projectId the id of the users current project * @param ouFqn the organizational unit * * @return the initialized CmsObject * * @throws CmsException in case something goes wrong */ private CmsObject initCmsObject(HttpServletRequest request, CmsUser user, String siteRoot, CmsUUID projectId, String ouFqn) throws CmsException { CmsProject project = null; try { project = m_securityManager.readProject(projectId); } catch (CmsDbEntryNotFoundException e) { // project not found, switch to online project project = m_securityManager.readProject(CmsProject.ONLINE_PROJECT_ID); } // get requested resource uri and remote IP address, as well as time for "time warp" browsing String requestedResource = null; Long requestTimeAttr = null; String remoteAddr; if (request != null) { // get path info from request requestedResource = getPathInfo(request); // check for special header for remote address remoteAddr = request.getHeader(CmsRequestUtil.HEADER_X_FORWARDED_FOR); if (remoteAddr == null) { // if header is not available, use default remote address remoteAddr = request.getRemoteAddr(); } // check for special "time warp" browsing HttpSession session = request.getSession(false); if (session != null) { // no new session must be created here requestTimeAttr = (Long) session.getAttribute(CmsContextInfo.ATTRIBUTE_REQUEST_TIME); } } else { // if no request is available, the IP is always set to localhost remoteAddr = CmsContextInfo.LOCALHOST; } if (requestedResource == null) { // path info can still be null requestedResource = "/"; } // calculate the request time long requestTime; if (requestTimeAttr == null) { requestTime = System.currentTimeMillis(); } else { requestTime = requestTimeAttr.longValue(); } // get locale and encoding CmsI18nInfo i18nInfo; if (m_localeManager.isInitialized()) { // locale manager is initialized // resolve locale and encoding if (requestedResource.endsWith(OpenCmsServlet.HANDLE_GWT) && (request != null)) { // GWT RPC call, always keep the request encoding and use the default locale i18nInfo = new CmsI18nInfo(CmsLocaleManager.getDefaultLocale(), request.getCharacterEncoding()); } else { String resourceName; if (requestedResource.startsWith(CmsWorkplace.VFS_PATH_SYSTEM)) { // add site root only if resource name does not start with "/system" resourceName = requestedResource; } else if (OpenCms.getSiteManager().startsWithShared(requestedResource)) { resourceName = requestedResource; } else { resourceName = siteRoot.concat(requestedResource); } i18nInfo = m_localeManager.getI18nInfo(request, user, project, resourceName); } } else { // locale manager not initialized, this will be true _only_ during system startup // the values set does not matter, no locale information form VFS is used on system startup // this is just to protect against null pointer exceptions i18nInfo = new CmsI18nInfo(Locale.ENGLISH, getSystemInfo().getDefaultEncoding()); } // decode the requested resource, always using UTF-8 requestedResource = CmsEncoder.decode(requestedResource); // initialize the context info CmsContextInfo contextInfo = new CmsContextInfo(user, project, requestedResource, siteRoot, i18nInfo.getLocale(), i18nInfo.getEncoding(), remoteAddr, requestTime, ouFqn); // now generate and return the CmsObject return initCmsObject(contextInfo); }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Show HTTP header information.//from w w w. ja v a 2 s . co m */ @SuppressWarnings("unchecked") protected void showRequestInfo(HttpServletRequest req) { if (M_log.isDebugEnabled()) M_log.debug("DefaultServlet Request Info"); // Show generic info if (M_log.isDebugEnabled()) M_log.debug("Encoding : " + req.getCharacterEncoding()); if (M_log.isDebugEnabled()) M_log.debug("Length : " + req.getContentLength()); if (M_log.isDebugEnabled()) M_log.debug("Type : " + req.getContentType()); if (M_log.isDebugEnabled()) M_log.debug("Parameters"); Enumeration parameters = req.getParameterNames(); while (parameters.hasMoreElements()) { String paramName = (String) parameters.nextElement(); String[] values = req.getParameterValues(paramName); System.out.print(paramName + " : "); for (int i = 0; i < values.length; i++) { System.out.print(values[i] + ", "); } } if (M_log.isDebugEnabled()) M_log.debug("Protocol : " + req.getProtocol()); if (M_log.isDebugEnabled()) M_log.debug("Address : " + req.getRemoteAddr()); if (M_log.isDebugEnabled()) M_log.debug("Host : " + req.getRemoteHost()); if (M_log.isDebugEnabled()) M_log.debug("Scheme : " + req.getScheme()); if (M_log.isDebugEnabled()) M_log.debug("Server Name : " + req.getServerName()); if (M_log.isDebugEnabled()) M_log.debug("Server Port : " + req.getServerPort()); if (M_log.isDebugEnabled()) M_log.debug("Attributes"); Enumeration attributes = req.getAttributeNames(); while (attributes.hasMoreElements()) { String attributeName = (String) attributes.nextElement(); System.out.print(attributeName + " : "); if (M_log.isDebugEnabled()) M_log.debug(req.getAttribute(attributeName).toString()); } // Show HTTP info if (M_log.isDebugEnabled()) M_log.debug("HTTP Header Info"); if (M_log.isDebugEnabled()) M_log.debug("Authentication Type : " + req.getAuthType()); if (M_log.isDebugEnabled()) M_log.debug("HTTP Method : " + req.getMethod()); if (M_log.isDebugEnabled()) M_log.debug("Path Info : " + req.getPathInfo()); if (M_log.isDebugEnabled()) M_log.debug("Path translated : " + req.getPathTranslated()); if (M_log.isDebugEnabled()) M_log.debug("Query string : " + req.getQueryString()); if (M_log.isDebugEnabled()) M_log.debug("Remote user : " + req.getRemoteUser()); if (M_log.isDebugEnabled()) M_log.debug("Requested session id : " + req.getRequestedSessionId()); if (M_log.isDebugEnabled()) M_log.debug("Request URI : " + req.getRequestURI()); if (M_log.isDebugEnabled()) M_log.debug("Context path : " + req.getContextPath()); if (M_log.isDebugEnabled()) M_log.debug("Servlet path : " + req.getServletPath()); if (M_log.isDebugEnabled()) M_log.debug("User principal : " + req.getUserPrincipal()); if (M_log.isDebugEnabled()) M_log.debug("Headers : "); Enumeration headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = (String) headers.nextElement(); System.out.print(headerName + " : "); if (M_log.isDebugEnabled()) M_log.debug(req.getHeader(headerName)); } }
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 w w . j a 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 . ja va 2 s .c om 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.wings.session.WingServlet.java
public final SessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response, boolean createSessionServlet) throws ServletException { final HttpSession httpSession = request.getSession(true); // it should be enough to synchronize on the http session object... synchronized (httpSession) { SessionServlet sessionServlet = null; if (httpSession != null) { sessionServlet = (SessionServlet) httpSession.getAttribute(lookupName); }//from ww w . ja v a 2s. c o m // Sanity check - maybe this is a stored/deserialized session servlet? if (sessionServlet != null && !sessionServlet.isValid()) { sessionServlet.destroy(); sessionServlet = null; } /* * we are only interested in a new session, if the response is * not null. If it is null, then we just called getSessionServlet() * for lookup purposes and are satisfied, if we don't get anything. */ if (sessionServlet == null) { if (createSessionServlet) { log.info("no session servlet, create new one"); sessionServlet = newSession(request, response); httpSession.setAttribute(lookupName, sessionServlet); } else { return null; } } if (log.isDebugEnabled()) { StringBuilder message = new StringBuilder().append("session id: ") .append(request.getRequestedSessionId()).append(", created at: ") .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) .format(new java.util.Date(httpSession.getCreationTime()))) .append(", identified via:") .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "") .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ") .append(httpSession.getMaxInactiveInterval()).append("s "); log.debug(message.toString()); //log.debug("session valid " + request.isRequestedSessionIdValid()); //log.debug("session httpsession id " + httpSession.getId()); //log.debug("session httpsession new " + httpSession.isNew()); //log.debug("session last accessed at " + // new java.util.Date(httpSession.getLastAccessedTime())); //log.debug("session expiration timeout (s) " + // httpSession.getMaxInactiveInterval()); //log.debug("session contains wings session " + // (httpSession.getAttribute(lookupName) != null)); } sessionServlet.getSession().getExternalizeManager().setResponse(response); /* Handling of the requests character encoding. * -------------------------------------------- * The following block is needed for a correct handling of * non-ISO-8859-1 data: * * Using LocaleCharacterSet and/or charset.properties we can * advise the client to use i.e. UTF-8 as character encoding. * Once told the browser consequently also encodes his requests * in the choosen characterset of the sings session. This is * achieved by adding the HTML code * <meta http-equiv="Content-Type" content="text/html;charset="<charset>"> * to the generated pages. * * If the user hasn't overridden the encoding in their browser, * then all form data (e.g. mueller) is submitted with data encoded * like m%C3%BCller because byte pair C3 BC is how the german * u-umlaut is represented in UTF-8. If the form is * iso-8859-1 encoded then you get m%FCller, because byte FC is * how it is presented in iso-8859-1. * * So the browser behaves correctly by sending his form input * correctly encoded in the advised character encoding. The issue * is that the servlet container is typically unable to determine * the correct encoding of this form data. By proposal the browser * should als declare the used character encoding for his data. * But actual browsers omit this information and hence the servlet * container is unable to guess the right encoding (Tomcat actually * thenalways guesses ISO 8859-1). This results in totally * scrumbled up data for all non ISO-8859-1 character encodings. * With the block below we tell the servlet container about the * character encoding we expect in the browsers request and hence * the servlet container can do the correct decoding. * This has to be done at very first, otherwise the servlet * container will ignore this setting. */ if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding? try { String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding(); // We know better about the used character encoding than tomcat log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding); request.setCharacterEncoding(sessionCharacterEncoding); } catch (UnsupportedEncodingException e) { log.warn("Problem on applying current session character encoding", e); } } return sessionServlet; } }
From source file:org.wings.session.PortletWingServlet.java
public final PortletSessionServlet getSessionServlet(HttpServletRequest request, HttpServletResponse response, boolean createSessionServlet) throws ServletException { // WingS-Portlet-Bridge: for the bridge we are using the portletSession to // seperate between the instances of one portlet through the portlet scope RenderRequest renderRequest = (RenderRequest) request.getAttribute(Const.REQUEST_ATTR_RENDER_REQUEST); if (renderRequest == null) { log.error("WingS-Portlet-Bridge: cant get RenderRequest because " + "the request attribute " + Const.REQUEST_ATTR_RENDER_REQUEST + " is null!"); }/*from w w w .j a v a2s . com*/ final PortletSession portletSession = renderRequest.getPortletSession(); // WingS-Portlet-Bridge: get the wings mainclass for current mode String lookupName = "SessionServlet"; lookupName = "SessionServlet:" + (String) renderRequest.getAttribute(Const.REQUEST_ATTR_WINGS_CLASS); log.info("WingS-Portlet-Bridge: loaded mainclass " + lookupName + " for PortletSessionServlet identificaction"); // it should be enough to synchronize on the http session object... synchronized (portletSession) { PortletSessionServlet sessionServlet = null; if (portletSession != null) { // WingS-Portlet-Bridge: changed for portlet scope sessionServlet = (PortletSessionServlet) portletSession.getAttribute(lookupName, PortletSession.PORTLET_SCOPE); } // Sanity check - maybe this is a stored/deserialized session servlet? if (sessionServlet != null && !sessionServlet.isValid()) { sessionServlet.destroy(); sessionServlet = null; log.debug("session servlet exists but is not valid"); } /* * we are only interested in a new session, if the response is * not null. If it is null, then we just called getSessionServlet() * for lookup purposes and are satisfied, if we don't get anything. */ if (sessionServlet == null) { if (createSessionServlet) { log.info("no session servlet, create new one"); sessionServlet = newSession(request, response); portletSession.setAttribute(lookupName, sessionServlet, PortletSession.PORTLET_SCOPE); } else { return null; } } if (log.isDebugEnabled()) { StringBuilder message = new StringBuilder().append("session id: ") .append(request.getRequestedSessionId()).append(", created at: ") .append(DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) .format(new java.util.Date(portletSession.getCreationTime()))) .append(", identified via:") .append(request.isRequestedSessionIdFromCookie() ? " cookie" : "") .append(request.isRequestedSessionIdFromURL() ? " URL" : "").append(", expiring after: ") .append(portletSession.getMaxInactiveInterval()).append("s "); log.debug(message.toString()); //log.debug("session valid " + request.isRequestedSessionIdValid()); //log.debug("session httpsession id " + httpSession.getId()); //log.debug("session httpsession new " + httpSession.isNew()); //log.debug("session last accessed at " + // new java.util.Date(httpSession.getLastAccessedTime())); //log.debug("session expiration timeout (s) " + // httpSession.getMaxInactiveInterval()); //log.debug("session contains wings session " + // (httpSession.getAttribute(lookupName) != null)); } sessionServlet.getSession().getExternalizeManager().setResponse(response); /* Handling of the requests character encoding. * -------------------------------------------- * The following block is needed for a correct handling of * non-ISO-8859-1 data: * * Using LocaleCharacterSet and/or charset.properties we can * advise the client to use i.e. UTF-8 as character encoding. * Once told the browser consequently also encodes his requests * in the choosen characterset of the sings session. This is * achieved by adding the HTML code * <meta http-equiv="Content-Type" content="text/html;charset="<charset>"> * to the generated pages. * * If the user hasn't overridden the encoding in their browser, * then all form data (e.g. mueller) is submitted with data encoded * like m%C3%BCller because byte pair C3 BC is how the german * u-umlaut is represented in UTF-8. If the form is * iso-8859-1 encoded then you get m%FCller, because byte FC is * how it is presented in iso-8859-1. * * So the browser behaves correctly by sending his form input * correctly encoded in the advised character encoding. The issue * is that the servlet container is typically unable to determine * the correct encoding of this form data. By proposal the browser * should als declare the used character encoding for his data. * But actual browsers omit this information and hence the servlet * container is unable to guess the right encoding (Tomcat actually * thenalways guesses ISO 8859-1). This results in totally * scrumbled up data for all non ISO-8859-1 character encodings. * With the block below we tell the servlet container about the * character encoding we expect in the browsers request and hence * the servlet container can do the correct decoding. * This has to be done at very first, otherwise the servlet * container will ignore this setting. */ if ((request.getCharacterEncoding() == null)) { // was servlet container able to identify encoding? try { String sessionCharacterEncoding = sessionServlet.getSession().getCharacterEncoding(); // We know better about the used character encoding than tomcat log.debug("Advising servlet container to interpret request as " + sessionCharacterEncoding); request.setCharacterEncoding(sessionCharacterEncoding); } catch (UnsupportedEncodingException e) { log.warn("Problem on applying current session character encoding", e); } } return sessionServlet; } }
From source file:org.apache.tapestry.engine.AbstractEngine.java
/** * Invoked from {@link #service(RequestContext)} to ensure that the engine's * instance variables are setup. This allows the application a chance to * restore transient variables that will not have survived deserialization. * * Determines the servlet prefix: this is the base URL used by * {@link IEngineService services} to build URLs. It consists * of two parts: the context path and the servlet path. * * <p>The servlet path is retrieved from {@link HttpServletRequest#getServletPath()}. * * <p>The context path is retrieved from {@link HttpServletRequest#getContextPath()}. * * <p>The global object is retrieved from {@link IEngine#getGlobal()} method. * * <p>The final path is available via the {@link #getServletPath()} method. * * <p>In addition, this method locates and/or creates the: * <ul>/* w w w .j a v a 2s. c o m*/ * <li>{@link IComponentClassEnhancer} * <li>{@link Pool} * <li>{@link ITemplateSource} * <li>{@link ISpecificationSource} * <li>{@link IPageSource} * <li>{@link IEngineService} {@link Map} * <ll>{@link IScriptSource} * <li>{@link IComponentMessagesSource} * <li>{@link IPropertySource} * </ul> * * <p>This order is important, because some of the later shared objects * depend on some of the earlier shared objects already having * been located or created * (especially {@link #getPool() pool}). * * <p>Subclasses should invoke this implementation first, then perform their * own setup. * **/ protected void setupForRequest(RequestContext context) { HttpServlet servlet = context.getServlet(); ServletContext servletContext = servlet.getServletContext(); HttpServletRequest request = context.getRequest(); HttpSession session = context.getSession(); if (session != null) _sessionId = context.getSession().getId(); else _sessionId = null; // Previously, this used getRemoteHost(), but that requires an // expensive reverse DNS lookup. Possibly, the host name lookup // should occur ... but only if there's an actual error message // to display. if (_clientAddress == null) _clientAddress = request.getRemoteAddr(); // servletPath is null, so this means either we're doing the // first request in this session, or we're handling a subsequent // request in another JVM (i.e. another server in the cluster). // In any case, we have to do some late (re-)initialization. if (_servletPath == null) { // Get the path *within* the servlet context // In rare cases related to the tagsupport service, getServletPath() is wrong // (its a JSP, which invokes Tapestry as an include, thus muddling what // the real servlet and servlet path is). In those cases, the JSP tag // will inform us. String path = (String) request.getAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE); if (path == null) path = request.getServletPath(); // Get the context path, which may be the empty string // (but won't be null). _contextPath = request.getContextPath(); _servletPath = _contextPath + path; } String servletName = context.getServlet().getServletName(); if (_propertySource == null) { String name = PROPERTY_SOURCE_NAME + ":" + servletName; _propertySource = (IPropertySource) servletContext.getAttribute(name); if (_propertySource == null) { _propertySource = createPropertySource(context); servletContext.setAttribute(name, _propertySource); } } if (_enhancer == null) { String name = ENHANCER_NAME + ":" + servletName; _enhancer = (IComponentClassEnhancer) servletContext.getAttribute(name); if (_enhancer == null) { _enhancer = createComponentClassEnhancer(context); servletContext.setAttribute(name, _enhancer); } } if (_pool == null) { String name = POOL_NAME + ":" + servletName; _pool = (Pool) servletContext.getAttribute(name); if (_pool == null) { _pool = createPool(context); servletContext.setAttribute(name, _pool); } } if (_templateSource == null) { String name = TEMPLATE_SOURCE_NAME + ":" + servletName; _templateSource = (ITemplateSource) servletContext.getAttribute(name); if (_templateSource == null) { _templateSource = createTemplateSource(context); servletContext.setAttribute(name, _templateSource); } } if (_specificationSource == null) { String name = SPECIFICATION_SOURCE_NAME + ":" + servletName; _specificationSource = (ISpecificationSource) servletContext.getAttribute(name); if (_specificationSource == null) { _specificationSource = createSpecificationSource(context); servletContext.setAttribute(name, _specificationSource); } } if (_pageSource == null) { String name = PAGE_SOURCE_NAME + ":" + servletName; _pageSource = (IPageSource) servletContext.getAttribute(name); if (_pageSource == null) { _pageSource = createPageSource(context); servletContext.setAttribute(name, _pageSource); } } if (_scriptSource == null) { String name = SCRIPT_SOURCE_NAME + ":" + servletName; _scriptSource = (IScriptSource) servletContext.getAttribute(name); if (_scriptSource == null) { _scriptSource = createScriptSource(context); servletContext.setAttribute(name, _scriptSource); } } if (_serviceMap == null) { String name = SERVICE_MAP_NAME + ":" + servletName; _serviceMap = (Map) servletContext.getAttribute(name); if (_serviceMap == null) { _serviceMap = createServiceMap(); servletContext.setAttribute(name, _serviceMap); } } if (_stringsSource == null) { String name = STRINGS_SOURCE_NAME + ":" + servletName; _stringsSource = (IComponentMessagesSource) servletContext.getAttribute(name); if (_stringsSource == null) { _stringsSource = createComponentStringsSource(context); servletContext.setAttribute(name, _stringsSource); } } if (_dataSqueezer == null) { String name = DATA_SQUEEZER_NAME + ":" + servletName; _dataSqueezer = (DataSqueezer) servletContext.getAttribute(name); if (_dataSqueezer == null) { _dataSqueezer = createDataSqueezer(); servletContext.setAttribute(name, _dataSqueezer); } } if (_global == null) { String name = GLOBAL_NAME + ":" + servletName; _global = servletContext.getAttribute(name); if (_global == null) { _global = createGlobal(context); servletContext.setAttribute(name, _global); } } if (_resourceChecksumSource == null) { String name = RESOURCE_CHECKSUM_SOURCE_NAME + ":" + servletName; _resourceChecksumSource = (ResourceChecksumSource) servletContext.getAttribute(name); if (_resourceChecksumSource == null) { _resourceChecksumSource = createResourceChecksumSource(); servletContext.setAttribute(name, _resourceChecksumSource); } } String encoding = request.getCharacterEncoding(); if (encoding == null) { encoding = getOutputEncoding(); try { request.setCharacterEncoding(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(Tapestry.format("illegal-encoding", encoding)); } catch (NoSuchMethodError e) { // Servlet API 2.2 compatibility // Behave okay if the setCharacterEncoding() method is unavailable } catch (AbstractMethodError e) { // Servlet API 2.2 compatibility // Behave okay if the setCharacterEncoding() method is unavailable } } }
From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java
public void buildInputDocument(Context context, Object inputData) throws Exception { Engine.logBeans.debug("[WebServiceTranslator] Making input document"); HttpServletRequest request = (HttpServletRequest) inputData; SOAPMessage requestMessage = (SOAPMessage) request .getAttribute(WebServiceServlet.REQUEST_MESSAGE_ATTRIBUTE); SOAPPart sp = requestMessage.getSOAPPart(); SOAPEnvelope se = sp.getEnvelope(); SOAPBody sb = se.getBody();/*from w ww. j a v a 2 s .c o m*/ Iterator<?> iterator = sb.getChildElements(); SOAPElement method, parameter; String methodName; InputDocumentBuilder inputDocumentBuilder = new InputDocumentBuilder(context); while (iterator.hasNext()) { List<RequestableVariable> variableList = null; // jmc 12/06/26 Object element = iterator.next(); if (element instanceof SOAPElement) { method = (SOAPElement) element; methodName = method.getElementName().getLocalName(); Engine.logBeans.debug("[WebServiceTranslator] Requested web service name: " + methodName); int i = methodName.indexOf("__"); // for statefull transaction, don't replace the project if (context.project == null || !context.project.getName().equals(context.projectName)) { context.project = Engine.theApp.databaseObjectsManager.getProjectByName(context.projectName); } String connectorName = null; if (i == -1) { context.connectorName = null; context.sequenceName = methodName; } else { connectorName = methodName.substring(0, i); context.transactionName = methodName.substring(i + 2); } if ((connectorName != null) && (!connectorName.equals(context.connectorName))) { Engine.logBeans.debug("Connector name differs from previous one; requiring new session"); context.isNewSession = true; context.connectorName = connectorName; Engine.logBeans.debug("[WebServiceTranslator] The connector is overridden to \"" + context.connectorName + "\"."); } Engine.logBeans.debug("[WebServiceTranslator] Connector: " + (context.connectorName == null ? "(default)" : context.connectorName)); Engine.logBeans.debug("[WebServiceTranslator] Transaction: " + context.transactionName); //Connector connector = (context.connectorName == null ? context.project.getDefaultConnector() : context.project.getConnectorByName(context.connectorName)); //Transaction transaction = (context.transactionName == null ? connector.getDefaultTransaction() : connector.getTransactionByName(context.transactionName)); RequestableObject requestable = null; if (context.sequenceName != null) { requestable = context.project.getSequenceByName(context.sequenceName); variableList = ((Sequence) requestable).getVariablesList(); } else if (context.connectorName != null) { if (context.transactionName != null) { requestable = context.project.getConnectorByName(context.connectorName) .getTransactionByName(context.transactionName); if (requestable instanceof TransactionWithVariables) { variableList = ((TransactionWithVariables) requestable).getVariablesList(); } } } Iterator<?> iterator2 = method.getChildElements(); String parameterName, parameterValue; while (iterator2.hasNext()) { element = iterator2.next(); if (element instanceof SOAPElement) { parameter = (SOAPElement) element; parameterName = parameter.getElementName().getLocalName(); parameterValue = parameter.getValue(); if (parameterValue == null) { parameterValue = ""; } if (variableList != null) { // jmc 12/06/26 hide hidden variables in sequences String str = (String) Visibility.Logs.replaceVariables(variableList, "" + parameterName + "=\"" + parameterValue + "\""); Engine.logBeans.debug(" Parameter: " + str); } else Engine.logBeans.debug(" Parameter: " + parameterName + "=\"" + parameterValue + "\""); // Handle convertigo parameters if (parameterName.startsWith("__")) { webServiceServletRequester.handleParameter(parameterName, parameterValue); } // Common parameter handling if (inputDocumentBuilder.handleSpecialParameter(parameterName, parameterValue)) { // handled } // Compatibility for Convertigo 2.x else if (parameterName.equals("context")) { // Just ignore it } else { SOAPElement soapArrayElement = null; Iterator<?> iterator3; String href = parameter.getAttributeValue(se.createName("href")); String arrayType = parameter.getAttributeValue(se.createName("soapenc:arrayType")); if (arrayType == null) { iterator3 = parameter.getAllAttributes(); while (iterator3.hasNext()) { element = iterator3.next(); if (element instanceof Name) { String s = ((Name) element).getQualifiedName(); if (s.equals("soapenc:arrayType")) { arrayType = s; break; } } } } // Array (Microsoft .net) if (href != null) { Engine.logBeans.debug("Deserializing Microsoft .net array"); iterator3 = sb.getChildElements(); while (iterator3.hasNext()) { element = iterator3.next(); if (element instanceof SOAPElement) { soapArrayElement = (SOAPElement) element; String elementId = soapArrayElement.getAttributeValue(se.createName("id")); if (elementId != null) { if (href.equals("#" + elementId)) { iterator3 = soapArrayElement.getChildElements(); while (iterator3.hasNext()) { element = iterator3.next(); if (element instanceof SOAPElement) { break; } } break; } } } } // Find the element with href id iterator3 = sb.getChildElements(); while (iterator3.hasNext()) { element = iterator3.next(); if (element instanceof SOAPElement) { soapArrayElement = (SOAPElement) element; String elementId = soapArrayElement.getAttributeValue(se.createName("id")); if (elementId != null) { if (href.equals("#" + elementId)) { break; } } } } } // Array (Java/Axis) else if (arrayType != null) { Engine.logBeans.debug("Deserializing Java/Axis array"); soapArrayElement = parameter; } // If the node has children nodes, we assume it is an array. else if (parameter.getChildElements().hasNext()) { if (isSoapArray((IVariableContainer) requestable, parameterName)) { Engine.logBeans.debug("Deserializing array"); soapArrayElement = parameter; } } // Deserializing array if (soapArrayElement != null) { iterator3 = soapArrayElement.getChildElements(); while (iterator3.hasNext()) { element = iterator3.next(); if (element instanceof SOAPElement) { soapArrayElement = (SOAPElement) element; parameterValue = soapArrayElement.getValue(); if (parameterValue == null) parameterValue = ""; handleSimpleVariable(context.inputDocument, soapArrayElement, parameterName, parameterValue, inputDocumentBuilder.transactionVariablesElement); } } } // Deserializing simple variable else { handleSimpleVariable(context.inputDocument, parameter, parameterName, parameterValue, inputDocumentBuilder.transactionVariablesElement); } } } } if (Engine.logBeans.isDebugEnabled()) { String soapMessage = SOAPUtils.toString(requestMessage, request.getCharacterEncoding()); if (requestable instanceof TransactionWithVariables) Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n" + Visibility.Logs.replaceVariables( ((TransactionWithVariables) (requestable)).getVariablesList(), request)); else if (requestable instanceof Sequence) Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n" + Visibility.Logs .replaceVariables(((Sequence) (requestable)).getVariablesList(), request)); else Engine.logBeans.debug("[WebServiceTranslator] SOAP message received:\n" + soapMessage); } break; } } Engine.logBeans.debug("[WebServiceTranslator] SOAP message analyzed"); Engine.logBeans.debug("[WebServiceTranslator] Input document created"); }
From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java
@Override public String getDestination(String function, VersioningSessionController versioningSC, HttpServletRequest request) { String destination = ""; SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "User=" + versioningSC.getUserId() + " Function=" + function); String rootDestination = "/versioningPeas/jsp/"; ResourceLocator messages = new ResourceLocator( "com.stratelia.silverpeas.versioningPeas.multilang.versioning", versioningSC.getLanguage()); try {/*from www .j a v a 2 s .c om*/ String flag = versioningSC.getProfile(); request.setAttribute("Profile", flag); if (function.startsWith("ViewReadersList")) { List<Group> groups = new ArrayList<Group>(); List<String> users = new ArrayList<String>(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.READER); if (profile != null) { groups = versioningSC.groupIds2Groups(profile.getAllGroups()); users = versioningSC.userIds2Users(profile.getAllUsers()); } request.setAttribute("Groups", groups); request.setAttribute("Users", users); destination = rootDestination + "ReadList.jsp"; } else if (function.startsWith("ViewWritersList")) { Document document = versioningSC.getEditingDocument(); ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { workers = document.getWorkList(); if (document.getCurrentWorkListOrder() == Integer .parseInt(VersioningSessionController.WRITERS_LIST_ORDERED) && !versioningSC.isAlreadyMerged() && !profile.getAllGroups().isEmpty()) { // Need to merge users from groups with other users workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); } } request.setAttribute("Workers", workers); destination = rootDestination + "WorkList.jsp"; } else if (function.startsWith("ChangeOrder")) { String lines = request.getParameter("lines"); Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); if (lines != null) { int users_count = Integer.parseInt(lines); if (users_count == users.size()) { ArrayList<Worker> new_users = new ArrayList<Worker>(users_count); for (int i = 0; i < users_count; i++) { Worker user = users.get(i); boolean v_value = false; // Validator String chvi = request.getParameter("chv" + i); if (chvi != null) { v_value = true; } user.setApproval(v_value); new_users.add(user); } // Sorting begin int upIndex = Integer.parseInt(request.getParameter("up")); int downIndex = Integer.parseInt(request.getParameter("down")); int addIndex = Integer.parseInt(request.getParameter("add")); // Remove user to change order if (upIndex > 0 && upIndex < users_count) { Worker user = new_users.remove(upIndex); new_users.add(upIndex - 1, user); } if (downIndex >= 0 && downIndex < users_count - 1) { Worker user = new_users.remove(downIndex); new_users.add(downIndex + 1, user); } if (addIndex >= 0 && addIndex < users_count) { Worker user = new_users.get(addIndex); Worker new_user = new Worker(user.getUserId(), Integer.parseInt(versioningSC.getEditingDocument().getPk().getId()), 0, user.isApproval(), true, versioningSC.getComponentId(), user.getType(), user.isSaved(), user.isUsed(), user.getListType()); new_users.add(addIndex + 1, new_user); users_count++; } for (int i = 0; i < users_count; i++) { new_users.get(i).setOrder(i); } document.setWorkList(new_users); } } destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ChangeListType")) { Document document = versioningSC.getEditingDocument(); String listType = request.getParameter("ListType"); if (!StringUtil.isDefined(listType)) { listType = VersioningSessionController.WRITERS_LIST_SIMPLE; } document.setCurrentWorkListOrder(Integer.parseInt(listType)); ProfileInst profile = versioningSC.getProfile(VersioningSessionController.WRITER); ArrayList<Worker> workers = new ArrayList<Worker>(); if (profile != null) { if (listType.equals(VersioningSessionController.WRITERS_LIST_ORDERED)) { // Need to merge users from groups with other users workers = document.getWorkList(); workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers); versioningSC.setAlreadyMerged(true); } else { ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(workers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(workers, profile.getAllUsers()); workers.addAll(workersUsers); } } document.setWorkList(workers); versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("SaveListType")) { Document document = versioningSC.getEditingDocument(); ArrayList<Worker> users = document.getWorkList(); ArrayList<Worker> updateUsers = new ArrayList<Worker>(); for (int i = 0; i < users.size(); i++) { Worker user = users.get(i); // Set approval rights to users String chvi = request.getParameter("chv" + i); boolean v_value = false; if (chvi != null) { v_value = true; } user.setApproval(v_value); updateUsers.add(user); } versioningSC.updateWorkList(document); versioningSC.updateDocument(document); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("ViewVersions")) { request.setAttribute("Document", versioningSC.getEditingDocument()); destination = rootDestination + "versions.jsp"; } else if (function.equals("SelectUsersGroupsProfileInstance")) { String role = request.getParameter("Role"); String listType = request.getParameter("ListType"); if (StringUtil.isDefined(listType)) { versioningSC.getEditingDocument().setCurrentWorkListOrder(Integer.parseInt(listType)); } versioningSC.initUserPanelInstanceForGroupsUsers(role); destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } else if (function.startsWith("DocumentProfileSetUsersAndGroups")) { String role = request.getParameter("Role"); ProfileInst profile = versioningSC.getProfile(role); versioningSC.updateDocumentProfile(profile); if (role.equals(VersioningSessionController.WRITER)) { ArrayList<Worker> oldWorkers = versioningSC.getEditingDocument().getWorkList(); ArrayList<Worker> workers = new ArrayList<Worker>(); ArrayList<Worker> workersUsers = new ArrayList<Worker>(); ArrayList<Worker> workersGroups = new ArrayList<Worker>(); workersGroups = versioningSC.convertGroupsToWorkers(oldWorkers, profile.getAllGroups()); workers.addAll(workersGroups); workersUsers = versioningSC.convertUsersToWorkers(oldWorkers, profile.getAllUsers()); workers.addAll(workersUsers); ArrayList<Worker> sortedWorkers = new ArrayList<Worker>(); if (workers != null) { for (int i = 0; i < workers.size(); i++) { Worker sortedWorker = workers.get(i); sortedWorker.setOrder(i); sortedWorkers.add(sortedWorker); } workers = sortedWorkers; } versioningSC.getEditingDocument().setWorkList(workers); versioningSC.updateWorkList(versioningSC.getEditingDocument()); request.setAttribute("urlToReload", "ViewWritersList"); } else { request.setAttribute("urlToReload", "ViewReadersList"); } destination = rootDestination + "closeWindow.jsp"; } else if (function.startsWith("SaveList")) { String role = request.getParameter("Role"); String fromFunction = request.getParameter("From"); if (versioningSC.isAccessListExist(role)) { versioningSC.removeAccessList(role); } versioningSC.saveAccessList(role); request.setAttribute("Message", messages.getString("versioning.ListSaved", "")); destination = getDestination(fromFunction, versioningSC, request); } else if (function.startsWith("DeleteReaderProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.READER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } destination = getDestination("ViewReadersList", versioningSC, request); } else if (function.startsWith("DeleteWriterProfile")) { ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.WRITER); if (profile != null) { profile.removeAllGroups(); profile.removeAllUsers(); versioningSC.updateProfileInst(profile); } versioningSC.deleteWorkers(true); versioningSC.setAlreadyMerged(false); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.startsWith("Update")) { String docId = request.getParameter("DocId"); String name = request.getParameter("name"); String description = request.getParameter("description"); String comments = request.getParameter("comments"); Document document = versioningSC .getDocument(new DocumentPK(Integer.parseInt(docId), versioningSC.getComponentId())); document.setDescription(description); document.setName(name); document.setAdditionalInfo(comments); versioningSC.updateDocument(document); versioningSC.setEditingDocument(document); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("CloseWindow")) { destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewVersion")) { // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(request.getParameter("documentId"), versioningSC, request); } destination = rootDestination + "newVersion.jsp"; } else if (function.equals("AddNewOnlineVersion")) { String documentId = request.getParameter("documentId"); request.setAttribute("DocumentId", documentId); // Display xmlForm if used if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(documentId, versioningSC, request); } destination = rootDestination + "newOnlineVersion.jsp"; } else if (function.equals("ChangeValidator")) { String setTypeId = request.getParameter("VV"); String setType = request.getParameter("SetType"); // 'U'for users or 'G' // for groups versioningSC.setWorkerValidator(versioningSC.getEditingDocument().getWorkList(), Integer.parseInt(setTypeId), setType); destination = getDestination("ViewWritersList", versioningSC, request); } else if (function.equals("ListPublicVersionsOfDocument")) { String documentId = request.getParameter("DocId"); String isAlias = request.getParameter("Alias"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); List<DocumentVersion> publicVersions = versioningSC.getPublicDocumentVersions(documentPK); request.setAttribute("Document", document); request.setAttribute("PublicVersions", publicVersions); request.setAttribute("Alias", isAlias); destination = "/versioningPeas/jsp/publicVersions.jsp"; } else if ("ViewAllVersions".equals(function)) { return viewVersions(request, versioningSC); } else if ("saveOnline".equals(function)) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); String userId = versioningSC.getUserId(); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); boolean force = "true".equalsIgnoreCase(request.getParameter("force_release")); String callback = FileUploadUtil.getParameter(items, "Callback"); request.setAttribute("Callback", callback); destination = "/versioningPeas/jsp/documentSaved.jsp"; boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); DocumentVersionPK newVersionPK = versioningSC.saveOnline(document, comments, radio, Integer.parseInt(userId), force, addXmlForm); if (newVersionPK != null) { request.setAttribute("DocumentId", documentId); DocumentVersion version = versioningSC.getLastVersion(documentPK); request.setAttribute("Version", version); if (addXmlForm) { saveXMLData(versioningSC, newVersionPK, items); } } else { if ("admin".equals(versioningSC.getUserRoleLevel())) { // TODO MANU ecrire la page pour ressoumettre en forcant destination = "/versioningPeas/jsp/forceDocumentLocked.jsp"; } else { destination = "/versioningPeas/jsp/documentLocked.jsp"; } } } else if ("Checkout".equals(function)) { String documentId = request.getParameter("DocId"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); Document document = versioningSC.getDocument(documentPK); document.setStatus(1); document.setLastCheckOutDate(new Date()); versioningSC.checkDocumentOut(documentPK, Integer.parseInt(versioningSC.getUserId()), new Date()); document = versioningSC.getDocument(documentPK); versioningSC.setEditingDocument(document); request.setAttribute("Document", document); destination = rootDestination + "versions.jsp"; } else if ("DeleteDocumentRequest".equals(function)) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); request.setAttribute("DocId", documentId); request.setAttribute("Url", url); destination = rootDestination + "deleteDocument.jsp"; } else if (function.equals("DeleteDocument")) { String documentId = request.getParameter("DocId"); String url = request.getParameter("Url"); DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(), versioningSC.getComponentId()); versioningSC.deleteDocument(documentPK); SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "url=" + url); request.setAttribute("urlToReload", url); destination = rootDestination + "closeWindow.jsp"; } else if (function.equals("AddNewDocument")) { String pubId = request.getParameter("PubId"); request.setAttribute("PubId", pubId); if (StringUtil.isDefined(versioningSC.getXmlForm())) { setXMLFormIntoRequest(null, versioningSC, request); } destination = rootDestination + "newDocument.jsp"; } else if (function.equals("SaveNewDocument")) { saveNewDocument(request, versioningSC); destination = getDestination("ViewVersions", versioningSC, request); } else if (function.equals("SaveNewVersion")) { if (!StringUtil.isDefined(request.getCharacterEncoding())) { request.setCharacterEncoding("UTF-8"); } String encoding = request.getCharacterEncoding(); List<FileItem> items = FileUploadUtil.parseRequest(request); String type = FileUploadUtil.getParameter(items, "type", "", encoding); String comments = FileUploadUtil.getParameter(items, "comments", "", encoding); String radio = FileUploadUtil.getParameter(items, "radio", "", encoding); String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding); // Save file on disk FileItem fileItem = FileUploadUtil.getFile(items, "file_upload"); boolean runOnUnix = !FileUtil.isWindows(); String logicalName = fileItem.getName(); String physicalName = "dummy"; String mimeType = "dummy"; File dir = null; int size = 0; if (logicalName != null) { if (runOnUnix) { logicalName = logicalName.replace('\\', File.separatorChar); } logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length()); type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length()); physicalName = new Long(new Date().getTime()).toString() + "." + type; mimeType = FileUtil.getMimeType(logicalName); if (!StringUtil.isDefined(mimeType)) { mimeType = "unknown"; } dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName); size = new Long(fileItem.getSize()).intValue(); fileItem.write(dir); } // create DocumentVersion String componentId = versioningSC.getComponentId(); DocumentPK docPK = new DocumentPK(Integer.parseInt(documentId), "useless", componentId); int userId = Integer.parseInt(versioningSC.getUserId()); DocumentVersion documentVersion = null; DocumentVersion lastVersion = versioningSC.getLastVersion(docPK); if (com.stratelia.silverpeas.versioning.ejb.RepositoryHelper.getJcrDocumentService() .isNodeLocked(lastVersion)) { destination = rootDestination + "documentLocked.jsp"; } else { List<DocumentVersion> versions = versioningSC.getDocumentVersions(docPK); int majorNumber = 0; int minorNumber = 1; if (versions != null && versions.size() > 0) { documentVersion = versions.get(0); majorNumber = documentVersion.getMajorNumber(); minorNumber = documentVersion.getMinorNumber(); DocumentVersion newVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber, userId, new Date(), comments, Integer.parseInt(radio), documentVersion.getStatus(), physicalName, logicalName, mimeType, size, componentId); boolean addXmlForm = !isXMLFormEmpty(versioningSC, items); if (addXmlForm) { newVersion.setXmlForm(versioningSC.getXmlForm()); } newVersion = versioningSC.addNewDocumentVersion(newVersion); ResourceLocator settings = new ResourceLocator( "com.stratelia.webactiv.util.attachment.Attachment", ""); boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false); // Specific case: 3d file to convert by Actify Publisher if (actifyPublisherEnable) { String extensions = settings.getString("Actify3dFiles"); StringTokenizer tokenizer = new StringTokenizer(extensions, ","); // 3d native file ? boolean fileForActify = false; SilverTrace.info("versioningPeas", "saveFile.jsp", "root.MSG_GEN_PARAM_VALUE", "nb tokenizer =" + tokenizer.countTokens()); while (tokenizer.hasMoreTokens() && !fileForActify) { String extension = tokenizer.nextToken(); if (type.equalsIgnoreCase(extension)) { fileForActify = true; } } if (fileForActify) { String dirDestName = "v_" + componentId + "_" + documentId; String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separator + dirDestName; String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath; if (!new File(destPath).exists()) { FileRepositoryManager.createGlobalTempPath(actifyWorkingPath); } String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath + File.separator + logicalName; FileRepositoryManager.copyFile( versioningSC.createPath(componentId, null) + File.separator + physicalName, destFile); } } if (addXmlForm) { saveXMLData(versioningSC, newVersion.getPk(), items); } } String returnURL = FileUploadUtil.getParameter(items, "ReturnURL"); if (!StringUtil.isDefined(returnURL)) { destination = getDestination("ViewVersions", versioningSC, request); } else { request.setAttribute("urlToReload", returnURL); destination = rootDestination + "closeWindow.jsp"; } } } else { destination = rootDestination + function; } } catch (Exception e) { SilverTrace.error("versioning", "VersioningRequestRouter.getDestination", "root.EX_CANT_GET_REQUEST_DESTINATION", e); request.setAttribute("javax.servlet.jsp.jspException", e); destination = "/admin/jsp/errorpageMain.jsp"; } SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE", "Destination=" + destination); return destination; }