如何在筛选器中加载属性文件

时间:2017-03-23 01:23:02

标签: java filter saml

我有一个需要SAML实现的应用程序,所以我包含了一个过滤器来进行验证或需要重定向。重定向工作正常,但是,重定向URL会根据我运行应用程序的环境而改变,因此我需要能够从属性文件中加载它。解码令牌所需的另一个属性也是如此。 加载属性文件的过程失败,属性变为空。

这是错误

[INFO] Mar 23, 2017 1:20:49 AM mypackage.SamlFilter init
[INFO] SEVERE: FAILED TO LOAD PROPERTIES FOR FILTER!!!!!!!!!!
[INFO] Mar 23, 2017 1:20:49 AM com.google.apphosting.utils.jetty.JettyLogger warn
[INFO] WARNING: failed SamlFilter: javax.servlet.ServletException: FAILED TO LOAD PROPERTIES FOR FILTER!!!!!!!!!!

这是班级

package mypackage;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Properties;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;

import org.apache.http.HttpStatus;
import org.codehaus.jettison.json.JSONObject;

import mypackage.utilities.JsonToken;
import mypackage.utilities.JsonTokenProcessor;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SamlFilter implements Filter {
    private JsonTokenProcessor jsonTokenProcessor;
    private String SSOurl;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        Cookie[] cookies = req.getCookies();
        if(cookies != null) { 
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    JsonToken jsonToken;
                    try {
                        jsonToken = jsonTokenProcessor.decode(token);
                    } catch (Exception e) {
                        log.error(e.getClass().getName() + " while decoding SAML token. Error: " + e.getLocalizedMessage());
                        res.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                        return;
                    }
                    if(!jsonToken.isExpired()) {
                        request.setAttribute("token", jsonToken);
                        chain.doFilter(request, response);
                        return;
                    }
                    break;
                }
            }
        }
        res.setStatus(HttpStatus.SC_UNAUTHORIZED);
        res.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        res.addHeader("Content-Type", MediaType.APPLICATION_JSON);
        res.addHeader("Expires", "0");
        res.addHeader("Pragma","no-cache");
        JSONObject returnObject = null;
        try {
            returnObject = new JSONObject();
            returnObject.put("redirectURL", redirectURL);
        } catch (Exception e) {
            log.warn("SamlFilter(): " + e.getClass().getName() + " Can't create redirect body. Error: " + e.getLocalizedMessage());
        }
        res.getWriter().write(returnObject.toString());
        res.getWriter().flush();
        res.getWriter().close();
        return;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Properties properties =     LoadProperties("properties/myfile.properties");
        String myproperty = properties.getProperty("myproperty");

        SSOurl = properties.getProperty("redirectURL");
        if(myproperty == null || myproperty.isEmpty() || SSOurl ==  null || SSOurl.isEmpty()) {
            throw new ServletException("FAILED TO LOAD PROPERTIES FOR FILTER!!!!!!!!!!");
        }
        try {
            jsonTokenProcessor = new JsonTokenProcessor(myproperty);
        } catch (Exception e) {
            log.error("Error: " + e.getLocalizedMessage());
        }
    }

    @Override
    public void destroy() {
    }

    private static Properties LoadProperties(String filename) {
        Properties newProperties = new Properties();
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
            if (inputStream != null) {
                newProperties.load(inputStream);
                Enumeration<?> e = newProperties.propertyNames();
                while (e.hasMoreElements()) {
                    String key = (String) e.nextElement();
                    String value = newProperties.getProperty(key);
                    log.info("Key : " + key + ", Value : " + value);
                }
            }
        } catch (Exception ex) {
            log.warn("Error: " + ex.getLocalizedMessage());
        }
        return newProperties;
    }
}

这是web.xml上的过滤器定义

<filter>
    <filter-name>SamlFilter</filter-name>
    <filter-class>mypackage.SamlFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SamlFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

1 个答案:

答案 0 :(得分:0)

所以我通过使加载属性的所有代码成为静态块来找到解决方案。这解决了一切

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void destroy() {
}

static {
    Properties newProperties = new Properties();
    try {
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("properties/myfile.properties");
        if (inputStream != null) {
            newProperties.load(inputStream);
            Enumeration<?> e = newProperties.propertyNames();
            while (e.hasMoreElements()) {
                String key = (String) e.nextElement();
                String value = newProperties.getProperty(key);
                log.info("Key : " + key + ", Value : " + value);
            }
        }
    } catch (Exception ex) {
        log.warn("Error: " + ex.getLocalizedMessage());
    }

    String myproperty = properties.getProperty("myproperty");

    SSOurl = properties.getProperty("redirectURL");
    if(myproperty == null || myproperty.isEmpty() || SSOurl ==  null || SSOurl.isEmpty()) {
        throw new ServletException("FAILED TO LOAD PROPERTIES FOR FILTER!!!!!!!!!!");
    }
    try {
        jsonTokenProcessor = new JsonTokenProcessor(myproperty);
    } catch (Exception e) {
        log.error("Error: " + e.getLocalizedMessage());
    }
}