| 1 | /********************************************************************** |
| 2 | * Copyright (c) 2014 Wind River Systems, Inc. and others |
| 3 | * |
| 4 | * All rights reserved. This program and the accompanying materials are |
| 5 | * made available under the terms of the Eclipse Public License v1.0 which |
| 6 | * accompanies this distribution, and is available at |
| 7 | * http://www.eclipse.org/legal/epl-v10.html |
| 8 | * |
| 9 | * Contributors: |
| 10 | * Markus Schorn - Initial API and implementation |
| 11 | **********************************************************************/ |
| 12 | package org.eclipse.tracecompass.internal.lttng2.control.ui.views.remote; |
| 13 | |
| 14 | import java.io.IOException; |
| 15 | import java.io.InputStream; |
| 16 | import java.io.InputStreamReader; |
| 17 | |
| 18 | import org.eclipse.core.runtime.IProgressMonitor; |
| 19 | import org.eclipse.tracecompass.internal.lttng2.control.ui.Activator; |
| 20 | |
| 21 | class InputReader { |
| 22 | private static final int JOIN_TIMEOUT = 300; |
| 23 | private static final int BYTES_PER_KB = 1024; |
| 24 | private final InputStreamReader fReader; |
| 25 | private final Thread fThread; |
| 26 | private final StringBuilder fResult; |
| 27 | private volatile boolean fDone; |
| 28 | |
| 29 | public InputReader(InputStream inputStream) { |
| 30 | fResult = new StringBuilder(); |
| 31 | fReader = new InputStreamReader(inputStream); |
| 32 | fThread = new Thread() { |
| 33 | @Override |
| 34 | public void run() { |
| 35 | final char[] buffer = new char[BYTES_PER_KB]; |
| 36 | try { |
| 37 | int read = fReader.read(buffer); |
| 38 | while (!fDone && (read) > 0) { |
| 39 | fResult.append(buffer, 0, read); |
| 40 | read = fReader.read(buffer); |
| 41 | } |
| 42 | } catch (IOException e) { |
| 43 | Activator.getDefault().logError(e.getMessage(), e); |
| 44 | } |
| 45 | } |
| 46 | }; |
| 47 | fThread.start(); |
| 48 | } |
| 49 | |
| 50 | public void waitFor(IProgressMonitor monitor) throws InterruptedException { |
| 51 | while (fThread.isAlive() && (monitor == null || !monitor.isCanceled())) { |
| 52 | fThread.join(JOIN_TIMEOUT); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | public void stop() { |
| 57 | fDone = true; |
| 58 | fThread.interrupt(); |
| 59 | } |
| 60 | |
| 61 | @Override |
| 62 | public String toString() { |
| 63 | return fResult.toString(); |
| 64 | } |
| 65 | |
| 66 | } |