001/*
002 *  Copyright 2010 Anyware Services
003 *
004 *  Licensed under the Apache License, Version 2.0 (the "License");
005 *  you may not use this file except in compliance with the License.
006 *  You may obtain a copy of the License at
007 *
008 *      http://www.apache.org/licenses/LICENSE-2.0
009 *
010 *  Unless required by applicable law or agreed to in writing, software
011 *  distributed under the License is distributed on an "AS IS" BASIS,
012 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 *  See the License for the specific language governing permissions and
014 *  limitations under the License.
015 */
016package org.ametys.cms.repository;
017
018import java.util.Date;
019
020import org.apache.commons.lang.time.FastDateFormat;
021
022import org.ametys.plugins.repository.query.expression.Expression;
023
024/**
025 * Constructs an {@link Expression} testing the existence of a particular step on the workflow history.
026 */
027public class HistoryStepExpression implements Expression
028{
029    private int _step;
030    private Date _startBefore;
031    private Date _startAfter;
032
033    /**
034     * Creates the expression.
035     * @param stepId the workflow step
036     */
037    public HistoryStepExpression(int stepId)
038    {
039        _step = stepId;
040    }
041    
042    /**
043     * Creates the expression.
044     * @param stepId the workflow step
045     * @param startAfter the beginning Date
046     * @param startBefore the ending Date
047     */
048    public HistoryStepExpression(int stepId, Date startAfter, Date startBefore)
049    {
050        _step = stepId;
051        _startBefore = startBefore;
052        _startAfter = startAfter;
053    }
054    
055    public String build()
056    {
057        StringBuilder sb = new StringBuilder("(oswf:historyStep/@oswf:stepId = ");
058        sb.append(_step);
059        
060        if (_startAfter != null)
061        {
062            sb.append(" and oswf:historyStep/@oswf:startDate >= xs:dateTime('" + FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").format(_startAfter) + "')");
063        }
064        
065        if (_startBefore != null)
066        {
067            sb.append(" and oswf:historyStep/@oswf:startDate <= xs:dateTime('" + FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSZZ").format(_startBefore) + "')");
068        }
069        sb.append(")");
070        return sb.toString();
071    }
072}