pax_global_header00006660000000000000000000000064121757402530014520gustar00rootroot0000000000000052 comment=52f006eb2f79ccdda35a12493201f9af07506753 com.hypirion.io-0.3.1/000077500000000000000000000000001217574025300145455ustar00rootroot00000000000000com.hypirion.io-0.3.1/.gitignore000066400000000000000000000002051217574025300165320ustar00rootroot00000000000000/target /lib /classes /checkouts pom.xml pom.xml.asc *.jar *.class .lein-deps-sum .lein-failures .lein-plugins .lein-repl-history *~ com.hypirion.io-0.3.1/CHANGES.md000066400000000000000000000022721217574025300161420ustar00rootroot00000000000000# com.hypirion.io changelog ## 0.3.1 * Compiling the project with `lein javac` will now produce `1.6`-compliant bytecode. ## 0.3.0 [`docs`][0.3.0-docs] [`tag`][0.3.0-tag] * Add ConsoleUtils, which makes it possible to manipulate console echoing and reading passwords. * Add SignalIntercepting as part of the library. ## 0.2.0 [`docs`][0.2.0-docs] [`tag`][0.2.0-tag] * Pipe and ClosingPipe now includes proper documentation. ## 0.2.0-RC1 [`tag`][0.2.0-RC1-tag] * Pipe and ClosingPipe is now a part of the library. `(undocumented)` * RevivableInputStream will now perform buffered reads, not unbuffered. `(undocumented)` ## 0.1.0 [`docs`][0.1.0-docs] [`tag`][0.1.0-tag] * RevivableInputStream is now a part of the library. [0.3.0-tag]: https://github.com/hyPiRion/com.hypirion.io/tree/0.3.0 [0.3.0-docs]: http://hypirion.github.com/com.hypirion.io/0.3.0/ [0.2.0-tag]: https://github.com/hyPiRion/com.hypirion.io/tree/0.2.0 [0.2.0-docs]: http://hypirion.github.com/com.hypirion.io/0.2.0/ [0.2.0-RC1-tag]: https://github.com/hyPiRion/com.hypirion.io/tree/0.2.0-RC1 [0.1.0-tag]: https://github.com/hyPiRion/com.hypirion.io/tree/0.1.0 [0.1.0-docs]: http://hypirion.github.com/com.hypirion.io/0.1.0/ com.hypirion.io-0.3.1/LICENSE000066400000000000000000000263721217574025300155640ustar00rootroot00000000000000Eclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 1. DEFINITIONS "Contribution" means: a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and b) in the case of each subsequent Contributor: i) changes to the Program, and ii) additions to the Program; where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. "Contributor" means any person or entity that distributes the Program. "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. "Program" means the Contributions distributed in accordance with this Agreement. "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 2. GRANT OF RIGHTS a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 3. REQUIREMENTS A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: a) it complies with the terms and conditions of this Agreement; and b) its license agreement: i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. When the Program is made available in source code form: a) it must be made available under this Agreement; and b) a copy of this Agreement must be included with each copy of the Program. Contributors may not remove or alter any copyright notices contained within the Program. Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 4. COMMERCIAL DISTRIBUTION Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 5. NO WARRANTY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 6. DISCLAIMER OF LIABILITY EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 7. GENERAL If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. com.hypirion.io-0.3.1/README.md000066400000000000000000000013511217574025300160240ustar00rootroot00000000000000# com.hypirion.io Java library which contain I/O classes for those with specific needs. For the API documentation, see . ## Usage Add a dependency to your this in your Clojure/Java/Scala app, and off we go. For Clojure, this can be done through ```clj [com.hypirion/io "0.3.1"] ``` or, for Maven: ``` com.hypirion io 0.3.1 ``` also ensure that Clojars is added to your repositories: ``` clojars http://clojars.org/repo/ ``` ## License Copyright © 2013 Jean Niklas L'orange Distributed under the Eclipse Public License, the same as Clojure. com.hypirion.io-0.3.1/project.clj000066400000000000000000000011361217574025300167060ustar00rootroot00000000000000(defproject com.hypirion/io "0.3.1" :description "I/O classes in Java for those with specific needs." :url "https://github.com/hyPiRion/com.hypirion.io" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :source-paths [] :java-source-paths ["src"] :javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"] :deploy-branches ["stable"] :profiles {:dev {:plugins [[lein-shell "0.2.0"]] :aliases {"javadoc" ["shell" "javadoc" "-d" "0.4.0-SNAPSHOT" "-sourcepath" "src/" "com.hypirion.io"]}}}) com.hypirion.io-0.3.1/src/000077500000000000000000000000001217574025300153345ustar00rootroot00000000000000com.hypirion.io-0.3.1/src/com/000077500000000000000000000000001217574025300161125ustar00rootroot00000000000000com.hypirion.io-0.3.1/src/com/hypirion/000077500000000000000000000000001217574025300177535ustar00rootroot00000000000000com.hypirion.io-0.3.1/src/com/hypirion/io/000077500000000000000000000000001217574025300203625ustar00rootroot00000000000000com.hypirion.io-0.3.1/src/com/hypirion/io/ClosingPipe.java000066400000000000000000000076661217574025300234600ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.io.Reader; import java.io.Closeable; import java.io.IOException; /** * A ClosingPipe is a link between an input stream and an output stream or a * reader or writer: The pipe, once started, will asynchronously redirect all * data received from the input source to the output source until it is paused, * stopped or the input source is empty. When the input source has been closed, * or the pipe has been stopped, a ClosingPipe will close the output source * afterwards. *

* Common usage of pipes includes asynchronous zipping of data from two data * sources, redirecting output and input to subprocesses and for loggers you * want to just pipe from and input source. * * @author Jean Niklas L'orange * @since com.hypirion.io 0.2.0 */ public class ClosingPipe extends Pipe { protected final Thread closer; /** * Creates a new closing pipe, which redirects data from the stream * in to the stream out once started. * * @param in the input stream to read from. * @param out the output stream to write out to. */ public ClosingPipe(InputStream in, OutputStream out) { this(in, out, DEFAULT_BUFFER_SIZE); } /** * Creates a new closing pipe with buffer size bufsize, which * redirects data from the stream in to the stream * out once started. * * @param in the input stream to read from. * @param out the output stream to write out to. * @param bufsize the buffer size of the pipe. */ public ClosingPipe(InputStream in, OutputStream out, int bufsize) { super(in, out, bufsize); closer = setupCloser(out); } /** * Creates a new closing pipe, which redirects data from the reader * in to the writer out once started. * * @param in the reader to read from. * @param out the writer to write out to. */ public ClosingPipe(Reader in, Writer out) { this(in, out, DEFAULT_BUFFER_SIZE); } /** * Creates a new closing pipe with buffer size bufsize, which * redirects data from the reader in to the writer * out once started. * * @param in the reader to read from. * @param out the writer to write out to. * @param bufsize the buffer size of the pipe. */ public ClosingPipe(Reader in, Writer out, int bufsize) { super(in, out, bufsize); closer = setupCloser(out); } private Thread setupCloser(Closeable out) { Runnable pt = new OutCloser(out); Thread closer = new Thread(pt); closer.setName(String.format("ClosingPipeCloser %d", this.hashCode())); closer.setDaemon(true); closer.start(); return closer; } private class OutCloser implements Runnable { private final Closeable out; public OutCloser(Closeable out) { this.out = out; } @Override public void run() { try { ClosingPipe.this.join(); out.close(); } catch (InterruptedException ie) { run(); // We're not giving up that easily. } catch (IOException ioe) { // The closable is somehow broken, leave it be. } } } } com.hypirion.io-0.3.1/src/com/hypirion/io/ConsoleUtils.java000066400000000000000000000112331217574025300236500ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import java.io.Console; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * The ConsoleUtils class is a static collection of methods used to modify or * use the console in rather unconventional ways. It is mainly a way to set on * and off echoing in the console, either manually or through password reading * from an arbitrary InputStream. * * @author Jean Niklas L'orange * @see java.io.Console * @since com.hypirion.io 0.3.0 */ public final class ConsoleUtils { /** * A static method which peeks into the {@link java.io.Console} class and * manually turns on or off echoing in the given console. * * @param on whether to set echoing on or off. * * @exception NoSuchMethodException if Java's own console class have no * private method named "echo". * @exception NoSuchFieldException if Java's own console class have no * private field named "echoOff". * @exception InvocationTargetException if Java's own console class have a * private method named "echo", but that this method tries to invoke that * method erroneously. * @exception IllegalAccessException if the access restrictions prohibits * this method from modifying and using private methods in Java's own * console class. */ public static synchronized boolean setEcho(boolean on) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException { Class params[] = new Class[1]; params[0] = Boolean.TYPE; Method echo = Console.class.getDeclaredMethod("echo", params); echo.setAccessible(true); boolean res = (Boolean) echo.invoke(null, on); Field echoOff = Console.class.getDeclaredField("echoOff"); echoOff.setAccessible(true); echoOff.set(null, res); return res; } /** * A static method which will read from a given InputStream while it turns * echo off in the JVM console. Works just as {@link * java.io.Console#readPassword}. * * @param is the InputStream to read from. * * @exception NoSuchMethodException if Java's own console class have no * private method named "echo". * @exception NoSuchFieldException if Java's own console class have no * private field named "echoOff". * @exception InvocationTargetException if Java's own console class have a * private method named "echo", but that this method tries to invoke that * method erroneously. * @exception IllegalAccessException if the access restrictions prohibits * {@link #setEcho(boolean)} from modifying and using private methods in * Java's own console class. * @exception IOException if the given InputStream throws an * IOException. */ public static char[] readPassword(InputStream is) throws NoSuchMethodException, IllegalAccessException, NoSuchFieldException, InvocationTargetException, IOException { try { synchronized(is) { setEcho(false); InputStreamReader isr = new InputStreamReader(is); char[] buf = new char[32]; int len = 0; loop: while (true) { int c = isr.read(); switch (c) { case -1: case '\n': break loop; case '\r': continue; } buf[len] = (char) c; len++; if (len == buf.length) { char[] fresh = new char[2*len]; System.arraycopy(buf, 0, fresh, 0, len); buf = fresh; } } char[] out = new char[len]; System.arraycopy(buf, 0, out, 0, len); return out; } } finally { setEcho(true); } } } com.hypirion.io-0.3.1/src/com/hypirion/io/Pipe.java000066400000000000000000000221101217574025300221160ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.Writer; import java.io.Reader; /** * A Pipe is a link between an input stream and an output stream or a reader or * writer: The pipe, once started, will asynchronously redirect all data * received from the input source to the output source until it is paused, * stopped or the input source is empty. *

* Common usage of pipes includes asynchronous zipping of data from two data * sources, redirecting output and input to subprocesses and for loggers you * want to just pipe from and input source. * * @author Jean Niklas L'orange * @since com.hypirion.io 0.2.0 */ public class Pipe { /** * The default size of a pipe's buffer. * @since com.hypirion.io 0.2.0 */ public static final int DEFAULT_BUFFER_SIZE = 1024; private final Thread pumper; private final Object lock; private volatile boolean currentlyRunning, stopped; /** * Creates a new pipe, which redirects data from the stream in * to the stream out once started. * * @param in the input stream to read from. * @param out the output stream to write out to. */ public Pipe(InputStream in, OutputStream out) { this(in, out, DEFAULT_BUFFER_SIZE); } /** * Creates a new pipe with buffer size bufsize, which redirects * data from the stream in to the stream out once * started. * * @param in the input stream to read from. * @param out the output stream to write out to. * @param bufsize the buffer size of the pipe. */ public Pipe(InputStream in, OutputStream out, int bufsize) { Runnable pt = new PipeOutputStream(in, out, bufsize); lock = new Object(); currentlyRunning = false; stopped = false; pumper = new Thread(pt); pumper.setName(String.format("PipeThread %d", this.hashCode())); pumper.setDaemon(true); pumper.start(); } /** * Creates a new pipe, which redirects data from the reader in * to the writer out once started. * * @param in the reader to read from. * @param out the writer to write out to. */ public Pipe(Reader in, Writer out) { this(in, out, DEFAULT_BUFFER_SIZE); } /** * Creates a new pipe with buffer size bufsize, which redirects * data from the reader in to the writer out once * started. * * @param in the reader to read from. * @param out the writer to write out to. * @param bufsize the buffer size of the pipe. */ public Pipe(Reader in, Writer out, int bufsize) { Runnable pt = new PipeWriter(in, out, bufsize); lock = new Object(); currentlyRunning = false; stopped = false; pumper = new Thread(pt); pumper.setName(String.format("PipeThread %d", this.hashCode())); pumper.setDaemon(true); pumper.start(); } /** * Waits for this pipe to finish piping. This happens when this pipe is * stopped and the last blocking read has finished. * * @exception InterruptedException if this thread is interrupted while * waiting. * * @see #stop() * @see #stop(boolean) */ public void join() throws InterruptedException { pumper.join(); } /** * Starts up this pipe. If this pipe has not yet been started or has been * paused, this method will (re)start the pipe. When this pipe is stopped, * this method will do nothing. */ public synchronized void start() { if (!stopped) { synchronized (lock) { currentlyRunning = true; lock.notify(); // Wake up the pumper if it's waiting. } } } /** * Pauses this pipe. Will block until the current blocking read by this pipe * has finished, regardless of whether this pipe has been stopped or not. If * this pipe has already been paused or stopped, and there is no blocking * read waiting, will immediatly return. * * @exception InterruptedException if this thread is interrupted while * waiting. * * @see #pause(boolean) */ public synchronized void pause() throws InterruptedException { pause(true); } /** * Pauses this pipe. If block is true, will wait until the * current blocking read by this pipe has finished. Will otherwise notify * this pipe and return immediately. * * @param block whether to wait for the blocking read (if any) or not. * * @exception InterruptedException if this thread is interrupted while * waiting. */ public synchronized void pause(boolean block) throws InterruptedException { if (!stopped) { synchronized (lock) { currentlyRunning = false; lock.notify(); if (block) { lock.wait(); // Wait for signal from pumper, which will start after we // release the lock } } } else if (block) { join(); } } /** * Stops this pipe. Will wait until the last blocking read has finished. * * @exception InterruptedException if this thread is interrupted while * waiting. * * @see #stop(boolean) */ public synchronized void stop() throws InterruptedException { stop(true); } /** * Stops this pipe. Will wait until the last blocking read has finished. If * block is true, will wait until the current blocking read by * this pipe has finished. Will otherwise notify this pipe and return * immediately. * * @param block whether to wait for the blocking read (if any) or not. * * @exception InterruptedException if this thread is interrupted while * waiting. */ public synchronized void stop(boolean block) throws InterruptedException { if (!stopped) { synchronized (lock) { currentlyRunning = false; stopped = true; lock.notify(); } } if (block) { join(); } } private class PipeOutputStream implements Runnable { private final byte[] data; private final InputStream in; private final OutputStream out; public PipeOutputStream(InputStream in, OutputStream out, int bufsize) { data = new byte[bufsize]; this.in = in; this.out = out; } @Override public void run() { try { outer: while (true) { synchronized (lock) { while (!currentlyRunning) { if (stopped) { break outer; } lock.wait(); lock.notify(); } } int count = in.read(data); if (count < 0) { break; } out.write(data, 0, count); out.flush(); } } catch (Exception e) { // Die silently for now. } } } private class PipeWriter implements Runnable { private final char[] data; private final Reader in; private final Writer out; public PipeWriter(Reader in, Writer out, int bufsize) { data = new char[bufsize]; this.in = in; this.out = out; } @Override public void run() { try { outer: while (true) { synchronized (lock) { while (!currentlyRunning) { if (stopped) { break outer; } lock.wait(); lock.notify(); } } int count = in.read(data); if (count < 0) { break; } out.write(data, 0, count); out.flush(); } } catch (Exception e) { // Die silently for now. } } } } com.hypirion.io-0.3.1/src/com/hypirion/io/RevivableInputStream.java000066400000000000000000000211211217574025300253350ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import java.io.InputStream; import java.io.IOException; import java.io.InterruptedIOException; /** * A revivable input stream is an unbuffered input stream wrapping another input * stream. Its primary feature is that it allows to "kill" blocking * .read calls by calling .kill. Reading from the * stream can be resumed by calling .resurrect. *

* The common use for this is to avoid closing an input stream, while still be * able to cancel a blocking .read where you must use an input * stream. This is useful if you need to send a message to the thread which * attempts to read from the input stream. * * @author Jean Niklas L'orange * @since com.hypirion.io 0.1.0 */ public class RevivableInputStream extends InputStream { private InputStream in; private volatile boolean killed; private volatile boolean streamClosed; private volatile int requestedBytes; private volatile byte[] data; private volatile boolean requestData; private final Object dataLock; private volatile boolean threadCrashed; private volatile IOException threadException; private final ThreadReader reader; private final Thread readerThread; /** * Creates a new RevivableInputStream which wraps * in, giving it power to be killed and resurrected. */ public RevivableInputStream(InputStream in) { this.in = in; killed = false; streamClosed = false; requestData = true; dataLock = new Object(); threadCrashed = false; threadException = null; requestedBytes = -1; data = null; reader = new ThreadReader(); readerThread = new Thread(reader); readerThread.setDaemon(true); readerThread.setName("RevivableReader " + in.hashCode()); readerThread.start(); while (requestData) { Thread.yield(); // ensure no deadlock by waiting for the reader to get into its // correct state } } /** * Returns the number of bytes than can be read from this input stream * without blocking. * * Will as of now return 0. * * @return 0 */ public synchronized int available() { return 0; } /** * Closes this revivable input stream and the underlying input stream, and * releases any with system resources (threads, memory) associated with this * stream. * * @exception IOException if the underlying InputStream throws * an IOException. */ public synchronized void close() throws IOException { synchronized (dataLock) { in.close(); dataLock.notifyAll(); } } /** * Reads the next byte of data from this revivable input stream. The value * byte is returned as an int in the range 0 to * 255. This method blocks until no data is available, the end * of the stream is detected, an exception is thrown or if the reviable * input stream is (potentially temporarily) killed. * * @return the next byte of data, or -1 if the end of the * stream is reached or the stream is killed. * @exception IOException if the underlying InputStream throws * an IOException when attempted to read. This exception will * be thrown every time read is called until the stream is closed. */ public synchronized int read() throws IOException { byte[] b = new byte[1]; int count = 0; do { count = read(b); } while (count == 0); if (count == -1){ return -1; } else { return b[0]; } } public synchronized int read(byte[] b, int off, int len) throws IOException { synchronized (dataLock) { if (data == null) { requestedBytes = len; requestData = true; dataLock.notifyAll(); } try { while (data == null && !killed && !streamClosed && !threadCrashed) { dataLock.wait(); } } catch (InterruptedException ie) { throw new InterruptedIOException(); } if (streamClosed) return -1; if (threadCrashed) throw threadException; if (killed) return -1; // data must be non-null here due to dataLock's critical section. int n = data.length; if (n < len) { int totRead = n; System.arraycopy(data, 0, b, off, n); data = null; // In case we can read additional data without blocking int additional = Math.min(in.available(), len - n); if (additional > 0) { additional = in.read(b, off + n, additional); // ^ sanity check } totRead += additional; return totRead; } else if (n > len) { System.arraycopy(data, 0, b, off, len); int diff = n - len; byte[] newData = new byte[diff]; System.arraycopy(data, len, newData, 0, diff); data = newData; return len; } else { // here n == len System.arraycopy(data, 0, b, off, len); data = null; return len; } } } /** * Kills this revivable input stream. Makes current and future read calls * immediately return -1. The input stream may be revived through * {@link #resurrect()}. If this revivable input stream is already killed, * this method does nothing. * * @see #resurrect() */ public void kill() { synchronized (dataLock) { killed = true; dataLock.notifyAll(); } } /** * Resurrects a killed revivable input stream. This makes it possible to * read from this input stream once again. If this revivable input stream is * not killed, this method does nothing. * * @see #kill() */ public synchronized void resurrect() { killed = false; } private class ThreadReader implements Runnable { @Override public void run() { while (true) { synchronized (dataLock) { requestData = false; dataLock.notifyAll(); try { while (!requestData) { dataLock.wait(); } } catch (InterruptedException ie) { threadCrashed = true; threadException = new InterruptedIOException(); // TODO: Use "real" exception return; } } // Data has been requested, create new array with data. try { byte[] buffer = new byte[requestedBytes]; int actualBytes = in.read(buffer); // <-- actual reading if (actualBytes == -1){ synchronized (dataLock){ streamClosed = true; dataLock.notifyAll(); return; } } byte[] actual = new byte[actualBytes]; System.arraycopy(buffer, 0, actual, 0, actualBytes); data = actual; } catch (IOException ioe) { synchronized (dataLock) { threadCrashed = true; threadException = ioe; // TODO: Proper wrapping here. dataLock.notifyAll(); return; } } } } } } com.hypirion.io-0.3.1/src/com/hypirion/io/SignalInterceptor.java000066400000000000000000000066671217574025300247000ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import java.util.concurrent.Callable; /** * The SignalInterceptor class is a static collection of methods used to * intercept POSIX signals before they are sent to their original signal * handlers. Signal interceptors may be chained: If one attach the handler * A to signal X, then attach the handler * B to X as well, then all raised signals of type * X will first call B, then A, then the * original handler. *

* Signal handlers are {@link java.util.concurrent.Callable}s, which return * booleans. If the signal handler returns true, the call chain * will continue. If the signal handler returns false or throws an * Exception, the call chain will stop (and no Exception will be thrown). If the * signal handler throws an Error, the Error will not be caught. * * @author Jean Niklas L'orange * @since com.hypirion.io 0.3.0 */ public class SignalInterceptor { /** * Registers the {@link java.util.concurrent.Callable} object to the POSIX * signal signame. The POSIX signal must be in upper case, * with the beginning SIG part omitted. *

* E.g. an interception to SIGINT be converted to the symbol * "INT". * * @param signame the POSIX signal name with SIG omitted. * @param fn the Callable to call. The Callable * should return either true or false. * @exception SignalInterceptorException if there is no signal with the name * signame, or if the JVM doesn't implement the most common JVM * signal handling facilities. */ public static void register(String signame, Callable fn) throws SignalInterceptorException { try { SignalInterceptorHelper.register(signame, fn); } catch (Throwable e) { // Catching Linkage errors etc. here throw new SignalInterceptorException(signame, e); } } /** * Registers the {@link java.util.concurrent.Callable} object to the POSIX * signal signame. If successful, will return true. If the * registering fails, returns false. The POSIX signal must be in upper case, * with the beginning SIG part omitted. *

* E.g. an interception to SIGINT be converted to the symbol * "INT". * * @param signame the POSIX signal name with SIG omitted. * @param fn the Callable to call. The Callable * should return either true or false. */ public static boolean tryRegister(String signame, Callable fn) { try { register(signame, fn); return true; } catch (SignalInterceptorException sie) { return false; } } } com.hypirion.io-0.3.1/src/com/hypirion/io/SignalInterceptorException.java000066400000000000000000000026501217574025300265430ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; /** * SignalInterceptorExceptions are thrown if the {@link * SignalInterceptor} class is unable to find the signal attempted to intercept, * or if the JVM doesn't implement the most common JVM signal handling * facilities. * * @author Jean Niklas L'orange * @since com.hypirion.io 0.3.0 */ public class SignalInterceptorException extends Exception { /** * The name of the signal attempted to intercept, with SIG * omitted. */ public final String signame; /** * Creates a new SignalInterceptorException where * signal is the attempted signal to intercept, with * cause as underlying reason for not being able to do so. */ public SignalInterceptorException(String signal, Throwable cause) { super(String.format("Unable to register for SIG%s", signal), cause); signame = signal; } } com.hypirion.io-0.3.1/src/com/hypirion/io/SignalInterceptorHelper.java000066400000000000000000000032051217574025300260210ustar00rootroot00000000000000/* * Copyright (c) 2013 Jean Niklas L'orange. All rights reserved. * * The use and distribution terms for this software are covered by the * Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) * which can be found in the file LICENSE at the root of this distribution. * * By using this software in any fashion, you are agreeing to be bound by * the terms of this license. * * You must not remove this notice, or any other, from this software. */ package com.hypirion.io; import sun.misc.Signal; import sun.misc.SignalHandler; import java.util.HashMap; import java.util.concurrent.Callable; class SignalInterceptorHelper { static void register(String signame, Callable fn) { Signal sig = new Signal(signame); WrappedCallable newHandler = new WrappedCallable(fn); SignalHandler oldHandler = Signal.handle(sig, newHandler); newHandler.attachOld(oldHandler); } private static class WrappedCallable implements SignalHandler { private Callable fn; private SignalHandler oldHandler; public WrappedCallable(Callable fn) { this.fn = fn; this.oldHandler = null; } public void attachOld(SignalHandler oldHandler) { this.oldHandler = oldHandler; } public void handle(Signal sig) { boolean cont = true; try { cont = (Boolean) fn.call(); } catch (Exception e) {} finally { if (cont && (oldHandler != null)) { oldHandler.handle(sig); } } } } }