package org.apache.servicemix.samples;
import java.util.ArrayList;
import java.util.List;
import javax.jbi.component.ComponentContext;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.MessageExchange;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.servicemix.http.endpoints.HttpSoapConsumerMarshaler;
/**
* Works in the same way as the HttpSoapConsumerMarshaler, plus adds the ability to filter incoming
* request with a blacklist/whitelist mechanism.
* @author <a href="" class="code-quote">"mailto:[email protected]">Jean-Baptiste Onofré</a>
* @version $Revision: 1.1 $
*/
public class ListedSoapConsumerMarshaler extends HttpSoapConsumerMarshaler {
private static final String IP_REJECTED = "IP_REJECTED";
private List<String> whitelist = new ArrayList<String>();
private List<String> blacklist = new ArrayList<String>();
/**
* @see org.apache.servicemix.http.endpoints.HttpSoapConsumerMarshaler#createExchange(javax.servlet.http.HttpServletRequest, javax.jbi.component.ComponentContext)
*/
public MessageExchange createExchange(HttpServletRequest request, ComponentContext context) throws Exception {
String requestIp = request.getRemoteAddr();
MessageExchange m = super.createExchange(request, context);
if (!isAllowed(requestIp)) {
m.setStatus(ExchangeStatus.ERROR);
m.setProperty(IP_REJECTED, Boolean.TRUE);
}
return m;
}
/**
* @see org.apache.servicemix.http.endpoints.HttpSoapConsumerMarshaler#sendError(javax.jbi.messaging.MessageExchange, java.lang.Exception, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void sendError(MessageExchange exchange, Exception error, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (exchange != null && Boolean.TRUE.equals(exchange.getProperty(IP_REJECTED))) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
} else {
super.sendError(exchange, error, request, response);
}
}
/**
* Test if the given ip is allowed to access this service.
* @param ip ip address
* @throws SecurityException
*
*/
protected boolean isAllowed(String ip) throws SecurityException {
return ((whitelist.isEmpty() || whitelist.contains(ip)) && !blacklist.contains(ip));
}
private List<String> parseAndConvertAsList(String ipList) {
List<String> res = new ArrayList<String>();
log.debug("Parsing IP list", ipList);
if (ipList != null) {
String[] ips = ipList.split("\\,");
for (String s : ips) {
String ip = s.trim();
if (ip.length() > 0) res.add(ip);
}
}
return res;
}
/**
* @param w the whitelist to set
*/
public void setWhitelist(String w) {
this.whitelist = parseAndConvertAsList(w);
}
/**
* @param b the blacklist to set
*/
public void setBlacklist(String b) {
this.blacklist = parseAndConvertAsList(b);
}
}