class EtagHandlerPipe extends FixedForwardPipe {

	@Override
	public PipeRunResult doPipe(Message message, IPipeLineSession session) throws PipeRunException {
		if (message==null) {
			throw new PipeRunException(this, getLogPrefix(session)+"got null input");
		}

		String uriPatternSessionKey = null;
		ParameterValueList pvl = null;
		ParameterList parameterList = getParameterList();
		if (parameterList != null) {
			try {
				pvl = parameterList.getValues(message, session);
				if (pvl != null) {
					String uriPattern = (String)pvl.getValue("uriPattern");
					if (uriPattern!=null) {
						uriPatternSessionKey = uriPattern;
					}
				}
			} catch (ParameterException e) {
				throw new PipeRunException(this, getLogPrefix(session) + "exception extracting parameters", e);
			}
		}

		//hash over data genereren, uit cache lezen en teruggeven, in cache updaten, verwijderen uit cache, cache naar disk wegschrijven, cache legen
		String cacheKey = null;
		if(uriPatternSessionKey != null && !uriPatternSessionKey.isEmpty())
			cacheKey = getRestPath()+"_"+uriPatternSessionKey.toLowerCase();
		else
			cacheKey = getRestPath()+"_"+getUriPattern();
		if(cache != null && cache.containsKey(cacheKey)) {
			Object returnCode = false;

			if(getAction().equalsIgnoreCase("generate")) {
				try {
					cache.put(cacheKey, RestListenerUtils.formatEtag(getRestPath(), getUriPattern(), message.asString().hashCode()));
				} catch (IOException e) {
					throw new PipeRunException(this, getLogPrefix(session)+"cannot open stream", e);
				}
				returnCode = true;
			}
			else if(getAction().equalsIgnoreCase("get")) {
				returnCode = cache.get(cacheKey);
			}
			else if(getAction().equalsIgnoreCase("set")) {
				try {
					cache.put(cacheKey, message.asString());
				} catch (IOException e) {
					throw new PipeRunException(this, getLogPrefix(session)+"cannot open stream", e);
				}
				returnCode = true;
			}
			else if(getAction().equalsIgnoreCase("delete")) {
				returnCode = cache.remove(cacheKey);
			}
			else if(getAction().equalsIgnoreCase("flush")) {
				if(cache instanceof ApiEhcache) {
					((ApiEhcache) cache).flush();
					returnCode = true;
				}
			}
			else if(getAction().equalsIgnoreCase("clear")) {
				cache.clear();
				returnCode = true;
			}
			else {
				throw new PipeRunException(this, getLogPrefix(session)+"action not found ["+getAction()+"]"); 
			}
			if(log.isDebugEnabled()) log.debug("found eTag cacheKey ["+cacheKey+"] with action ["+getAction()+"]");

			return new PipeRunResult(getForward(), returnCode);
		}
		else {
			PipeForward pipeForward = findForward("exception");
			String msg;

			if(cache == null)
				msg = "failed to locate cache";
			else
				msg = "failed to locate eTag ["+cacheKey+"] in cache";

			if (pipeForward==null) {
				throw new PipeRunException (this, getLogPrefix(session)+msg);
			}

			return new PipeRunResult(pipeForward, "");
		}
	}

}