package eu.dnetlib.enabling.is.sn;

import javax.xml.transform.dom.DOMResult;
import javax.xml.ws.wsaddressing.W3CEndpointReference;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * Extracts useful low level informations from an EPR, so that these can be encoded in the OAI
 * resumption token.
 *
 * @author michele
 *
 */
public final class EPRUtil {

	/**
	 * prevents instantiation.
	 */
	private EPRUtil() {
		// prevents instantiation
	}

	/**
	 * Extracts the service address out of the EPR.
	 *
	 * @param epr epr
	 * @return address
	 */
	public static String getAddress(final W3CEndpointReference epr) {
		return getValue(epr, "Address");
	}

	/**
	 * Extracts the resource identifier out of the EPR.
	 * @param epr epr
	 * @return resource identifier
	 */
	public static String getResourceIdentifier(final W3CEndpointReference epr) {
		return getValue(epr, "ResourceIdentifier");
	}

	/**
	 * Extracts an element with a given local name out of the resource identifier.
	 *
	 * @param epr epr
	 * @param name element name
	 * @return element value
	 */
	private static String getValue(final W3CEndpointReference epr, final String name) {
		final DOMResult dom = new DOMResult();
		epr.writeTo(dom);

		try {
			return XPathFactory.newInstance().newXPath().evaluate("//*[local-name() = '" + name + "']", dom.getNode());
		} catch (final XPathExpressionException e) {
			throw new IllegalStateException("cannot construct xpath expression", e);
		}
	}





}
