com.opensymphony.xwork2.ActionInvocation Java Examples

The following examples show how to use com.opensymphony.xwork2.ActionInvocation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedirectMessageInterceptor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * If the result is a redirect then store error and messages in the session.
 * @param invocation
 * @param validationAware
 * @throws java.lang.Exception
 */
protected void after(ActionInvocation invocation, ValidationAware validationAware) throws Exception {
	Result result = invocation.getResult();
	if (result != null && (result instanceof ServletRedirectResult || result instanceof ServletActionRedirectResult || result instanceof FrontServletActionRedirectResult)) {
		HttpServletRequest request = (HttpServletRequest) invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
		HttpSession session = request.getSession();
		
		Collection<String> actionErrors = validationAware.getActionErrors();
		if (actionErrors != null && actionErrors.size() > 0) {
			session.setAttribute(ACTION_ERRORS_KEY, actionErrors);
		}
		Collection<String> actionMessages = validationAware.getActionMessages();
		if (actionMessages != null && actionMessages.size() > 0) {
			session.setAttribute(ACTION_MESSAGES_KEY, actionMessages);
		}
		Map<String, List<String>> fieldErrors = validationAware.getFieldErrors();
		if (fieldErrors != null && fieldErrors.size() > 0) {
			session.setAttribute(FIELD_ERRORS_KEY, fieldErrors);
		}
	}
}
 
Example #2
Source File: authInterceptor.java    From Mall-Server with MIT License 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
    String token = ServletActionContext.getRequest().getHeader("x-access-token");

    if (token != null) {
        User user = Token.validToken(token, User.class);
        if (user != null) {
            ServletActionContext.getRequest().setAttribute("tokenData", user);
            actionInvocation.invoke();
            return null;
        }
    }
    ActionContext context = ActionContext.getContext();
    ValueStack stack = context.getValueStack();
    stack.set("jsonResult", ResponseTemplate.error(1, "请传输正确token"));
    return "success";
}
 
Example #3
Source File: LogonInterceptor.java    From aliada-tool with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
 * @param  invocation
 *            The ActionInvocation to set.
 * @return Returns the result of the invocation.
 * @throws Exception for the invoke method
 */
public String intercept(final ActionInvocation invocation) throws Exception {

	final ActionContext context = invocation.getInvocationContext();
	HttpServletRequest request = (HttpServletRequest) context
			.get(HTTP_REQUEST);
	HttpSession session = request.getSession(true);

	// Is there a "user" object stored in the user's HttpSession?
	Object user = session.getAttribute(USER_HANDLE);
	if (user == null) {
		// The user has not logged in yet.

		// Is the user attempting to log in right now?
		String loginAttempt = request.getParameter(LOGIN_ATTEMPT);

		/* The user is attempting to log in. */
		if (!StringUtils.isBlank(loginAttempt)) {
			return invocation.invoke();
		}
		return "logon";
	} else {
		return invocation.invoke();
	}
}
 
Example #4
Source File: postInterceptor.java    From Mall-Server with MIT License 6 votes vote down vote up
/**
 * 只允许POST访问拦截器
 * @param actionInvocation
 * @return
 * @throws Exception
 */
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
    // 解决跨域
    HttpServletResponse res = ServletActionContext.getResponse();
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "*");
    res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
    res.setHeader("Access-Control-Expose-Headers", "*");

    String method = ServletActionContext.getRequest().getMethod();
    if (method.equals("POST")) {
        actionInvocation.invoke();
        return null;
    } else {
        ActionContext context = ActionContext.getContext();
        Map<String, Object> jsonResult = new HashMap<String, Object>();
        jsonResult.put("rcode", 1);
        jsonResult.put("message", "just allow post method");
        jsonResult.put("result", "");
        ValueStack stack = context.getValueStack();
        stack.set("jsonResult", jsonResult);
        return "success";
    }
}
 
Example #5
Source File: ConfigInterceptor.java    From S-mall-ssh with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {

    HttpServletRequest request = (HttpServletRequest) actionInvocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
    Object action = actionInvocation.getAction();
    Map<String,String> config = configService.map();
    //配置首页SEO参数
    if(action.getClass().getSimpleName().equals("ShowAction")&&actionInvocation.getProxy().getMethod().equals("home")){
        String indexTitle = config.get("index_title");
        String indexKeyword = config.get("index_keyword");
        String indexDescription = config.get("index_description");
        request.setAttribute("SEOTitle",indexTitle);
        request.setAttribute("keywords",indexKeyword);
        request.setAttribute("description",indexDescription);
    }
    request.setAttribute("website_name",config.get("website_name"));
    request.setAttribute("productImgDir",config.get("path_product_img"));
    request.setAttribute("categoryImgDir",config.get("path_category_img"));
    return  actionInvocation.invoke();

}
 
Example #6
Source File: CustomTokenInterceptor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected String handleInvalidToken(ActionInvocation invocation) throws Exception {
    Object action = invocation.getAction();
    String errorMessage = this.getCustomMessage(invocation, "struts.messages.invalid.token",
            "The form has already been processed or no token was supplied, please try again.");
    String message = this.getCustomMessage(invocation, "struts.messages.invalid.token.message",
            "Stop double-submission of forms.");
    if (action instanceof ValidationAware) {
        if (null == this.getTypeMessages() || this.getTypeMessages().equalsIgnoreCase(TYPE_RETURN_NONE_MESSAGE)) {
            //nothing to do
        } else if (this.getTypeMessages().equalsIgnoreCase(TYPE_RETURN_ACTION_ERROR_MESSAGE)) {
            ((ValidationAware) action).addActionError(errorMessage);
        } else if (this.getTypeMessages().equalsIgnoreCase(TYPE_RETURN_ACTION_MESSAGE)) {
            ((ValidationAware) action).addActionMessage(message);
        } else {
            LOG.warn("Invalid message type : {}", this.getTypeMessages());
        }
    } else {
        LOG.warn(errorMessage);
    }
    return INVALID_TOKEN_CODE;
}
 
Example #7
Source File: ServletActionRedirectResultWithAnchor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void execute(ActionInvocation invocation) throws Exception {
	this.actionName = this.conditionalParse(this.actionName, invocation);
    if (this.namespace == null) {
    	this.namespace = invocation.getProxy().getNamespace();
    } else {
    	this.namespace = this.conditionalParse(this.namespace, invocation);
    }
    if (this.method == null) {
    	this.method = "";
    } else {
    	this.method = this.conditionalParse(this.method, invocation);
    }
    StringBuilder tmpLocation = new StringBuilder(this.actionMapper.getUriFromActionMapping(new ActionMapping(actionName, namespace, method, null)));
    if (null != this.getAnchorDest()) {
    	this.setAnchor(this.getAnchorDest());
    }
    setLocation(tmpLocation.toString());
    super.execute(invocation);
}
 
Example #8
Source File: StrutsInterceptor.java    From javamelody with Apache License 2.0 6 votes vote down vote up
/**
 * Intercepte une exécution d'action struts.
 * @param invocation ActionInvocation
 * @return String
 * @throws Exception e
 */
@Override
public String intercept(ActionInvocation invocation) throws Exception { // NOPMD
	// cette méthode est appelée par struts
	if (DISABLED || !STRUTS_COUNTER.isDisplayed()) {
		return invocation.invoke();
	}
	boolean systemError = false;
	try {
		// Requested action name.
		final String actionName = getRequestName(invocation);

		STRUTS_COUNTER.bindContextIncludingCpu(actionName);
		return invocation.invoke();
	} catch (final Error e) {
		// on catche Error pour avoir les erreurs systèmes
		// mais pas Exception qui sont fonctionnelles en général
		systemError = true;
		throw e;
	} finally {
		// on enregistre la requête dans les statistiques
		STRUTS_COUNTER.addRequestForCurrentContext(systemError);
	}
}
 
Example #9
Source File: StringResult.java    From anyline with Apache License 2.0 6 votes vote down vote up
protected void doExecute(String finalLocation, ActionInvocation invocation) throws Exception { 
       HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(HTTP_RESPONSE); 
   	response.setContentType("text/plain; charset=UTF-8"); 
   	response.setCharacterEncoding("UTF-8"); 
       PrintWriter writer = response.getWriter(); 
       try { 
       	//提取Action的传入值 
       	data = invocation.getStack().findValue("data"); 
       	if(null == data){ 
       		data = ""; 
       	} 
       	writer.print(data.toString()); 
       }catch(Exception e){
       	e.printStackTrace(); 
       }finally { 
           if (writer != null) { 
               writer.flush(); 
               writer.close(); 
           } 
       } 
}
 
Example #10
Source File: JasperReportsResult.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
/**
 * Sets up result properties, parsing etc.
 *
 * @param invocation Current invocation.
 * @throws Exception on initialization error.
 */
private void initializeProperties(ActionInvocation invocation) throws Exception {
    if (dataSource == null && connection == null) {
        String message = "No dataSource specified...";
        LOG.error(message);
        throw new RuntimeException(message);
    }
    if (dataSource != null)
        dataSource = conditionalParse(dataSource, invocation);

    format = conditionalParse(format, invocation);
    if (StringUtils.isEmpty(format)) {
        format = FORMAT_PDF;
    }

    if (contentDisposition != null) {
        contentDisposition = conditionalParse(contentDisposition, invocation);
    }

    if (documentName != null) {
        documentName = conditionalParse(documentName, invocation);
    }

    reportParameters = conditionalParse(reportParameters, invocation);
    exportParameters = conditionalParse(exportParameters, invocation);
}
 
Example #11
Source File: AuthenticationInterceptor.java    From journaldev with MIT License 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation)
		throws Exception {
	System.out.println("inside auth interceptor");
	Map<String, Object> sessionAttributes = actionInvocation.getInvocationContext().getSession();
	
	User user = (User) sessionAttributes.get("USER");
	
	if(user == null){
		return Action.LOGIN;
	}else{
		Action action = (Action) actionInvocation.getAction();
		if(action instanceof UserAware){
			((UserAware) action).setUser(user);
		}
		return actionInvocation.invoke();
	}
}
 
Example #12
Source File: RedirectMessageInterceptor.java    From entando-components with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * If the result is a redirect then store error and messages in the session.
 */
protected void after(ActionInvocation invocation, ValidationAware validationAware) throws Exception {
	Result result = invocation.getResult();

	if (result != null && (result instanceof ServletRedirectResult || result instanceof ServletActionRedirectResult || result instanceof FrontServletActionRedirectResult)) {
		Map<String, Object> session = invocation.getInvocationContext().getSession();

		Collection<String> actionErrors = validationAware.getActionErrors();
		if (actionErrors != null && actionErrors.size() > 0) {
			session.put(ACTION_ERRORS_KEY, actionErrors);
		}

		Collection<String> actionMessages = validationAware.getActionMessages();
		if (actionMessages != null && actionMessages.size() > 0) {
			session.put(ACTION_MESSAGES_KEY, actionMessages);
		}

		Map<String, List<String>> fieldErrors = validationAware.getFieldErrors();
		if (fieldErrors != null && fieldErrors.size() > 0) {
			session.put(FIELD_ERRORS_KEY, fieldErrors);
		}
	}
}
 
Example #13
Source File: HttpMethodInterceptor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public String intercept( ActionInvocation invocation )
    throws Exception
{
    String method = ServletActionContext.getRequest().getMethod();
    
    log.info( "Method: " + method );
    
    if ( method == null || !method.trim().toLowerCase().equals( allowedMethod.trim().toLowerCase() ) )
    {
        log.warn( "HTTP method ' " + allowedMethod + "' only allowed for this request" );
        
        return null;
    }
    
    return invocation.invoke();
}
 
Example #14
Source File: ActionInfoSupportInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	/*
	ActionInvocation ai=(ActionInvocation)ActionContext.getContext().get(ActionContext.ACTION_INVOCATION); 
	String action=ai.getProxy().getActionName(); 
	String namespace=ai.getProxy().getNamespace();
	*/
	HttpServletRequest request=ServletActionContext.getRequest(); 
	ActionContext context=actionInvocation.getInvocationContext();	
	String action=actionInvocation.getProxy().getActionName();
	String namespace=actionInvocation.getProxy().getNamespace();
	String remoteAddr=request.getRemoteAddr();
	String referer=request.getHeader("referer");		
	context.getSession().put(Constants.SESS_PAGE_INFO_ACTION_ByInterceptor, action);
	context.getSession().put(Constants.SESS_PAGE_INFO_NAMESPACE_ByInterceptor, namespace);
	context.getSession().put(Constants.SESS_PAGE_INFO_RemoteAddr_ByInterceptor, remoteAddr);
	context.getSession().put(Constants.SESS_PAGE_INFO_Referer_ByInterceptor, referer);	
	return actionInvocation.invoke();
}
 
Example #15
Source File: BaseSimpleActionInfo.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
public void execute() {
	ActionInvocation actionInvocation=ActionContext.getContext().getActionInvocation();		
	HttpServletRequest request=ServletActionContext.getRequest(); 
	
	String action=SimpleUtils.getStr(actionInvocation.getProxy().getActionName(), "");
	String namespace=SimpleUtils.getStr(actionInvocation.getProxy().getNamespace(), "");		
	String remoteAddr=SimpleUtils.getStr(request.getRemoteAddr(), "");
	String referer=SimpleUtils.getStr(request.getHeader("referer"), "");
	this.actionMethodName = actionInvocation.getProxy().getMethod();
	
	ActionContext.getContext().getSession().put(Constants.SESS_PAGE_INFO_ACTION_ByAction, action);
	ActionContext.getContext().getSession().put(Constants.SESS_PAGE_INFO_NAMESPACE_ByAction, namespace);
	ActionContext.getContext().getSession().put(Constants.SESS_PAGE_INFO_RemoteAddr_ByAction, remoteAddr);
	ActionContext.getContext().getSession().put(Constants.SESS_PAGE_INFO_Referer_ByAction, referer);
	this.pageInfoActionName=action;
	this.pageInfoNamespace=namespace;
	this.pageInfoRemoteAddr=remoteAddr;
	this.pageInfoReferer=referer;
	
}
 
Example #16
Source File: OrganisationUnitTreeInterceptor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void executeBeforeResult( ActionInvocation actionInvocation, String result )
    throws Exception
{
    Collection<OrganisationUnit> selectedUnits;
    List<OrganisationUnit> rootUnits;

    selectedUnits = selectionManager.getSelectedOrganisationUnits();   
    
    rootUnits = new ArrayList<>( selectionManager.getRootOrganisationUnits() );

    if ( selectedUnits == null )
    {
        selectedUnits = Collections.emptySet();
    }

    List<TreeNode> rootNodes = new ArrayList<>( rootUnits.size() );

    Set<OrganisationUnit> pathUnits = getPathUnits( rootUnits, selectedUnits );

    rootNodes = createLevelNodes( pathUnits, rootUnits, selectedUnits );

    Map<String, Collection<TreeNode>> valueMap = new HashMap<>( 1 );
    valueMap.put( VALUE_KEY, rootNodes );
    actionInvocation.getStack().push( valueMap );
}
 
Example #17
Source File: UserLoginInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	ActionContext actionContext=actionInvocation.getInvocationContext();  
	Map<String, Object> session=actionContext.getSession();  
	this.accountObj = (AccountObj)session.get(Constants.SESS_ACCOUNT);
	Map<String, String> dataMap = UserCurrentCookie.getCurrentData( (HttpServletRequest)actionContext.get(StrutsStatics.HTTP_REQUEST) );
	String currentId = StringUtils.defaultString( dataMap.get("currentId") );
	String accountId = StringUtils.defaultString( dataMap.get("account") );
	if (accountObj!=null && !StringUtils.isBlank(accountObj.getAccount()) ) {
		if ( StringUtils.isBlank(currentId) ) {
			currentId = "NULL";
		}
		String sessSysCurrentId = (String)session.get(Constants.SESS_SYSCURRENT_ID);
		if ( !currentId.equals(sessSysCurrentId) ) {
			logger.warn( "currentId: " + currentId + " not equals session variable currentId: " + sessSysCurrentId );
			return this.redirectLogin(actionInvocation, session, currentId, accountId);
		}
		if (uSessLogHelper.countByCurrent(accountObj.getAccount(), currentId)<1) {
			return this.redirectLogin(actionInvocation, session, currentId, accountId);
		}						
		return actionInvocation.invoke();
	} 
	return this.redirectLogin(actionInvocation, session, currentId, accountId);
}
 
Example #18
Source File: SecurityInterceptor.java    From OA with GNU General Public License v3.0 6 votes vote down vote up
public String intercept(ActionInvocation invocation) throws Exception {
		HttpSession session = ServletActionContext.getRequest().getSession();
		HttpServletRequest request=ServletActionContext.getRequest();
		String clazz=invocation.getAction().getClass().getName();
		System.out.println("clazz is "+clazz);
//		System.out.println(clazz+invocation.getAction());
		
		if (session.getAttribute("admin") == null ){
			if(UserAction.class.getName().equals(clazz)){
				System.out.println("if admin is null");
				return invocation.invoke(); 
			}
			System.out.println("admin is null");
			return Action.LOGIN;
		}else {
			if(UserAction.class.getName().equals(clazz)){
				Map parameters = invocation.getInvocationContext().getParameters();
				if(parameters.get("user.account")!=null){
					System.out.println("-====");
					System.out.println("user.account");
					session.removeAttribute("admin");
				}
			}
			return invocation.invoke();
		}
	}
 
Example #19
Source File: JetTemplateResult.java    From jetbrick-template-1x with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(String location, ActionInvocation ai) throws Exception {
    Map<String, Object> model = ai.getStack().getContext();
    HttpServletRequest request = (HttpServletRequest) model.get(ServletActionContext.HTTP_REQUEST);
    HttpServletResponse response = (HttpServletResponse) model.get(ServletActionContext.HTTP_RESPONSE);

    if (JetWebEngineLoader.unavailable()) {
        ServletContext servletContext = (ServletContext) model.get(ServletActionContext.SERVLET_CONTEXT);
        JetWebEngineLoader.setServletContext(servletContext);
    }

    JetContext context = new JetWebContext(request, response, null);
    context.put("action", ai.getAction());
    context.put("valueStack", model);
    JetTemplate template = JetWebEngineLoader.getJetEngine().getTemplate(location);
    template.render(context, response.getOutputStream());
}
 
Example #20
Source File: SystemSettingInterceptor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public String intercept( ActionInvocation invocation )
    throws Exception
{
    Map<String, Object> map = new HashMap<>();
    
    map.put( DATE_FORMAT, calendarService.getSystemDateFormat() );
    map.put( SettingKey.CONFIGURATION.getName(), configurationService.getConfiguration() );
    map.put( SettingKey.FLAG_IMAGE.getName(), systemSettingManager.getFlagImage() );
    map.put( SettingKey.CREDENTIALS_EXPIRES.getName(), systemSettingManager.credentialsExpires() );
    map.put( SettingKey.SELF_REGISTRATION_NO_RECAPTCHA.getName(), systemSettingManager.selfRegistrationNoRecaptcha() );
    map.put( SYSPROP_PORTAL, defaultIfEmpty( System.getProperty( SYSPROP_PORTAL ), String.valueOf( false ) ) );
    
    map.putAll( systemSettingManager.getSystemSettings( SETTINGS ) );
    
    invocation.getStack().push( map );

    return invocation.invoke();
}
 
Example #21
Source File: CustomJFreeChartResult.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {		
	Object newWidth = ActionContext.getContext().getValueStack().findValue("width");
	Object newHeight = ActionContext.getContext().getValueStack().findValue("height");
	if ( NumberUtils.isCreatable(String.valueOf(newWidth)) && NumberUtils.isCreatable(String.valueOf(newHeight)) ) {			
		int w = NumberUtils.toInt( String.valueOf(newWidth) );
		int h = NumberUtils.toInt( String.valueOf(newHeight) );
		if ( w > MAX_WIDTH ) {
			w = MAX_WIDTH;
		}
		if ( h > MAX_HEIGHT ) {
			h = MAX_HEIGHT;				
		}
		if ( w < MIN_WIDTH ) {
			w = MIN_WIDTH;				
		}
		if ( h < MIN_HEIGHT ) {
			h = MIN_HEIGHT;
		}
		super.setWidth(String.valueOf(w));
		super.setHeight(String.valueOf(h));
		logger.info("reset chart width=" + w + " , heigh=" + h);			
	}
	super.doExecute(finalLocation, invocation);
}
 
Example #22
Source File: UserAgentRejectInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {		
	HttpServletRequest request=ServletActionContext.getRequest(); 
	String userAgent = SimpleUtils.getStr(request.getHeader("User-Agent")).toUpperCase();
	if (rejectAgent==null) {
		return actionInvocation.invoke();
	}
	for (int i=0; rejectAgent!=null && i<rejectAgent.length; i++) {
		if (rejectAgent[i].trim().equals("")) {
			continue;
		}
		if (userAgent.indexOf(rejectAgent[i])>-1) {
			Map<String, Object> valueStackMap = new HashMap<String, Object>();
			valueStackMap.put("errorMessage", "not supported " + userAgent);
			valueStackMap.put("pageMessage", "not supported " + userAgent);
			ActionContext.getContext().getValueStack().push(valueStackMap);
			logger.warn("reject User-Agent="+userAgent);
			return "rejectUserAgent";
		}
	}
	return actionInvocation.invoke();
}
 
Example #23
Source File: JasperReportCloseConnHelperInterceptor.java    From bamboobsc with Apache License 2.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
	String result=actionInvocation.invoke();
	/**
	 * findValue 依照 jasper action xml 設定名稱決定
	 * 
	 * 如:
	 * <param name="connection">conn123</param>
	 * 
	 * 所以 findValue("conn123");
	 * 
	 */
	Connection connection=(Connection)actionInvocation.getStack().findValue("connection");
	if (connection!=null) {
		DataUtils.doReleaseConnection(connection);
		System.out.println(JasperReportCloseConnHelperInterceptor.class.getName()+" doReleaseConnection ...");
	} else {
		System.out.println(JasperReportCloseConnHelperInterceptor.class.getName()+" null connection ...");
	}
	return result;
}
 
Example #24
Source File: ApsFileUploadInterceptor.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String intercept(ActionInvocation invocation) throws Exception {
	if (null == super.maximumSize || super.maximumSize == 0) {
		ConfigInterface configManager = (ConfigInterface) ApsWebApplicationUtils.getBean(SystemConstants.BASE_CONFIG_MANAGER, ServletActionContext.getRequest());
		String maxSizeParam = configManager.getParam(SystemConstants.PAR_FILEUPLOAD_MAXSIZE);
		if (null != maxSizeParam) {
			try {
				this.setMaximumSize(Long.parseLong(maxSizeParam));
			} catch (Throwable t) {
				_logger.error("Error parsing param 'maxSize' - value '{}' - message ", maxSizeParam, t);
			}
		}
	}
	if (null == super.maximumSize || super.maximumSize == 0) {
		this.setMaximumSize(DEFAULT_MAX_SIZE);
	}
	return super.intercept(invocation);
}
 
Example #25
Source File: LoginInterceptor.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public String intercept( ActionInvocation invocation )
    throws Exception
{
    Boolean jli = (Boolean) ServletActionContext.getRequest().getSession()
        .getAttribute( LoginInterceptor.JLI_SESSION_VARIABLE );

    if ( jli != null )
    {
        log.debug( "JLI marker is present. Running " + actions.size() + " JLI actions." );

        for ( Action a : actions )
        {
            a.execute();
        }

        ServletActionContext.getRequest().getSession().removeAttribute( LoginInterceptor.JLI_SESSION_VARIABLE );
    }

    return invocation.invoke();
}
 
Example #26
Source File: FrontServletActionRedirectResult.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void extractResultParams(Map<String, String> redirectParams, ResultConfig resultConfig, ActionInvocation invocation) {
    Map resultConfigParams = resultConfig.getParams();
    for (Iterator i = resultConfigParams.entrySet().iterator(); i.hasNext();) {
        Map.Entry e = (Map.Entry) i.next();
        if (!this.getProhibitedResultParams().contains(e.getKey())) {
            String potentialValue = e.getValue() == null ? "" : conditionalParse(e.getValue().toString(), invocation);
            if (!suppressEmptyParameters || ((potentialValue != null) && (potentialValue.length() > 0))) {
                redirectParams.put(e.getKey().toString(), potentialValue);
            }
        }
    }
}
 
Example #27
Source File: CheckPrivilegeInterceptor.java    From SmartEducation with Apache License 2.0 5 votes vote down vote up
public String intercept(ActionInvocation invocation) throws Exception {
	// 获取信息
	User user = (User) ActionContext.getContext().getSession().get("user"); // 当前登录用户
	//    /
	String namespace = invocation.getProxy().getNamespace();
	//   xxx_xxxx
	String actionName = invocation.getProxy().getActionName();
	//     /xxx_xxxx
	String privUrl = namespace + actionName; // 对应的权限URL

	// 如果未登录
	if (user == null) {
		if (privUrl.startsWith("/user_login")||privUrl.equals("/rand")) { 
			// "/user_loginUI",
			// "/user_login"
			// 如果是去登录,就放行
			return invocation.invoke();
		} else {
			// 如果不是去登录
				//-->绑定
			if(privUrl.startsWith("/qqLoginInfo")||privUrl.startsWith("/weiboInfo"))
				return invocation.invoke();
			return "loginUI";
		}
	}
	// 如果已登录,就判断权限
	else {
		if (user.hasPrivilegeByUrl(privUrl)) {
			// 如果有权限,就放行
			return invocation.invoke();
		} else {
			// 如果没有权限,就转到提示页面
			return "noPrivilegeError";
		}
	}
}
 
Example #28
Source File: LoggeduserInterceptor.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String intercept(ActionInvocation invocation) throws Exception {
	boolean isAuthorized = false;
	try {
		HttpSession session = ServletActionContext.getRequest().getSession();
		UserDetails currentUser = (UserDetails) session.getAttribute(SystemConstants.SESSIONPARAM_CURRENT_USER);
		isAuthorized = null != currentUser && !currentUser.getUsername().equals(SystemConstants.GUEST_USER_NAME);
		if (isAuthorized) {
			return this.invoke(invocation);
		}
	} catch (Throwable t) {
		_logger.error("Error occurred verifying logged user", t);
	}
	return this.getErrorResultName();
}
 
Example #29
Source File: GridJasperResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void execute( ActionInvocation invocation )
    throws Exception
{
    // ---------------------------------------------------------------------
    // Get grid
    // ---------------------------------------------------------------------

    Grid _grid = (Grid) invocation.getStack().findValue( "grid" );
    
    grid = _grid != null ? _grid : grid;
    
    Map<String, Object> _params = (Map<String, Object>) invocation.getStack().findValue( "params" );

    params = _params != null ? _params : params;
    
    // ---------------------------------------------------------------------
    // Configure response
    // ---------------------------------------------------------------------

    HttpServletResponse response = ServletActionContext.getResponse();

    String filename = CodecUtils.filenameEncode( StringUtils.defaultIfEmpty( grid.getTitle(), DEFAULT_FILENAME ) ) + ".pdf";
    
    ContextUtils.configureResponse( response, ContextUtils.CONTENT_TYPE_PDF, true, filename, false );
    
    // ---------------------------------------------------------------------
    // Write jrxml based on Velocity template
    // ---------------------------------------------------------------------

    GridUtils.toJasperReport( grid, params, response.getOutputStream() );
}
 
Example #30
Source File: PlainTextErrorResult.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void execute( ActionInvocation invocation )
    throws Exception
{
    HttpServletResponse response = (HttpServletResponse) invocation.getInvocationContext().get(
        StrutsStatics.HTTP_RESPONSE );

    response.setContentType( "text/plain; charset=UTF-8" );
    response.setHeader( "Content-Disposition", "inline" );
    response.setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );

    ValueStack stack = ActionContext.getContext().getValueStack();
    String finalMessage = parse ? TextParseUtil.translateVariables( message, stack ) : message;

    finalMessage = formatFinalMessage( finalMessage );

    // ---------------------------------------------------------------------
    // Write final message
    // ---------------------------------------------------------------------

    PrintWriter writer = null;

    try
    {
        writer = response.getWriter();
        writer.print( finalMessage );
        writer.flush();
    }
    finally
    {
        if ( writer != null )
        {
            writer.close();
        }
    }
}