/*
 * 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;

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

	/**
	 * @param expression XPath の文字列表現。
	 * @throws JXPathException コンパイルに失敗した場合。
	 */
	public JXE(final String expression) {
		super();
		// TODO Convertable
		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 boolean setValue(final Object root, final Object value) {
		try {
			JXPathContext.newContext(root).setValue(expression, value);
			return true;
		} catch (final JXPathException e) {
			if (e.getException() != null
					&& !(e.getException() instanceof JXPathException)) {
				throw new ELTargetRuntimeException(e.getException());
			} else {
				throw e;
			}
		}
	}

	public String getExpression() {
		return expression;
	}
}
