/*
 * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * 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 com.b2international.snowowl.datastore.request;

import java.io.IOException;

import com.b2international.index.revision.RevisionIndex;
import com.b2international.index.revision.RevisionIndexRead;
import com.b2international.index.revision.RevisionSearcher;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.domain.DelegatingBranchContext;
import com.b2international.snowowl.core.events.DelegatingRequest;
import com.b2international.snowowl.core.events.Request;

/**
 * A subclass of {@link DelegatingRequest} that:
 * <ul>
 * <li>opens an index read transaction using {@link IndexTransactionProvider};
 * <li>executes the delegate with a {@link BranchContext} that allows access to an {@link IndexSearcher} from the read
 * transaction.
 * </ul>
 * 
 * @since 4.5
 */
public final class RevisionIndexReadRequest<B> extends DelegatingRequest<BranchContext, BranchContext, B> {

	RevisionIndexReadRequest(Request<BranchContext, B> next) {
		super(next);
	}
	
	@Override
	public B execute(final BranchContext context) {
		return context.service(RevisionIndex.class).read(context.branch().path(), new RevisionIndexRead<B>() {
			@Override
			public B execute(RevisionSearcher index) throws IOException {
				return wrapAndExecute(context, index);
			}
		});
	}
	
	private B wrapAndExecute(final BranchContext context, final RevisionSearcher index) {
		final BranchContext decoratedContext = new DelegatingBranchContext(context) {
			@Override
			public <T> T service(Class<T> type) {
				if (type.isAssignableFrom(RevisionSearcher.class)) {
					return type.cast(index);
				} else {
					return super.service(type);
				}
			}
		};

		return next(decoratedContext);
	}
}

@@ -706,16 +706,76 @@
 ption;%0A%0A
+import com.b2international.index.query.QueryParseException;%0A
 import c
@@ -1199,16 +1199,99 @@
 Request;
+%0Aimport com.b2international.snowowl.core.exceptions.IllegalQueryParameterException;
 %0A%0A/**%0A *
@@ -2022,16 +2022,27 @@
 ption %7B%0A
+%09%09%09%09try %7B%0A%09
 %09%09%09%09retu
@@ -2076,16 +2076,123 @@
 index);%0A
+%09%09%09%09%7D catch (QueryParseException e) %7B%0A%09%09%09%09%09throw new IllegalQueryParameterException(e.getMessage());%0A%09%09%09%09%7D%0A
 %09%09%09%7D%0A%09%09%7D

throw IllegalQueryParameterEx. if failed to parse query...