Example usage for java.io InputStream available

List of usage examples for java.io InputStream available

Introduction

In this page you can find the example usage for java.io InputStream available.

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking, which may be 0, or 0 when end of stream is detected.

Usage

From source file:com.jaspersoft.jasperserver.test.CoreDataCreateTestNG.java

private void createThemeFile(String filePath, InputStream fileInputStream) throws Exception {
    int length = fileInputStream.available();
    byte[] data = new byte[length];
    int off = 0;//from   w ww.  j a va  2  s  .  co  m
    while ((off += fileInputStream.read(data, off, length - off)) < length) {
    }
    ;

    String[] pathParts = filePath.split("/");
    Folder parentFolder = null;
    String baseFolderURI = "";
    for (int i = 0; i < pathParts.length - 1; i++) {
        if (parentFolder != null) {
            baseFolderURI = parentFolder.getURIString();
        }
        parentFolder = getOrCreateFolder(baseFolderURI, pathParts[i]);
    }

    String fileName = pathParts[pathParts.length - 1];
    FileResource fileResource = (FileResource) getRepositoryService().newResource(null, FileResource.class);
    fileResource.setName(fileName);
    fileResource.setLabel(fileName);
    fileResource.setParentFolder(parentFolder);
    Date now = new Date();
    fileResource.setCreationDate(now);
    fileResource.setUpdateDate(now);
    fileResource.setData(data);
    String type = (fileName.toUpperCase().endsWith(".CSS")) ? FileResource.TYPE_CSS : FileResource.TYPE_IMAGE;
    fileResource.setFileType(type);

    m_logger.info("createThemeFile() => creating file : " + fileResource.getURIString());
    getRepositoryService().saveResource(null, fileResource);
}

From source file:com.dreamlinx.automation.DINRelay.java

/**
 * This method runs the provided command in the current runtime environment
 * within the instance of this virtual machine.
 *
 * @param commandWithArgs Command and arguments.
 * @return Process//from   ww  w .j a v a 2s . c o  m
 * @throws IOException
 */
private void runCommand(String[] commandWithArgs) throws IOException {
    Process p = Runtime.getRuntime().exec(commandWithArgs);
    try {
        // read and close all streams to prevent open handles
        InputStream i = p.getInputStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        i = p.getErrorStream();
        while (i.available() > 0) {
            i.read();
        }
        i.close();
        p.getOutputStream().close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.appnexus.opensdk.MRAIDImplementation.java

String getMraidDotJS(Resources r) {
    InputStream ins = r.openRawResource(R.raw.mraid);
    try {/*from  w ww  .j av  a2s . c  om*/
        byte[] buffer = new byte[ins.available()];
        if (ins.read(buffer) > 0) {
            return new String(buffer, "UTF-8");
        }
    } catch (IOException e) {

    }
    return null;
}

From source file:li.klass.fhem.fhem.TelnetConnection.java

private String read(InputStream inputStream) throws IOException {
    waitForFilledStream(inputStream, 3000);

    StringBuilder buffer = new StringBuilder();
    while (inputStream.available() > 0 || waitForFilledStream(inputStream, 100)) {
        char readChar = (char) inputStream.read();
        buffer.append(readChar);// w  ww .ja va2  s . c  o m
    }
    return buffer.toString();
}

From source file:org.auraframework.integration.test.archetype.AuraArchetypeSimpleTestMANUAL.java

@Test
public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;//w  w  w.j  a v a2s.c o  m
    workspace = new File(IOUtil.newTempDir("archetype"));
    try {
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}

From source file:org.auraframework.archetype.AuraArchetypeSimpleTestMANUAL.java

public void testProjectCreation() throws Throwable {
    Process jettyProcess = null;//from   w  w w .  j  ava2 s. c o m
    workspace = new File(
            System.getProperty("java.io.tmpdir") + File.separator + getName() + System.currentTimeMillis());
    try {
        // create a workspace to place the project files in
        workspace.mkdirs();

        // generate a project from the archetype
        Process genProcess = startProcess(workspace,
                ImmutableList.of("mvn", "archetype:generate", "-DarchetypeRepository=" + archRepo,
                        "-DarchetypeCatalog=" + archCatalog, "-DarchetypeGroupId=" + archetype.groupId,
                        "-DarchetypeArtifactId=" + archetype.artifactId,
                        "-DarchetypeVersion=" + archetype.version, "-DgroupId=" + project.groupId,
                        "-DartifactId=" + project.artifactId, "-Dversion=" + project.version,
                        "-Dpackage=" + projectPackage, "-DinteractiveMode=false"));
        goldMavenOutput(genProcess, "-creation.txt", "Failed to generate artifact!");

        File projectDir = new File(workspace, project.artifactId);
        assertDirectory(projectDir);
        verifyGeneratedResources(projectDir);

        // build the new project
        Process buildProcess = startProcess(projectDir, ImmutableList.of("mvn", "install"));
        goldMavenOutput(buildProcess, "-install.txt", "Failed to build new project!");

        // get a free port for jetty
        ServerSocket socket = new ServerSocket(0);
        int jettyPort = socket.getLocalPort();
        socket.close();

        // start up jetty
        jettyProcess = startProcess(projectDir,
                ImmutableList.of("mvn", "jetty:run", "-Djetty.port=" + jettyPort));

        int status = 0;
        for (int i = 0; i < 30; i++) {
            try {
                HttpGet get = obtainGetMethod("/");
                HttpResponse response = perform(get);
                status = getStatusCode(response);
                get.releaseConnection();
                break;
            } catch (ConnectException ce) {
                // expected, before server is listening
                Thread.sleep(1000);
            }
        }
        assertEquals("Failed to connect to server", HttpStatus.SC_OK, status);

        verifyDefaultDocument();
        verifySampleComponents();
    } catch (Throwable t) {
        // if any errors in Jetty requests, let's print out the Jetty
        // console output for diag before killing the
        // test
        if (jettyProcess != null) {
            InputStream is = jettyProcess.getInputStream();
            int len = is.available();
            byte[] buf = new byte[len];
            is.read(buf);
            System.err.println(new String(buf));
        }
        throw t;
    } finally {
        // kill Jetty
        if (jettyProcess != null) {
            try {
                jettyProcess.exitValue();
            } catch (IllegalThreadStateException e) {
                jettyProcess.destroy();
            }
        }
        // cleanup generated workspace
        IOUtil.delete(workspace);
    }
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

private void encapsulate(String cover, String message, String output) throws IOException {
    try {/*from w  w  w.ja v  a2  s.  com*/
        String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "embed", "-a",
                "RandomLSB", "-cf", cover, "-mf", message, "-sf", output, "-C", "-E" };
        Process process = Runtime.getRuntime().exec(args);
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        byte b[] = new byte[inputStream.available()];
        inputStream.read(b, 0, b.length);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:algorithm.OpenStegoRandomLSBSteganography.java

private void encapsulateAndCompress(String cover, String message, String output) throws IOException {
    try {// w w w. j  a v a  2 s .c o m
        String[] args = new String[] { "java", "-jar", LIBRARY_DIRECTORY + "openstego.jar", "embed", "-a",
                "RandomLSB", "-cf", cover, "-mf", message, "-sf", output, "-c", "-E" };
        Process process = Runtime.getRuntime().exec(args);
        process.waitFor();
        InputStream inputStream = process.getInputStream();
        byte b[] = new byte[inputStream.available()];
        inputStream.read(b, 0, b.length);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.saarang.samples.apps.iosched.ui.ExpertsDirectoryActivity.java

public String loadJSONFromAsset() {
    String json = null;/*from w  ww  . j a  v  a 2 s. co m*/
    try {

        InputStream is = getAssets().open("sponsors.json");

        int size = is.available();

        byte[] buffer = new byte[size];

        is.read(buffer);

        is.close();

        json = new String(buffer, "UTF-8");

    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;

}

From source file:edu.smu.tspell.wordnet.impl.RandomAccessReader.java

/**
 * Constructs an instance of this class, specifying the file that is to
 * be read.//  ww w. j  a  v a  2 s. co m
 * 
 * @param  file File that is to be read.
 * @throws FileNotFoundException The specified file does not exist.
 */
protected RandomAccessReader(String name) throws IOException {
    super();
    InputStream stream = getClass().getResourceAsStream(name);
    if (stream == null) {
        throw new IOException("Cannot open resource: " + name);
    }
    fileSize = stream.available();
    byte[] buffer = IOUtils.toByteArray(stream);
    int read = buffer.length;
    if (read != fileSize) {
        throw new IOException("Unsuccessful read from: " + name + " " + read + " instead of " + fileSize);
    }
    accessor = ByteBuffer.wrap(buffer);
    filePointer = accessor.position();
    stream.close();
}