Search in sources :

Example 81 with InputStreamReader

use of java.io.InputStreamReader in project openhab1-addons by openhab.

the class SonanceBinding method execute.

/*
     * {@inheritDoc}
     */
@Override
protected void execute() {
    if (!bindingsExist()) {
        logger.debug("There is no existing Sonance binding configuration => refresh cycle aborted!");
        return;
    }
    logger.info("Refreshing all items");
    List<String> offlineEndPoints = new ArrayList<String>();
    for (SonanceBindingProvider provider : providers) {
        for (String itemName : provider.getItemNames()) {
            String group = provider.getGroup(itemName);
            String ip = provider.getIP(itemName);
            int port = provider.getPort(itemName);
            String key = ip + ":" + port;
            if (!offlineEndPoints.contains(key)) {
                try {
                    if (!socketCache.containsKey(key)) {
                        socketCache.put(key, new Socket(ip, port));
                        outputStreamCache.put(key, new DataOutputStream(socketCache.get(key).getOutputStream()));
                        bufferedReaderCache.put(key, new BufferedReader(new InputStreamReader(socketCache.get(key).getInputStream())));
                        logger.debug("New socket created ({}:{})", ip, port);
                    }
                    if (provider.isMute(itemName)) {
                        sendMuteCommand(itemName, SonanceConsts.MUTE_QUERY + group, outputStreamCache.get(key), bufferedReaderCache.get(key));
                    } else if (provider.isVolume(itemName)) {
                        sendVolumeCommand(itemName, SonanceConsts.VOLUME_QUERY + group, outputStreamCache.get(key), bufferedReaderCache.get(key));
                    } else if (provider.isPower(itemName)) {
                        sendPowerCommand(itemName, SonanceConsts.POWER_QUERY, outputStreamCache.get(key), bufferedReaderCache.get(key));
                    }
                } catch (UnknownHostException e) {
                    logger.error("UnknownHostException occured when connecting to amplifier {}:{}.", ip, port);
                } catch (IOException e) {
                    logger.debug("Amplifier ({},{}) is offline, status can't be updated at this moment.", ip, port);
                    try {
                        socketCache.get(key).close();
                    } catch (Exception ex) {
                    }
                    socketCache.remove(key);
                    outputStreamCache.remove(key);
                    bufferedReaderCache.remove(key);
                    // Stop trying to fetch other
                    offlineEndPoints.add(key);
                // values from this end
                // point until next execute
                // cycle
                }
            }
        }
    }
}
Also used : SonanceBindingProvider(org.openhab.binding.sonance.SonanceBindingProvider) InputStreamReader(java.io.InputStreamReader) UnknownHostException(java.net.UnknownHostException) DataOutputStream(java.io.DataOutputStream) ArrayList(java.util.ArrayList) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Socket(java.net.Socket) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 82 with InputStreamReader

use of java.io.InputStreamReader in project zipkin by openzipkin.

the class ExecJarRule method apply.

@Override
public Statement apply(Statement base, Description description) {
    return new Statement() {

        public void evaluate() throws Throwable {
            try {
                ProcessBuilder bootBuilder = new ProcessBuilder("java", "-jar", execJar);
                bootBuilder.environment().put("SERVER_PORT", String.valueOf(port()));
                bootBuilder.environment().putAll(environment);
                bootBuilder.redirectErrorStream(true);
                bootApp = bootBuilder.start();
                CountDownLatch startedOrCrashed = new CountDownLatch(1);
                Thread consoleReader = new Thread(() -> {
                    boolean foundStartMessage = false;
                    try (BufferedReader reader = new BufferedReader(new InputStreamReader(bootApp.getInputStream()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.indexOf("JVM running for") != -1) {
                                foundStartMessage = true;
                                startedOrCrashed.countDown();
                            }
                            console.add(line);
                        }
                    } catch (Exception e) {
                    } finally {
                        if (!foundStartMessage)
                            startedOrCrashed.countDown();
                    }
                });
                consoleReader.setDaemon(true);
                consoleReader.start();
                if (!startedOrCrashed.await(10, TimeUnit.SECONDS)) {
                    throw new AssumptionViolatedException("Took too long to start or crash");
                }
                base.evaluate();
            } finally {
                bootApp.destroy();
            }
        }
    };
}
Also used : InputStreamReader(java.io.InputStreamReader) AssumptionViolatedException(org.junit.AssumptionViolatedException) Statement(org.junit.runners.model.Statement) BufferedReader(java.io.BufferedReader) CountDownLatch(java.util.concurrent.CountDownLatch) AssumptionViolatedException(org.junit.AssumptionViolatedException) IOException(java.io.IOException)

Example 83 with InputStreamReader

use of java.io.InputStreamReader in project quasar by puniverse.

the class SimpleSuspendableClassifier method parse.

private static void parse(URL file, Set<String> set, Set<String> classSet) {
    try (InputStream is = file.openStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")))) {
        String line;
        for (int linenum = 1; (line = reader.readLine()) != null; linenum++) {
            final String s = line.trim();
            if (s.isEmpty())
                continue;
            if (s.charAt(0) == '#')
                continue;
            final int index = s.lastIndexOf('.');
            if (index <= 0) {
                System.err.println("Can't parse line " + linenum + " in " + file + ": " + line);
                continue;
            }
            final String className = s.substring(0, index).replace('.', '/');
            final String methodName = s.substring(index + 1);
            final String fullName = className + '.' + methodName;
            if (methodName.equals("*")) {
                if (classSet != null)
                    classSet.add(className);
            } else
                set.add(fullName);
        }
    } catch (IOException e) {
    // silently ignore
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 84 with InputStreamReader

use of java.io.InputStreamReader in project spaceships-demo by puniverse.

the class Spaceships method main.

/**
     * @param args the command line arguments
     */
public static void main(String[] args) throws Exception {
    System.out.println("COMPILER: " + System.getProperty("java.vm.name"));
    System.out.println("VERSION: " + System.getProperty("java.version"));
    System.out.println("OS: " + System.getProperty("os.name"));
    System.out.println("PROCESSORS: " + Runtime.getRuntime().availableProcessors());
    System.out.println();
    Properties props = new Properties();
    props.load(new InputStreamReader(ClassLoader.getSystemResourceAsStream("spaceships.properties")));
    Metrics.register("cpu", new CpuUsageGaugeSet());
    Metrics.register("memory", new MemoryUsageGaugeSet());
    int glxNode = args.length > 0 ? Integer.parseInt(args[0]) : -1;
    if (glxNode < 0)
        glxNode = Integer.parseInt(props.getProperty("galaxy.nodeId", "-1"));
    if (glxNode >= 0) {
        if (glxNode == 0)
            throw new IllegalArgumentException("Node cannot be 0. Reserved for Galaxy server.");
        System.out.println("Connecting to Galaxy cluster...");
        System.setProperty("co.paralleluniverse.flightRecorderDumpFile", "spaceships-" + glxNode + ".log");
        System.setProperty("galaxy.nodeId", Integer.toString(glxNode));
        System.setProperty("galaxy.port", props.getProperty("galaxy.port", Integer.toString(7050 + glxNode)));
        System.setProperty("galaxy.slave_port", props.getProperty("galaxy.port", Integer.toString(8050 + glxNode)));
        Grid.getInstance();
    }
    System.out.println("Initializing...");
    spaceships = new Spaceships(glxNode, props);
    System.out.println("Running...");
    spaceships.run();
    Thread.sleep(100000);
}
Also used : InputStreamReader(java.io.InputStreamReader) MemoryUsageGaugeSet(com.codahale.metrics.jvm.MemoryUsageGaugeSet) Properties(java.util.Properties) CpuUsageGaugeSet(co.paralleluniverse.common.monitoring.CpuUsageGaugeSet)

Example 85 with InputStreamReader

use of java.io.InputStreamReader in project weiciyuan by qii.

the class JavaHttpUtility method readResult.

private String readResult(HttpURLConnection urlConnection) throws WeiboException {
    InputStream is = null;
    BufferedReader buffer = null;
    GlobalContext globalContext = GlobalContext.getInstance();
    String errorStr = globalContext.getString(R.string.timeout);
    globalContext = null;
    try {
        is = urlConnection.getInputStream();
        String content_encode = urlConnection.getContentEncoding();
        if (!TextUtils.isEmpty(content_encode) && content_encode.equals("gzip")) {
            is = new GZIPInputStream(is);
        }
        buffer = new BufferedReader(new InputStreamReader(is));
        StringBuilder strBuilder = new StringBuilder();
        String line;
        while ((line = buffer.readLine()) != null) {
            strBuilder.append(line);
        }
        //            AppLogger.d("result=" + strBuilder.toString());
        return strBuilder.toString();
    } catch (IOException e) {
        e.printStackTrace();
        throw new WeiboException(errorStr, e);
    } finally {
        Utility.closeSilently(is);
        Utility.closeSilently(buffer);
        urlConnection.disconnect();
    }
}
Also used : GlobalContext(org.qii.weiciyuan.support.utils.GlobalContext) GZIPInputStream(java.util.zip.GZIPInputStream) WeiboException(org.qii.weiciyuan.support.error.WeiboException) InputStreamReader(java.io.InputStreamReader) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BufferedReader(java.io.BufferedReader) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException)

Aggregations

InputStreamReader (java.io.InputStreamReader)4861 BufferedReader (java.io.BufferedReader)3402 IOException (java.io.IOException)2108 InputStream (java.io.InputStream)1272 FileInputStream (java.io.FileInputStream)857 URL (java.net.URL)605 ArrayList (java.util.ArrayList)559 Reader (java.io.Reader)518 File (java.io.File)514 Test (org.junit.Test)451 HttpURLConnection (java.net.HttpURLConnection)290 ByteArrayInputStream (java.io.ByteArrayInputStream)282 OutputStreamWriter (java.io.OutputStreamWriter)241 FileNotFoundException (java.io.FileNotFoundException)240 URLConnection (java.net.URLConnection)227 HashMap (java.util.HashMap)192 Socket (java.net.Socket)178 OutputStream (java.io.OutputStream)175 StringWriter (java.io.StringWriter)148 BufferedWriter (java.io.BufferedWriter)138