Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

In this page you can find the example usage for java.io InputStreamReader read.

Prototype

public int read() throws IOException 

Source Link

Document

Reads a single character.

Usage

From source file:org.apache.synapse.core.axis2.MediatorDeployer.java

/**
 * This will be called when there is a change in the specified deployment
 * folder (in the axis2.xml) and this will load the relevant classes to the system and
 * register them with the MediatorFactoryFinder
 *
 * @param deploymentFileData - describes the updated file
 * @throws DeploymentException - in case an error on the deployment
 *///from  w  ww. j a v  a 2  s . c o  m
public void deploy(DeploymentFileData deploymentFileData) throws DeploymentException {

    log.info("Loading mediator from: " + deploymentFileData.getAbsolutePath());

    // get the context class loader for the later restore of the context class loader
    ClassLoader prevCl = Thread.currentThread().getContextClassLoader();

    try {

        DeploymentClassLoader urlCl = new DeploymentClassLoader(
                new URL[] { deploymentFileData.getFile().toURL() }, null, prevCl);
        Thread.currentThread().setContextClassLoader(urlCl);

        // MediatorFactory registration
        URL facURL = urlCl.findResource("META-INF/services/org.apache.synapse.config.xml.MediatorFactory");
        if (facURL != null) {
            InputStream facStream = facURL.openStream();
            InputStreamReader facreader = new InputStreamReader(facStream);

            StringBuffer facSB = new StringBuffer();
            int c;
            while ((c = facreader.read()) != -1) {
                facSB.append((char) c);
            }

            String[] facClassName = facSB.toString().split("\n");
            for (int i = 0; i < facClassName.length; i++) {
                log.info("Registering the Mediator factory: " + facClassName[i]);
                Class facClass = urlCl.loadClass(facClassName[i]);
                MediatorFactory facInst = (MediatorFactory) facClass.newInstance();
                MediatorFactoryFinder.getInstance().getFactoryMap().put(facInst.getTagQName(), facClass);
                log.info("Mediator loaded and registered for " + "the tag name: " + facInst.getTagQName());
            }
        } else {
            handleException("Unable to find the MediatorFactory implementation. "
                    + "Unable to register the MediatorFactory with the FactoryFinder");
        }

        // MediatorSerializer registration
        URL serURL = urlCl.findResource("META-INF/services/org.apache.synapse.config.xml.MediatorSerializer");
        if (serURL != null) {
            InputStream serStream = serURL.openStream();
            InputStreamReader serReader = new InputStreamReader(serStream);

            StringBuffer serSB = new StringBuffer();
            int c;
            while ((c = serReader.read()) != -1) {
                serSB.append((char) c);
            }

            String[] serClassName = serSB.toString().split("\n");
            for (int i = 0; i < serClassName.length; i++) {
                log.info("Registering the Mediator serializer: " + serClassName[i]);
                Class serClass = urlCl.loadClass(serClassName[i]);
                MediatorSerializer serInst = (MediatorSerializer) serClass.newInstance();
                MediatorSerializerFinder.getInstance().getSerializerMap().put(serInst.getMediatorClassName(),
                        serInst);
                log.info("Mediator loaded and registered for " + "the serialization as: "
                        + serInst.getMediatorClassName());
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Unable to find the MediatorSerializer implementation. "
                        + "Unable to register the MediatorSerializer with the SerializerFinder");
            }
        }

    } catch (IOException e) {
        handleException("I/O error in reading the mediator jar file", e);
    } catch (ClassNotFoundException e) {
        handleException("Unable to find the specified class on the path or in the jar file", e);
    } catch (IllegalAccessException e) {
        handleException("Unable to load the class from the jar", e);
    } catch (InstantiationException e) {
        handleException("Unable to instantiate the class specified", e);
    } finally {
        // restore the class loader back
        if (log.isDebugEnabled()) {
            log.debug("Restoring the context class loader to the original");
        }
        Thread.currentThread().setContextClassLoader(prevCl);
    }
}

From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java

private static String loadPomFromJar(final File file) {
    InputStream is = null;/* w w w.  ja  v  a2s . c  om*/
    InputStreamReader isr = null;
    try {
        ZipFile zip = new ZipFile(file);

        for (Enumeration e = zip.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();

            if (entry.getName().startsWith("META-INF/maven") && entry.getName().endsWith("pom.xml")) {
                is = zip.getInputStream(entry);
                isr = new InputStreamReader(is, "UTF-8");
                StringBuilder sb = new StringBuilder();
                for (int c = isr.read(); c != -1; c = isr.read()) {
                    sb.append((char) c);
                }
                return sb.toString();
            }
        }
    } catch (ZipException e) {
        log.error(e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage());
    } finally {
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }

    return null;
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("ftp")) {
        FTPClient client = null;/*from   www . ja v a 2s.  c  o m*/
        String host = url.getHost();

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);
        //               System.out.println( "Connected.");

        // After connection attempt, you should check the reply code to verify
        // success.
        int reply = client.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

        //               System.out.println( "Logging in ...");

        if (!client.login(username, password)) {
            //                  System.out.println( "Could not log in.");
            // TODO bring up login dialog?
            client.disconnect();

            throw new IOException("Could not login to FTP Server \"" + host + "\".");
        }

        //               System.out.println( "Logged in.");

        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.enterLocalPassiveMode();

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}

From source file:org.jboss.test.classloader.leak.test.ClassloaderLeakTestBase.java

private void makeWebRequest(String url, String responseContent) {
    HttpClient client = new HttpClient();
    GetMethod method = new GetMethod(url);
    int responseCode = 0;
    try {//from w  w  w.  j  a  va  2s. com
        responseCode = client.executeMethod(method);

        assertTrue("Get OK with url: " + url + " responseCode: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);

        InputStream rs = method.getResponseBodyAsStream();
        InputStreamReader reader = new InputStreamReader(rs);
        StringWriter writer = new StringWriter();
        int c;
        while ((c = reader.read()) != -1)
            writer.write(c);

        String rsp = writer.toString();

        assertTrue("Response contains " + responseContent, rsp.indexOf(responseContent) >= 0);
    } catch (IOException e) {
        e.printStackTrace();
        fail("HttpClient executeMethod fails." + e.toString());
    } finally {
        method.releaseConnection();
    }
}

From source file:com.esp8266.mkspiffs.ESP8266FS.java

private int listenOnProcess(String[] arguments) {
    try {/*from   www.  j a v a 2  s .co m*/
        final Process p = ProcessUtils.exec(arguments);
        Thread thread = new Thread() {
            public void run() {
                try {
                    InputStreamReader reader = new InputStreamReader(p.getInputStream());
                    int c;
                    while ((c = reader.read()) != -1)
                        System.out.print((char) c);
                    reader.close();

                    reader = new InputStreamReader(p.getErrorStream());
                    while ((c = reader.read()) != -1)
                        System.err.print((char) c);
                    reader.close();
                } catch (Exception e) {
                }
            }
        };
        thread.start();
        int res = p.waitFor();
        thread.join();
        return res;
    } catch (Exception e) {
        return -1;
    }
}

From source file:org.openhab.binding.neohub.internal.NeoHubConnector.java

/**
 * Sends the message over the network and provides the response to the
 * response handler./*from  w  w w  .j a v  a  2  s.  c  o  m*/
 * 
 * @param msg
 *            message to neohub
 * @param handler
 *            handler to process the response, may be <code>null</code>
 * @return result of handler or <code>null</code> if network problem
 *         occurred
 */
public <T> T sendMessage(final String msg, final ResponseHandler<T> handler) {
    final StringBuilder response = new StringBuilder();
    final Socket socket = new Socket();
    try {
        socket.connect(new InetSocketAddress(hostname, port), timeout);
        final InputStreamReader in = new InputStreamReader(socket.getInputStream(), US_ASCII);
        final OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), US_ASCII);
        logger.debug(">> {}", msg);
        out.write(msg);
        out.write(0); // NUL terminate the command string
        out.flush();

        int l;
        while ((l = in.read()) > 0) {// NUL termination & end of stream (-1)
            response.append((char) l);
        }
    } catch (final IOException e) {
        logger.error("Failed to connect to neohub [host '{}' port '{}' timeout '{}']",
                new Object[] { hostname, port, timeout });
        logger.debug("Failed to connect to neohub.", e);
        return null;
    } finally {
        IOUtils.closeQuietly(socket);
    }
    final String responseStr = response.toString();
    logger.debug("<< {}", responseStr);

    if (handler != null) {
        return handler.onResponse(responseStr);
    } else
        return null;
}

From source file:org.jboss.test.cluster.classloader.leak.test.ClassloaderLeakTestBase.java

/**
 * FIXME Comment this//from w w  w  . j ava  2 s .  com
 * 
 * @param client
 * @param method
 * @param url
 * @param responseContent
 */
private void checkWebRequest(HttpClient client, GetMethod method, String url, String responseContent) {
    int responseCode = 0;
    try {
        responseCode = client.executeMethod(method);

        assertTrue("Get OK with url: " + url + " responseCode: " + responseCode,
                responseCode == HttpURLConnection.HTTP_OK);

        InputStream rs = method.getResponseBodyAsStream();
        InputStreamReader reader = new InputStreamReader(rs);
        StringWriter writer = new StringWriter();
        int c;
        while ((c = reader.read()) != -1)
            writer.write(c);

        String rsp = writer.toString();

        assertTrue("Response contains " + responseContent, rsp.indexOf(responseContent) >= 0);
    } catch (IOException e) {
        e.printStackTrace();
        fail("HttpClient executeMethod fails." + e.toString());
    } finally {
        method.releaseConnection();
    }
}

From source file:be.ibridge.kettle.trans.step.textfileinput.TextFileInput.java

public static final String getLine(LogWriter log, InputStreamReader reader, String format)
        throws KettleFileException {
    StringBuffer line = new StringBuffer(256);
    int c = 0;// w w  w .j av  a  2s.c o m
    boolean mixedMode = format.equalsIgnoreCase("mixed"); // for a small performance optimization

    try {
        while (c >= 0) {
            c = reader.read();

            if (!mixedMode) { // no mixed mode
                if (c == '\n' || c == '\r') {
                    if (format.equalsIgnoreCase("DOS")) {
                        c = reader.read(); // skip \n and \r
                        if (c != '\r' && c != '\n') {
                            // make sure its really a linefeed or cariage return
                            // raise an error this is not a DOS file 
                            // so we have pulled a character from the next line
                            throw new KettleFileException(
                                    "DOS format was specified but only a single line feed character was found, not 2");
                        }
                    }
                    return line.toString();
                }
                if (c >= 0)
                    line.append((char) c);
            } else // in mixed mode we suppose the LF is the last char and CR is ignored
                   // not for MAC OS 9 but works for Mac OS X. Mac OS 9 can use UNIX-Format
            {
                if (c == '\n') {
                    return line.toString();
                } else if (c != '\r') {
                    if (c >= 0)
                        line.append((char) c);
                }
            }
        }
    } catch (KettleFileException e) {
        throw e;
    } catch (Exception e) {
        if (line.length() == 0) {
            log.logError("get line", "Exception reading line: " + e.toString());
            return null;
        }
        return line.toString();
    }
    if (line.length() > 0)
        return line.toString();

    return null;
}

From source file:org.opencastproject.manager.system.workflow.WorkflowManager.java

/**
 * Handles the new worklfow file./*  w w w  .j a  v  a 2  s  .  c om*/
 *
 * @param request
 * @param response
 * @throws TransformerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public void handleNewWorkflowFile(HttpServletRequest request, HttpServletResponse response)
        throws TransformerException, ParserConfigurationException, SAXException, IOException {

    File xmlWorkflowFile = new File(PluginManagerConstants.WORKFLOWS_PATH + "TMPfile.xml");

    int counter = 0;

    try {
        InputStreamReader inputStream = new InputStreamReader(request.getInputStream());
        FileOutputStream outputStream = new FileOutputStream(xmlWorkflowFile);

        int c = 0;

        while ((c = inputStream.read()) != -1) {
            outputStream.write(c);
            counter++;
        }

        inputStream.close();
        outputStream.close();
    } catch (FileNotFoundException e) {
        System.err.println("FileStreamsTest: " + e);
    } catch (IOException e) {
        System.err.println("FileStreamsTest: " + e);
    }

    if (counter == 0) {
        xmlWorkflowFile.delete();
        return;
    }

    String newXMLFile = stringValidator(request.getHeader("FileName"));
    File newXMLWorkflowFile = new File(PluginManagerConstants.WORKFLOWS_PATH + newXMLFile);
    newXMLWorkflowFile.delete();
    xmlWorkflowFile.renameTo(new File(PluginManagerConstants.WORKFLOWS_PATH + newXMLFile));
}

From source file:com.southernstorm.tvguide.TvChannelCache.java

private static String readLine(InputStreamReader reader) throws IOException {
    StringBuilder builder = new StringBuilder(1024);
    int ch;/* ww  w .  ja  v a  2  s  . c om*/
    while ((ch = reader.read()) != -1 && ch != '\n')
        builder.append((char) ch);
    if (ch == -1 && builder.length() == 0)
        return null;
    return builder.toString();
}