Example #1
0
  /** Creates the action context and initializes the thread local */
  public ActionContext createActionContext(
      HttpServletRequest request, HttpServletResponse response) {
    ActionContext ctx;
    Integer counter = 1;
    Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);
    if (oldCounter != null) {
      counter = oldCounter + 1;
    }

    ActionContext oldContext = ActionContext.getContext();
    if (oldContext != null) {
      // detected existing context, so we are probably in a forward
      ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));
    } else {
      ValueStack stack =
          dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
      stack
          .getContext()
          .putAll(dispatcher.createContextMap(request, response, null, servletContext));

      // 利用ValueStack的context属性实例化ActionContext
      ctx = new ActionContext(stack.getContext());
    }
    request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);
    ActionContext.setContext(ctx);
    return ctx;
  }
  @Override
  public String doIntercept(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    if (!(action instanceof NoParameters)) {
      ActionContext ac = invocation.getInvocationContext();
      final Map<String, Object> parameters = retrieveParameters(ac);

      if (LOG.isDebugEnabled()) {
        LOG.debug("Setting params " + getParameterLogMap(parameters));
      }

      if (parameters != null) {
        Map<String, Object> contextMap = ac.getContextMap();
        try {
          ReflectionContextState.setCreatingNullObjects(contextMap, true);
          ReflectionContextState.setDenyMethodExecution(contextMap, true);
          ReflectionContextState.setReportingConversionErrors(contextMap, true);

          ValueStack stack = ac.getValueStack();
          setParameters(action, stack, parameters);
        } finally {
          ReflectionContextState.setCreatingNullObjects(contextMap, false);
          ReflectionContextState.setDenyMethodExecution(contextMap, false);
          ReflectionContextState.setReportingConversionErrors(contextMap, false);
        }
      }
    }
    return invocation.invoke();
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    converter = container.getInstance(XWorkConverter.class);

    ac = ActionContext.getContext();
    ac.setLocale(Locale.US);
    context = ac.getContextMap();
  }
  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&param2=value+2&param3=value+3#fragment",
        res.getRedirectedUrl());

    control.verify();
  }
  /**
   * 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);
      }
    }
  }