001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 018package org.apache.commons.io.input; 019 020import java.io.IOException; 021import java.time.Duration; 022import java.time.Instant; 023 024import org.apache.commons.io.input.ObservableInputStream.Observer; 025 026/** 027 * An observer with timestamps. 028 * <p> 029 * For example: 030 * </p> 031 * 032 * <pre> 033 * final TimestampedObserver timetampedObserver = new TimestampedObserver(); 034 * try (final ObservableInputStream inputStream = new ObservableInputStream(...), 035 * timetampedObserver)) { 036 * ... 037 * } 038 * System.out.printf("IO duration: %s%n", timetampedObserver.getOpenToCloseDuration()); 039 * </pre> 040 * 041 * @since 2.9.0 042 */ 043public class TimestampedObserver extends Observer { 044 045 private volatile Instant closeInstant; 046 private final Instant openInstant = Instant.now(); 047 048 @Override 049 public void closed() throws IOException { 050 closeInstant = Instant.now(); 051 } 052 053 /** 054 * Gets the instant for when this instance was closed. 055 * 056 * @return the instant for when closed was called. 057 */ 058 public Instant getCloseInstant() { 059 return closeInstant; 060 } 061 062 /** 063 * Gets the Duration between creation and close. 064 * 065 * @return the Duration between creation and close. 066 */ 067 public Duration getOpenToCloseDuration() { 068 return Duration.between(openInstant, closeInstant); 069 } 070 071 /** 072 * Gets the Duration between creation and now. 073 * 074 * @return the Duration between creation and now. 075 */ 076 public Duration getOpenToNowDuration() { 077 return Duration.between(openInstant, Instant.now()); 078 } 079 080 /** 081 * Gets the instant for when this instance was created. 082 * 083 * @return the instant for when this instance was created. 084 */ 085 public Instant getOpenInstant() { 086 return openInstant; 087 } 088 089 @Override 090 public String toString() { 091 return "TimestampedObserver [openInstant=" + openInstant + ", closeInstant=" + closeInstant + "]"; 092 } 093 094}