package eu.dnetlib.pid.service;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.cxf.interceptor.AbstractOutDatabindingInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.message.Message;
import org.apache.cxf.phase.Phase;

/**
 * Class to intercept outgoing HTTP SOAP messages.
 * <p>
 * It adds to each intercepted message an HTTP header called 'Authorization' with the value contained in the field
 * 'authKey'.
 * </p>
 * 
 * @author alessia
 * 
 */
public class HeaderGeneratorInterceptor extends AbstractOutDatabindingInterceptor {
	/** Logger. */
	private static final Log log = LogFactory.getLog(HeaderGeneratorInterceptor.class); // NOPMD by marko on 11/24/08 5:02 PM
	/** Value of the Authorization header to add as HTTP header to the intercepted message. */
	private String authKey;

	public HeaderGeneratorInterceptor() {
		super(Phase.MARSHAL);
	}

	public HeaderGeneratorInterceptor(final String phase) {
		super(phase);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void handleMessage(Message outMessage) throws Fault {
		log.debug("INTERCEPTOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOR");

		final Map<String, List> headers = (Map<String, List>) outMessage.get(Message.PROTOCOL_HEADERS);
		try {
			headers.put("Authorization", Collections.singletonList(this.authKey));
			log.debug(headers);
		} catch (final Exception ce) {
			log.debug("exce: " + ce);
			throw new RuntimeException(ce);
		}
	}

	public void setAuthKey(final String authKey) {
		this.authKey = authKey;
	}

	public String getAuthKey() {
		return this.authKey;
	}
}
