| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.s9api; |
| 9 | |
| 10 | import java.util.ArrayList; |
| 11 | import java.util.List; |
| 12 | import java.util.function.Consumer; |
| 13 | |
| 14 | /** |
| 15 | * A helper class for implementing the {@link Destination} interface} |
| 16 | */ |
| 17 | public class DestinationHelper { |
| 18 | |
| 19 | private Destination helpee; |
| 20 | |
| 21 | private List<Action> listeners = new ArrayList<>(); |
| 22 | |
| 23 | public DestinationHelper(Destination helpee) { |
| 24 | this.helpee = helpee; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Register a listener to be notified when this destination is closed |
| 29 | * @param listener an object to be notified when writing to the destination |
| 30 | * is successfully completed |
| 31 | */ |
| 32 | |
| 33 | final public void onClose(Action listener) { |
| 34 | listeners.add(listener); |
| 35 | } |
| 36 | |
| 37 | /** |
| 38 | * Close the destination and notify all registered listeners that it has been closed. |
| 39 | * This method is intended for internal use by Saxon. The method first calls {@code close} |
| 40 | * to close the destination, then it calls {@link Consumer#accept} on each of the |
| 41 | * listeners in turn to notify the fact that it has been closed. |
| 42 | * @throws SaxonApiException if the close() method throws {@code SaxonApiException}. |
| 43 | */ |
| 44 | |
| 45 | public void closeAndNotify() throws SaxonApiException { |
| 46 | helpee.close(); |
| 47 | for (Action action : listeners) { |
| 48 | action.act(); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | public List<Action> getListeners() { |
| 53 | return listeners; |
| 54 | } |
| 55 | |
| 56 | |
| 57 | } |
| 58 |