001/**
002 * Copyright 2010-2014 The Kuali Foundation
003 *
004 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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.kuali.common.util.wait;
017
018import static com.google.common.base.Preconditions.checkState;
019import static java.lang.System.currentTimeMillis;
020import static org.apache.commons.lang3.StringUtils.leftPad;
021import static org.kuali.common.util.base.Threads.sleep;
022import static org.kuali.common.util.log.Loggers.newLogger;
023
024import org.kuali.common.util.FormatUtils;
025import org.kuali.common.util.condition.Condition;
026import org.slf4j.Logger;
027
028public class DefaultWaitService implements WaitService {
029
030        private static final Logger logger = newLogger();
031
032        @Override
033        public WaitResult wait(WaitContext context, Condition condition) {
034                long start = currentTimeMillis();
035                long timeout = start + context.getTimeoutMillis();
036                sleep(context.getInitialPauseMillis());
037                while (!condition.isTrue()) {
038                        long now = currentTimeMillis();
039                        checkState(now <= timeout, "Timed out waiting");
040                        String elapsed = leftPad(FormatUtils.getTime(now - start), 7, " ");
041                        String timeoutString = leftPad(FormatUtils.getTime(timeout - now), 7, " ");
042                        logger.info("[elapsed: {}  timeout: {}]", elapsed, timeoutString);
043                        sleep(context.getSleepMillis());
044                }
045                return WaitResult.create(start, currentTimeMillis());
046        }
047
048}