public String intercept(ActionInvocation invocation) throws Exception { User user = null; HttpServletRequest request = ServletActionContext.getRequest(); int messageCount; userService.setSessionFactory(sessionFactory); user = (User) request.getSession().getAttribute("user"); if (user == null) { System.out.println("redirecting to login"); return MUST_AUTHENTICATE; } else { invocation.getStack().setValue("user", user); List<Message> messages = messageService.findCountByType(user.getCompanyId()); long totalCount = 0; for (int i = 0; i < messages.size(); i++) { if (messages.get(i).getType().compareTo("RFQ") == 0) { request.getSession().putValue("rfqMessageCount", messages.get(i).getCount()); } else if (messages.get(i).getType().compareTo("USER") == 0) { request.getSession().putValue("userMessageCount", messages.get(i).getCount()); } totalCount += messages.get(i).getCount(); } request.getSession().putValue("totalMessageCount", totalCount); return invocation.invoke(); } }
public void beforeResult(ActionInvocation invocation, String resultCode) { ValueStack stack = invocation.getStack(); CompoundRoot root = stack.getRoot(); boolean needsRefresh = true; Object newModel = action.getModel(); // Check to see if the new model instance is already on the stack for (Object item : root) { if (item.equals(newModel)) { needsRefresh = false; } } // Add the new model on the stack if (needsRefresh) { // Clear off the old model instance if (originalModel != null) { root.remove(originalModel); } if (newModel != null) { stack.push(newModel); } } }
@Override public String intercept(ActionInvocation actionInvocation) throws Exception { ActionConfig actionConfig = actionInvocation.getProxy().getConfig(); final Map<String, String> staticParams = actionConfig.getParams(); if (staticParams != null) { // --------------------------------------------------------------------- // Push the specified static parameters onto the value stack // --------------------------------------------------------------------- Map<String, Object> matches = new HashMap<>(); for (Map.Entry<String, String> entry : staticParams.entrySet()) { if (standardParams.contains(entry.getKey())) { matches.put(entry.getKey(), entry.getValue()); } else if (commaSeparatedParams.contains(entry.getKey())) { String[] values = entry.getValue().split(","); for (int i = 0; i < values.length; i++) { values[i] = values[i].trim(); } matches.put(entry.getKey(), values); } } actionInvocation.getStack().push(matches); } // TODO: move this to its own systemInfoInterceptor? Map<String, Object> systemInfo = new HashMap<>(); String revision = systemService.getSystemInfo().getRevision(); if (StringUtils.isEmpty(revision)) { revision = "__dev__"; } systemInfo.put("buildRevision", revision); actionInvocation.getStack().push(systemInfo); return actionInvocation.invoke(); }
@Override public String intercept(ActionInvocation invocation) throws Exception { System.out.println("actionName" + invocation.getAction().getClass().getName()); String name = (String) invocation.getStack().findString("username"); System.out.println(name); if (name == null || "123".equals(name)) { System.out.println("fail"); return "fail"; } return invocation.invoke(); }
protected Object getOverrideExpr(ActionInvocation invocation, Object value) { ValueStack stack = invocation.getStack(); try { stack.push(value); return escape(stack.findString("top")); } finally { stack.pop(); } }
/** * @param invocation * @param dataName * @param data */ protected void prepareImportData( ActionInvocation invocation, String dataName, List<Map<String, String>> data) { ValueStack stack = invocation.getStack(); // constructor all the parameters from csv data for (int i = 0; i < data.size(); i++) { Map<String, String> line = (Map<String, String>) data.get(i); for (Map.Entry<String, String> entry : line.entrySet()) { String key = dataName + "[" + i + "]." + entry.getKey(); stack.setValue(key, entry.getValue()); } } }
@Override public String intercept(ActionInvocation invocation) throws Exception { Object action = invocation.getAction(); if (action instanceof ModelDriven) { ModelDriven modelDriven = (ModelDriven) action; ValueStack stack = invocation.getStack(); Object model = modelDriven.getModel(); if (model != null) { stack.push(model); } if (refreshModelBeforeResult) { invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model)); } } return invocation.invoke(); }
@Override public String intercept(ActionInvocation invocation) throws Exception { if (log.isDebugEnabled()) { log.debug("*******************************************************************************"); } HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST); List<Article> articles = generateArticles(request); log.info("共有" + articles.size() + "个图文消息"); int i = 0; for (Iterator<Article> it = articles.iterator(); it.hasNext(); ) { log.info("********图文消息" + i + "********"); Article temp = it.next(); if (temp != null) { log.info("缩略图:" + temp.getThumb_media_id()); log.info("标题:" + temp.getTitle()); log.info("作者:" + temp.getAuthor()); log.info("阅读原文URL:" + temp.getContent_source_url()); log.info("备注:" + temp.getDigest()); log.info("是否显示封面图:" + temp.getShow_cover_pic()); log.info("内容:" + temp.getContent()); } i++; } if (log.isDebugEnabled()) { log.info("*******************************************************************************"); } ValueStack vs = invocation.getStack(); vs.setValue("articles", articles); String result = invocation.invoke(); log.info(result); return result; }
public void testIncludeParameterInResultWithConditionParseOn() throws Exception { ResultConfig resultConfig = new ResultConfig.Builder("", "") .addParam("actionName", "someActionName") .addParam("namespace", "someNamespace") .addParam("encode", "true") .addParam("parse", "true") .addParam("location", "someLocation") .addParam("prependServletContext", "true") .addParam("method", "someMethod") .addParam("statusCode", "333") .addParam("param1", "${#value1}") .addParam("param2", "${#value2}") .addParam("param3", "${#value3}") .addParam("anchor", "${#fragment}") .build(); ActionContext context = ActionContext.getContext(); ValueStack stack = context.getValueStack(); context.getContextMap().put("value1", "value 1"); context.getContextMap().put("value2", "value 2"); context.getContextMap().put("value3", "value 3"); MockHttpServletRequest req = new MockHttpServletRequest(); MockHttpServletResponse res = new MockHttpServletResponse(); context.put(ServletActionContext.HTTP_REQUEST, req); context.put(ServletActionContext.HTTP_RESPONSE, res); Map<String, ResultConfig> results = new HashMap<String, ResultConfig>(); results.put("myResult", resultConfig); ActionConfig actionConfig = new ActionConfig.Builder("", "", "").addResultConfigs(results).build(); ServletActionRedirectResult result = new ServletActionRedirectResult(); result.setActionName("myAction"); result.setNamespace("/myNamespace"); result.setParse(true); result.setEncode(false); result.setPrependServletContext(false); result.setAnchor("fragment"); result.setUrlHelper(new DefaultUrlHelper()); IMocksControl control = createControl(); ActionProxy mockActionProxy = control.createMock(ActionProxy.class); ActionInvocation mockInvocation = control.createMock(ActionInvocation.class); expect(mockInvocation.getProxy()).andReturn(mockActionProxy); expect(mockInvocation.getResultCode()).andReturn("myResult"); expect(mockActionProxy.getConfig()).andReturn(actionConfig); expect(mockInvocation.getInvocationContext()).andReturn(context); expect(mockInvocation.getStack()).andReturn(stack).anyTimes(); control.replay(); result.setActionMapper(container.getInstance(ActionMapper.class)); result.execute(mockInvocation); assertEquals( "/myNamespace/myAction.action?param1=value+1¶m2=value+2¶m3=value+3#fragment", res.getRedirectedUrl()); control.verify(); }
/* * (non-Javadoc) * * @seecom.opensymphony.xwork2.Result#execute(com.opensymphony.xwork2. * ActionInvocation) */ @Override @SuppressWarnings("unused") public void execute(ActionInvocation invocation) throws Exception { ActionContext actionContext = invocation.getInvocationContext(); HttpServletRequest request = (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) actionContext.get(StrutsStatics.HTTP_RESPONSE); ValueStack vs = invocation.getStack(); if (null == value) { return; } Object evaluated = vs.findValue(value); if (null == evaluated) { LOG.warn("value [" + value + "] is null in ValueStack. "); return; } try { if (isPrimitive(evaluated)) { // Map<String, Object> map = new HashMap<String, Object>(1); key = StringUtils.isBlank(key) ? value : StringUtils.trim(key); map.put(key, evaluated); evaluated = map; } GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter( DateTime.class, new JsonSerializer<DateTime>() { @Override public JsonElement serialize(DateTime arg0, Type arg1, JsonSerializationContext arg2) { return new JsonPrimitive(arg0.toString(DateFormatter.SDF_YMDHMS)); } }); Gson gson = builder.create(); String json = gson.toJson(evaluated); if (StringUtils.isNotBlank(jsonpCallback)) { json = String.format("%s(%s);", jsonpCallback, json); } if (LOG.isDebugEnabled()) { LOG.debug("[JSON]\n" + json); } String encoding = getEncoding(); String contentType = getContentType(); if (encoding != null) { contentType = contentType + ";charset=" + encoding; } Writer writer = new OutputStreamWriter(response.getOutputStream(), encoding); try { response.setContentType(contentType); response.setContentLength(json.getBytes(defaultEncoding).length); writer.write(json); } finally { writer.close(); } } catch (Exception e) { LOG.error("Unable to render json for value: '" + value + "'", e); throw e; } finally { // } return; }
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { // Will throw a runtime exception if no "datasource" property. initializeProperties(invocation); if (LOG.isDebugEnabled()) { LOG.debug( "Creating JasperReport for dataSource = " + dataSource + ", format = " + format, new Object[0]); } HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST); HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(ServletActionContext.HTTP_RESPONSE); // Handle IE special case: it sends a "contype" request first. if ("contype".equals(request.getHeader("User-Agent"))) { try { response.setContentType("application/pdf"); response.setContentLength(0); ServletOutputStream outputStream = response.getOutputStream(); outputStream.close(); } catch (IOException e) { LOG.error("Error writing report output", e); throw new ServletException(e.getMessage(), e); } return; } // Construct the data source for the report. ValueStack stack = invocation.getStack(); ValueStackDataSource stackDataSource = null; Connection conn = (Connection) stack.findValue(connection); if (conn == null) stackDataSource = new ValueStackDataSource(stack, dataSource); // Determine the directory that the report file is in and set the reportDirectory parameter // For WW 2.1.7: // ServletContext servletContext = ((ServletConfig) // invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONFIG)).getServletContext(); ServletContext servletContext = (ServletContext) invocation.getInvocationContext().get(ServletActionContext.SERVLET_CONTEXT); String systemId = servletContext.getRealPath(finalLocation); Map parameters = new ValueStackShadowMap(stack); File directory = new File(systemId.substring(0, systemId.lastIndexOf(File.separator))); parameters.put("reportDirectory", directory); parameters.put(JRParameter.REPORT_LOCALE, invocation.getInvocationContext().getLocale()); // put timezone in jasper report parameter if (timeZone != null) { timeZone = conditionalParse(timeZone, invocation); final TimeZone tz = TimeZone.getTimeZone(timeZone); if (tz != null) { // put the report time zone parameters.put(JRParameter.REPORT_TIME_ZONE, tz); } } // Add any report parameters from action to param map. Map reportParams = (Map) stack.findValue(reportParameters); if (reportParams != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found report parameters; adding to parameters...", new Object[0]); } parameters.putAll(reportParams); } byte[] output; JasperPrint jasperPrint; // Fill the report and produce a print object try { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(new File(systemId)); if (conn == null) jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, stackDataSource); else jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn); } catch (JRException e) { LOG.error("Error building report for uri " + systemId, e); throw new ServletException(e.getMessage(), e); } // Export the print object to the desired output format try { if (contentDisposition != null || documentName != null) { final StringBuffer tmp = new StringBuffer(); tmp.append((contentDisposition == null) ? "inline" : contentDisposition); if (documentName != null) { tmp.append("; filename="); tmp.append(documentName); tmp.append("."); tmp.append(format.toLowerCase()); } response.setHeader("Content-disposition", tmp.toString()); } JRExporter exporter; if (format.equals(FORMAT_PDF)) { response.setContentType("application/pdf"); exporter = new JRPdfExporter(); } else if (format.equals(FORMAT_CSV)) { response.setContentType("text/csv"); exporter = new JRCsvExporter(); } else if (format.equals(FORMAT_HTML)) { response.setContentType("text/html"); // IMAGES_MAPS seems to be only supported as "backward compatible" from JasperReports 1.1.0 Map imagesMap = new HashMap(); request.getSession(true).setAttribute("IMAGES_MAP", imagesMap); exporter = new JRHtmlExporter(); exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, imagesMap); exporter.setParameter( JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + imageServletUrl); // Needed to support chart images: exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); request.getSession().setAttribute("net.sf.jasperreports.j2ee.jasper_print", jasperPrint); } else if (format.equals(FORMAT_XLS)) { response.setContentType("application/vnd.ms-excel"); exporter = new JRXlsExporter(); } else if (format.equals(FORMAT_XML)) { response.setContentType("text/xml"); exporter = new JRXmlExporter(); } else if (format.equals(FORMAT_RTF)) { response.setContentType("application/rtf"); exporter = new JRRtfExporter(); } else { throw new ServletException("Unknown report format: " + format); } Map exportParams = (Map) stack.findValue(exportParameters); if (exportParams != null) { if (LOG.isDebugEnabled()) { LOG.debug("Found export parameters; adding to exporter parameters...", new Object[0]); } exporter.getParameters().putAll(exportParams); } output = exportReportToBytes(jasperPrint, exporter); } catch (JRException e) { String message = "Error producing " + format + " report for uri " + systemId; LOG.error(message, e); throw new ServletException(e.getMessage(), e); } response.setContentLength(output.length); // Will throw ServletException on IOException. writeReport(response, output); }
/** * 1. get fileComponent from action * * <p>2. validate fileName to see if filePrefix is allowed * * <p>3. validate file format with the import file template * * <p>4. * * @see * com.pc.core.web.interceptor.AroundInterceptor#before(com.opensymphony.xwork2.ActionInvocation) */ public void before(ActionInvocation invocation) throws Exception { Action action = (Action) invocation.getAction(); HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST); if (action instanceof ImportPreparation && request instanceof MultiPartRequestWrapper) { ServletContext servletContext = ServletActionContext.getServletContext(); ActionContext invocationContext = invocation.getInvocationContext(); ImportPreparation importPreparation = (ImportPreparation) action; // 1. get fileComponent from valueStack FileComponent fileComponent = (FileComponent) invocation.getStack().findValue("fileComponent"); if (fileComponent == null || fileComponent.getUpload() == null) throw new ImportException( "error.upload.file.empty", "r:" + importPreparation.getErrorReturn() + "/import/error"); // 2. validate fileName String fileExt = fileComponent.getFileExtension(); if (!Arrays.asList(this.allowedPrefix).contains(fileExt)) { throw new ImportException( "error.upload.file-ext.not-allowed", "r:" + importPreparation.getErrorReturn() + "/import/error"); } // Create CsvReader to parse the file CsvReader csvReader = new CsvReader(new FileReader(fileComponent.getUpload())); try { // get file header information from cache String header = (String) servletContext.getAttribute( importPreparation.getTarget().toUpperCase() + "_HEADERS"); String[] headerKeys = header.split(","); // 3. validate file format if (csvReader.readHeaders()) { if (headerKeys.length != csvReader.getHeaderCount()) { throw new ImportException( "error.upload.file-format.mismatch", "r:" + importPreparation.getErrorReturn() + "/import/error"); } } // Read data from CsvReader List<Map<String, String>> data = new ArrayList<Map<String, String>>(); while (csvReader.readRecord()) { Map<String, String> record = new LinkedHashMap<String, String>(); for (int i = 0; i < headerKeys.length; i++) { record.put(headerKeys[i], csvReader.get(i)); } data.add(record); } // 4. validate data importPreparation.validate(data); // 5. set data OgnlContextState.setCreatingNullObjects(invocationContext.getContextMap(), true); OgnlContextState.setDenyMethodExecution(invocationContext.getContextMap(), true); OgnlContextState.setReportingConversionErrors(invocationContext.getContextMap(), true); prepareImportData(invocation, importPreparation.getDataName(), data); } finally { // release all the resource anyway csvReader.close(); OgnlContextState.setCreatingNullObjects(invocationContext.getContextMap(), true); OgnlContextState.setDenyMethodExecution(invocationContext.getContextMap(), true); OgnlContextState.setReportingConversionErrors(invocationContext.getContextMap(), true); } } }
public String intercept(ActionInvocation invocation) throws Exception { int userId; Object action = invocation.getAction(); if (action instanceof ExceptionHandler) { // actually print the message for debugging purposes String trace = getStackTrace(((ExceptionHandler) action).getException()); return ""; } // TODO FINNUCKS: this logs out a current user on one of // these actions and sets it to the read only user. // Need to check ID and ... ? if (action instanceof ROIterationAction || (isUnderReadOnlyAction && (action instanceof ChartAction || action instanceof IterationAction || action instanceof IterationHistoryAction || action instanceof StoryAction))) { isUnderReadOnlyAction = true; // log in read only user if we got to here UserDAOHibernate userDao = new UserDAOHibernate(); SessionFactory sessionFactory = null; try { sessionFactory = (SessionFactory) new InitialContext().lookup("hibernateSessionFactory"); userDao.setSessionFactory(sessionFactory); } catch (NamingException e) { e.printStackTrace(); } Session session = sessionFactory.openSession(); User user = userDao.getByLoginName("readonly"); SecurityUtil.setLoggedUser(user); // push current user to the value stack invocation.getStack().set("currentUser", user); invocation.getStack().set("currentUserJson", new JSONSerializer().serialize(user)); session.disconnect(); session.close(); // perform request String result = invocation.invoke(); // after the request: // reset the logged user SecurityUtil.setLoggedUser(null); return result; } try { // get the current user id userId = SecurityUtil.getLoggedUserId(); } catch (IllegalStateException e) { // no logged user log.warn("no user found to be assigned"); SecurityUtil.setLoggedUser(null); return invocation.invoke(); } // get the user object corresponding to the id User user = userBusiness.retrieve(userId); // check that user hasn't been removed during the session if (user == null) { SecurityUtil.logoutCurrentUser(); } // check that user hasn't been disabled during the session if (!user.isEnabled()) { SecurityUtil.logoutCurrentUser(); } // before the request: // set this user as the logged user SecurityUtil.setLoggedUser(user); // push current user to the value stack invocation.getStack().set("currentUser", user); invocation.getStack().set("currentUserJson", new JSONSerializer().serialize(user)); // perform request String result = invocation.invoke(); // after the request: // reset the logged user SecurityUtil.setLoggedUser(null); return result; }
/** * Default implementation to handle ExceptionHolder publishing. Pushes given ExceptionHolder on * the stack. Subclasses may override this to customize publishing. * * @param invocation The invocation to publish Exception for. * @param exceptionHolder The exceptionHolder wrapping the Exception to publish. */ protected void publishException(ActionInvocation invocation, ExceptionHolder exceptionHolder) { invocation.getStack().push(exceptionHolder); }
@Override protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("In doExecute. finalLocation: " + finalLocation + ", renderer: " + renderer); } OutputStream os = null; try { final ActionContext actionContext = invocation.getInvocationContext(); final HttpServletRequest request = (HttpServletRequest) actionContext.get(HTTP_REQUEST); final HttpServletResponse response = (HttpServletResponse) actionContext.get(HTTP_RESPONSE); final SimpleServletResponseWrapper responseWrapper = new SimpleServletResponseWrapper(response); final ServletContext servletContext = (ServletContext) actionContext.get(SERVLET_CONTEXT); ViewRenderer viewRenderer; if (renderer == null) { viewRenderer = container.getInstance(ViewRenderer.class); } else { viewRenderer = container.getInstance(ViewRenderer.class, renderer); } if (viewRenderer == null) { final String err = "Cannot get an instance of ViewRenderer with the name '" + renderer + "'."; LOG.error(err); throw new AssertionError(err); } // render view viewRenderer.render( finalLocation, request, responseWrapper, servletContext, actionContext.getLocale(), invocation.getStack(), invocation.getAction()); // Set the content type response.setContentType(PDF_MIME_TYPE); // Set the content-disposition if (contentDisposition != null) { response.addHeader("Content-Disposition", conditionalParse(contentDisposition, invocation)); } // Set the cache control headers if necessary if (!allowCaching) { response.addHeader("Pragma", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } if (LOG.isTraceEnabled()) { LOG.trace("Content before parsing:\n" + responseWrapper.toString()); } // parse response wrapper final Document document = parseContent(responseWrapper.toString()); final Element head = document.head(); // add CSS from cssPathsSet parameter if (cssPathsSet != null && !cssPathsSet.isEmpty()) { for (String css : cssPathsSet) { // remove leading slash if (css.startsWith("\\")) { css = css.substring(1); } head.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + css + "\" />"); } } // add style for font family that supports unicode head.append(FONT_STYLE_TAG); final String content = document.html(); if (LOG.isTraceEnabled()) { LOG.trace("Content after parsing:\n" + content); } // put pdf stream into response createPdfStream(content, findBaseUrl(request), response.getOutputStream()); } finally { if (os != null) { os.close(); } } }