コード例 #1
0
  /**
   * validation check를 할때 hashMap name이 view(jsp)에서 입력되었는지를 알수 있게 하기 위해서는 stack에 getter setter로 정의된
   * hashMap(여기에서는 reqMap이름을 쓴다)이름을 지정하고 hashMap에 저장된 값을 리턴한다.
   */
  @Override
  protected Object getFieldValue(String name, Object object) throws ValidationException {
    ValueStack stack = ActionContext.getContext().getValueStack();

    boolean pop = false;

    if (!(stack.getRoot().contains(object))) {
      stack.push(object);
      pop = true;
    }

    Object retVal = null;
    // HashMap reqMap의 값을 stack에 넣어준다.
    Object obj = (Map) stack.findValue("reqMap");

    // HashMap reqMap이 null이 아닐때
    if (obj != null) {
      Map m = (Map) obj;
      // stack에 있는 HashMap reqMap값을 name으로 가져와서 valueStack에 올려준다.
      retVal = m.get(name);
    }
    // HashMap reqMap이 null일때
    else {
      // getter setter을 사용한 name의 값을 valueStack에 올려준다.
      retVal = stack.findValue(name);
    }

    if (pop) {
      stack.pop();
    }

    return retVal;
  }
コード例 #2
0
  public void testGenericPropertiesFromGetter() {
    GenericsBean gb = new GenericsBean();
    ValueStack stack = ac.getValueStack();
    stack.push(gb);

    assertEquals(1, gb.getGetterList().size());
    assertEquals("42.42", stack.findValue("getterList.get(0).toString()"));
    assertEquals(new Double(42.42), stack.findValue("getterList.get(0)"));
    assertEquals(new Double(42.42), gb.getGetterList().get(0));
  }
コード例 #3
0
ファイル: NestedAction.java プロジェクト: ChenLinXi/struts
  public String noStack() {
    ValueStack stack = ActionContext.getContext().getValueStack();
    // Action + DefaultTextProvider on the stack
    Assert.assertEquals(2, stack.size());
    Assert.assertNull(stack.findValue(ActionNestingTest.KEY));
    Assert.assertEquals(
        ActionNestingTest.NESTED_VALUE, stack.findValue(ActionNestingTest.NESTED_KEY));

    return SUCCESS;
  }
コード例 #4
0
ファイル: NestedAction.java プロジェクト: ChenLinXi/struts
  public String stack() {
    ValueStack stack = ActionContext.getContext().getValueStack();
    // DefaultTextProvider, NestedActionTest pushed on by the test, and the NestedAction
    Assert.assertEquals(3, stack.size());
    Assert.assertNotNull(stack.findValue(ActionNestingTest.KEY));
    Assert.assertEquals(
        ActionContext.getContext().getValueStack().findValue(ActionNestingTest.KEY),
        ActionNestingTest.VALUE);
    Assert.assertEquals(
        ActionNestingTest.NESTED_VALUE, stack.findValue(ActionNestingTest.NESTED_KEY));

    return SUCCESS;
  }
コード例 #5
0
 /**
  * @return
  * @throws JspException 作者:孙树林 创建日期:2010-12-29
  */
 @Override
 public int doStartTag() throws JspException {
   JspWriter writer = pageContext.getOut();
   try {
     ValueStack stack = TagUtils.getStack(pageContext);
     Object obj = stack.findValue("ex");
     GeneralException exception = (GeneralException) obj;
     writer.print("错误信息:<br>");
     writer.print(exception.getMessage() + "<br>");
     StackTraceElement[] elements = exception.getStackTrace();
     writer.print("详细内容:<br>");
     for (StackTraceElement element : elements) {
       writer.println(
           element.getClassName()
               + "."
               + element.getMethodName()
               + "("
               + element.getFileName()
               + ": "
               + element.getLineNumber()
               + ")<br>");
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return EVAL_PAGE;
 }
コード例 #6
0
  public void testGenericPropertiesFromSetter() {
    GenericsBean gb = new GenericsBean();
    ValueStack stack = ac.getValueStack();
    stack.push(gb);

    stack.setValue("genericMap[123.12]", "66");
    stack.setValue("genericMap[456.12]", "42");

    assertEquals(2, gb.getGenericMap().size());
    assertEquals("66", stack.findValue("genericMap.get(123.12).toString()"));
    assertEquals("42", stack.findValue("genericMap.get(456.12).toString()"));
    assertEquals(66, stack.findValue("genericMap.get(123.12)"));
    assertEquals(42, stack.findValue("genericMap.get(456.12)"));
    assertEquals(true, stack.findValue("genericMap.containsValue(66)"));
    assertEquals(true, stack.findValue("genericMap.containsValue(42)"));
    assertEquals(true, stack.findValue("genericMap.containsKey(123.12)"));
    assertEquals(true, stack.findValue("genericMap.containsKey(456.12)"));
  }
コード例 #7
0
  /**
   * Implementation of get(), overriding HashMap implementation.
   *
   * @param key - The key to get in HashMap and if not found there from the valueStack.
   * @return value - The object from HashMap or if null, from the valueStack.
   * @see java.util.HashMap#get
   */
  public Object get(Object key) {
    Object value = super.get(key);

    if ((value == null) && key instanceof String) {
      value = valueStack.findValue((String) key);
    }

    return value;
  }
コード例 #8
0
  /**
   * Implementation of containsKey(), overriding HashMap implementation.
   *
   * @param key - The key to check in HashMap and if not found to check on valueStack.
   * @return <tt>true</tt>, if conatins key, <tt>false</tt> otherwise.
   * @see java.util.HashMap#containsKey
   */
  public boolean containsKey(Object key) {
    boolean hasKey = super.containsKey(key);

    if (!hasKey) {
      if (valueStack.findValue((String) key) != null) {
        hasKey = true;
      }
    }

    return hasKey;
  }
コード例 #9
0
  // FIXME: Implement nested Generics such as: List of Generics List, Map of Generic keys/values,
  // etc...
  public void no_testGenericPropertiesWithNestedGenerics() {
    GenericsBean gb = new GenericsBean();
    ValueStack stack = ac.getValueStack();
    stack.push(gb);

    stack.setValue("extendedMap[123.12]", new String[] {"1", "2", "3", "4"});
    stack.setValue("extendedMap[456.12]", new String[] {"5", "6", "7", "8", "9"});

    System.out.println("gb.getExtendedMap(): " + gb.getExtendedMap());

    assertEquals(2, gb.getExtendedMap().size());
    System.out.println(stack.findValue("extendedMap"));
    assertEquals(4, stack.findValue("extendedMap.get(123.12).size"));
    assertEquals(5, stack.findValue("extendedMap.get(456.12).size"));

    assertEquals("1", stack.findValue("extendedMap.get(123.12).get(0)"));
    assertEquals("5", stack.findValue("extendedMap.get(456.12).get(0)"));
    assertEquals(Integer.class, stack.findValue("extendedMap.get(123.12).get(0).class"));
    assertEquals(Integer.class, stack.findValue("extendedMap.get(456.12).get(0).class"));

    assertEquals(List.class, stack.findValue("extendedMap.get(123.12).class"));
    assertEquals(List.class, stack.findValue("extendedMap.get(456.12).class"));
  }
コード例 #10
0
ファイル: JSONResult.java プロジェクト: wengui/wg-base
  /*
   * (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;
  }
コード例 #11
0
  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);
  }
コード例 #12
0
 public void testValueStackWithTypeParameter() {
   ValueStack stack = ActionContext.getContext().getValueStack();
   stack.push(new Foo1());
   Bar1 bar = (Bar1) stack.findValue("bar", Bar1.class);
   assertNotNull(bar);
 }
コード例 #13
0
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {

    ActionConfig config = invocation.getProxy().getConfig();
    ActionContext ac = invocation.getInvocationContext();
    Object action = invocation.getAction();

    // get the action's parameters
    final Map<String, String> parameters = config.getParams();

    if (parameters.containsKey(aliasesKey)) {

      String aliasExpression = parameters.get(aliasesKey);
      ValueStack stack = ac.getValueStack();
      Object obj = stack.findValue(aliasExpression);

      if (obj != null && obj instanceof Map) {
        // get secure stack
        ValueStack newStack = valueStackFactory.createValueStack(stack);
        boolean clearableStack = newStack instanceof ClearableValueStack;
        if (clearableStack) {
          // if the stack's context can be cleared, do that to prevent OGNL
          // from having access to objects in the stack, see XW-641
          ((ClearableValueStack) newStack).clearContextValues();
          Map<String, Object> context = newStack.getContext();
          ReflectionContextState.setCreatingNullObjects(context, true);
          ReflectionContextState.setDenyMethodExecution(context, true);
          ReflectionContextState.setReportingConversionErrors(context, true);

          // keep locale from original context
          context.put(ActionContext.LOCALE, stack.getContext().get(ActionContext.LOCALE));
        }

        // override
        Map aliases = (Map) obj;
        for (Object o : aliases.entrySet()) {
          Map.Entry entry = (Map.Entry) o;
          String name = entry.getKey().toString();
          String alias = (String) entry.getValue();
          Object value = stack.findValue(name);
          if (null == value) {
            // workaround
            Map<String, Object> contextParameters = ActionContext.getContext().getParameters();

            if (null != contextParameters) {
              value = contextParameters.get(name);
            }
          }
          if (null != value) {
            try {
              newStack.setValue(alias, value);
            } catch (RuntimeException e) {
              if (devMode) {
                String developerNotification =
                    LocalizedTextUtil.findText(
                        ParametersInterceptor.class,
                        "devmode.notification",
                        ActionContext.getContext().getLocale(),
                        "Developer Notification:\n{0}",
                        new Object[] {
                          "Unexpected Exception caught setting '"
                              + entry.getKey()
                              + "' on '"
                              + action.getClass()
                              + ": "
                              + e.getMessage()
                        });
                LOG.error(developerNotification);
                if (action instanceof ValidationAware) {
                  ((ValidationAware) action).addActionMessage(developerNotification);
                }
              }
            }
          }
        }

        if (clearableStack && (stack.getContext() != null) && (newStack.getContext() != null))
          stack
              .getContext()
              .put(
                  ActionContext.CONVERSION_ERRORS,
                  newStack.getContext().get(ActionContext.CONVERSION_ERRORS));
      } else {
        LOG.debug("invalid alias expression:" + aliasesKey);
      }
    }

    return invocation.invoke();
  }