/*
 * Copyright 2006 Takahiro Nakamura.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package woolpack.adapter;

import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.jxpath.JXPathException;

import woolpack.el.AbstractEL;
import woolpack.el.ELTargetRuntimeException;
import woolpack.utils.CheckUtils;

/**
 * JXPath を使用した{@link woolpack.el.EL}(JXPath Expression)。
 * 本クラスはイミュータブルである。 本クラスは JXPath のライブラリを使用する。
 * 適用しているパターン：Adapter。
 * 
 * @author nakamura
 * 
 */
public class JXE extends AbstractEL {
	private final String expression;

	/**
	 * コンストラクタ。
	 * 
	 * @param expression
	 *            XPath の文字列表現。
	 * @throws NullPointerException
	 *             引数が null の場合。
	 * @throws StringIndexOutOfBoundsException
	 *             引数が空の場合。
	 * @throws JXPathException
	 *             のコンパイルに失敗した場合。
	 */
	public JXE(final String expression) {
		super();
		// TODO Convertable
		CheckUtils.checkNotEmpty(expression);
		this.expression = expression;
		JXPathContext.compile(expression);
	}

	/**
	 * @throws ELTargetRuntimeException
	 *             メソッドがエラーを投げた場合。
	 */
	@Override
	public Object getValue(final Object root, final Class toType) {
		try {
			return JXPathContext.newContext(root).getValue(expression, toType);
		} catch (final JXPathException e) {
			if (e.getException() != null
					&& !(e.getException() instanceof JXPathException)) {
				throw new ELTargetRuntimeException(e.getException());
			} else {
				throw e;
			}
		}
	}

	/**
	 * @throws ELTargetRuntimeException
	 *             メソッドがエラーを投げた場合。
	 */
	@Override
	public void setValue(final Object root, final Object value) {
		try {
			JXPathContext.newContext(root).setValue(expression, value);
		} catch (final JXPathException e) {
			if (e.getException() != null
					&& !(e.getException() instanceof JXPathException)) {
				throw new ELTargetRuntimeException(e.getException());
			} else {
				throw e;
			}
		}
	}
}
