Example usage for java.io BufferedInputStream available

List of usage examples for java.io BufferedInputStream available

Introduction

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

Prototype

public synchronized 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 by the next invocation of a method for this input stream.

Usage

From source file:org.apache.hadoop.hbase.master.GroupAssignmentManager.java

private static boolean readConfig() {
    try {/* ww w  . jav a  2 s . co  m*/

        FSDataInputStream input = null;
        try {
            input = master.getMasterFileSystem().getFileSystem()
                    .open(new Path(FSUtils.getRootDir(conf), "groupinformation.conf"));
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (input != null) {
            BufferedInputStream binput = new BufferedInputStream(input);
            int size = binput.available();
            byte[] result = new byte[size];

            binput.read(result);
            String groups = Bytes.toString(result);
            String[] grouplines = groups.split(":");
            binput.close();
            System.out.println("config is" + Bytes.toString(result));

            for (String line : grouplines) {
                if (line == null || line.length() <= 0)
                    continue;
                String[] serverlines = line.split(";");

                // System.out.println("Group" + serverlines[0]);
                String groupName = serverlines[0];
                HashSet<String> set = new HashSet<String>();
                String groupDifConfigV = serverlines[1];
                try {
                    groupDifConf.put(groupName, Boolean.parseBoolean(groupDifConfigV));
                } catch (Exception e) {
                    groupDifConf.put(groupName, false);
                    e.printStackTrace();
                }
                for (int i = 2; i < serverlines.length; i++) {
                    set.add(serverlines[i]);
                }
                groupServersString.put(groupName, set);
            }
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block

        e.printStackTrace();
        if (groupServersString.get(DEFAULT_GROUP) == null) {
            groupServersString.put(DEFAULT_GROUP, new HashSet<String>());
            LOG.error("there is no server in group 0 ");
            return false;
        }

    }
    if (groupServersString.get(DEFAULT_GROUP) == null) {
        groupServersString.put(DEFAULT_GROUP, new HashSet<String>());
        LOG.error("there is no server in group 0 ");
        return false;
    }
    return true;

}

From source file:net.tirasa.hct.cocoon.sax.HippoRepositoryReader.java

@Override
public void execute() {
    if (this.uuid == null) {
        throw new IllegalArgumentException(getClass().getSimpleName() + " wasn't able to read from given URL.");
    }//  w ww . ja v  a  2 s. c o m

    final HCTConnManager connManager = HCTConnManager.getBinaryInstance();
    BufferedInputStream repositoryIS = null;
    try {
        final Node node = connManager.getSession().getNodeByIdentifier(this.uuid);
        this.contentType = node.getProperty(ResourceUtils.DEFAULT_BINARY_MIME_TYPE_PROP_NAME).getString();

        repositoryIS = new BufferedInputStream(
                node.getProperty(ResourceUtils.DEFAULT_BINARY_DATA_PROP_NAME).getBinary().getStream());
        final byte[] buffer = new byte[1024];
        while (repositoryIS.available() != 0) {
            final int len = repositoryIS.read(buffer);
            this.outputStream.write(buffer, 0, len);
        }
    } catch (Exception e) {
        throw new ProcessingException("While reading node", e);
    } finally {
        IOUtils.closeQuietly(repositoryIS);
        connManager.logout();
    }
}

From source file:es.mityc.firmaJava.configuracion.Configuracion.java

/**
  * Este mtodo guarda la configuracin en el fichero SignXML.properties
  * @throws IOException /*from w w w .  j  a v  a2s  . com*/
  */
public void guardarConfiguracion() throws IOException {
    StringBuffer paraGrabar = new StringBuffer();
    String linea;

    // La configuracin siempre se guarda en un fichero externo
    File dir = new File(System.getProperty(USER_HOME) + File.separator + getNombreDirExterno());
    if ((!dir.exists()) || (!dir.isDirectory())) {
        if (!dir.mkdir())
            return;
    }
    File fichero = new File(dir, getNombreFicheroExterno());
    log.trace("Salva fichero de configuracin en: " + fichero.getAbsolutePath());
    if (!fichero.exists()) {
        // Si el fichero externo no existe se crea fuera un copia
        // del fichero almacenado dentro del jar
        InputStream fis = getClass().getResourceAsStream(FICHERO_PROPIEDADES);
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream(fichero);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int length = bis.available();
        byte[] datos = new byte[length];
        bis.read(datos);
        bos.write(datos);
        bos.flush();
        bos.close();
        bis.close();
    }
    // AppPerfect: Falso positivo
    BufferedReader propiedades = new BufferedReader(new FileReader(fichero));

    linea = propiedades.readLine();
    while (linea != null) {
        StringTokenizer token = new StringTokenizer(linea, IGUAL);
        if (token.hasMoreTokens()) {
            String clave = token.nextToken().trim();
            if (configuracion.containsKey(clave)) {
                paraGrabar.append(clave);
                paraGrabar.append(IGUAL_ESPACIADO);
                paraGrabar.append(getValor(clave));
                paraGrabar.append(CRLF);
            } else {
                paraGrabar.append(linea);
                paraGrabar.append(CRLF);

            }
        } else
            paraGrabar.append(CRLF);
        linea = propiedades.readLine();
    }
    propiedades.close();

    //AppPerfect: Falso positivo
    FileWriter fw = new FileWriter(fichero);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(String.valueOf(paraGrabar));
    bw.flush();
    bw.close();

}

From source file:view.CertificateManagementDialog.java

public Certificate readCertificateFromFile(File f) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
    Certificate cert = null;/*from   ww  w . j  a  v a2 s  .  com*/
    while (in.available() > 0) {
        cert = cf.generateCertificate(in);
    }
    in.close();
    return cert;
}

From source file:com.sangupta.clitools.file.HexDump.java

private void execute() {
    File file = new File(this.filePath);

    InputStream is = null;/*from   w  w  w . j  a va2  s.c o m*/
    BufferedInputStream bis = null;

    PrintStream outStream = null;
    try {
        is = new FileInputStream(file);
        bis = new BufferedInputStream(is);

        if (this.outputAsFile) {
            outStream = new PrintStream(
                    new BufferedOutputStream(new FileOutputStream(new File(file.getAbsolutePath() + ".hex"))));
        } else {
            outStream = System.out;
        }

        int currentRow = 0;
        do {
            hexDump(outStream, bis, currentRow, 16);
            currentRow += 16;

            if (bis.available() <= 0) {
                break;
            }

            if (!this.outputAsFile) {
                // ask user to continue or exit
                String input = ConsoleUtils.readLine(":", true);
                if ("q".equalsIgnoreCase(input)) {
                    break;
                }
            }
        } while (true);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(bis);
        if (this.outputAsFile) {
            IOUtils.closeQuietly(outStream);
        }
    }
}

From source file:nl.nn.adapterframework.compression.ZipWriter.java

public void writeEntryWithCompletedHeader(String filename, Object contents, boolean close, String charset)
        throws CompressionException, IOException {
    if (StringUtils.isEmpty(filename)) {
        throw new CompressionException("filename cannot be empty");
    }/*from  w  w  w  . ja v  a  2  s  .co  m*/

    byte[] contentBytes = null;
    BufferedInputStream bis = null;
    long size = 0;
    if (contents != null) {
        if (contents instanceof byte[]) {
            contentBytes = (byte[]) contents;
        } else if (contents instanceof InputStream) {
            contentBytes = Misc.streamToBytes((InputStream) contents);
        } else {
            contentBytes = contents.toString().getBytes(charset);
        }
        bis = new BufferedInputStream(new ByteArrayInputStream(contentBytes));
        size = bis.available();
    } else {
        log.warn("contents of zip entry [" + filename + "] is null");
    }

    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();
    crc.reset();
    if (bis != null) {
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();
    }
    if (contents != null) {
        bis = new BufferedInputStream(new ByteArrayInputStream(contentBytes));
    }
    ZipEntry entry = new ZipEntry(filename);
    entry.setMethod(ZipEntry.STORED);
    entry.setCompressedSize(size);
    entry.setSize(size);
    entry.setCrc(crc.getValue());
    getZipoutput().putNextEntry(entry);
    if (bis != null) {
        while ((bytesRead = bis.read(buffer)) != -1) {
            getZipoutput().write(buffer, 0, bytesRead);
        }
        bis.close();
    }
    getZipoutput().closeEntry();
}

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * test, if updateControlValue correctly changes the value and a value-changed event occurs on the relevant control.
 * Check the new updateControlValue method suitable for Upload controls with base64 binary data.
 *
 * @throws Exception/*www.  j  a  va  2 s  . co m*/
 */
public void testUploadBase64() throws Exception {
    String testFilename = "hello-upload.xhtml";
    String id = "upload-input";
    String nodePath = "//file";
    processor.setXMLContainer(getClass().getResourceAsStream(testFilename));
    processor.init();

    Listener listener = new ChibaBeanTest.Listener();
    JXPathContext context = JXPathContext.newContext(this.processor.getXMLContainer());
    Node node = (Node) context.getPointer("//*[@id='" + id + "']").getNode();
    EventTarget eventTarget = (EventTarget) node;
    eventTarget.addEventListener(EventFactory.VALUE_CHANGED, listener, false);
    BufferedInputStream bf = new BufferedInputStream(getClass().getResourceAsStream(testFilename));
    byte[] bytes = new byte[bf.available()];
    bf.read(bytes);
    String testString = new String(bytes);
    String uploadFilename = "upload-test.txt";
    String uploadMediatype = "text/xml";
    processor.updateControlValue(id, uploadMediatype, uploadFilename, bytes);

    assertTrue(listener.type.equals(EventFactory.VALUE_CHANGED));
    assertTrue(listener.target.equals(id));

    //test the side effect of dispatching the DOMActivate to a setvalue 
    //trigger -> the instance has a new value
    Document instance = processor.getContainer().getDefaultModel().getDefaultInstance().getInstanceDocument();
    JXPathContext context1 = JXPathContext.newContext(instance);
    byte[] value = context1.getValue(nodePath).toString().getBytes();
    assertEquals(testString, new String(Base64.decodeBase64(value)));

    //Verify upload properties
    assertEquals(uploadFilename, context1.getValue(nodePath + "/@path").toString());
    assertEquals(uploadMediatype, context1.getValue(nodePath + "/@contentType").toString());
}

From source file:org.chiba.xml.xforms.test.ChibaBeanTest.java

/**
 * test, if updateControlValue correctly changes the value and a value-changed event occurs on the relevant control.
 * Check the new updateControlValue method suitable for Upload controls with hex binary data.
 *
 * @throws Exception/*from w w  w  .  ja  v a2s .co m*/
 */
public void testUploadHex() throws Exception {
    String testFilename = "hello-upload.xhtml";
    String id = "upload-input-hex";
    String nodePath = "//file2";
    processor.setXMLContainer(getClass().getResourceAsStream(testFilename));
    processor.init();

    Listener listener = new ChibaBeanTest.Listener();
    JXPathContext context = JXPathContext.newContext(this.processor.getXMLContainer());
    Node node = (Node) context.getPointer("//*[@id='" + id + "']").getNode();
    EventTarget eventTarget = (EventTarget) node;
    eventTarget.addEventListener(EventFactory.VALUE_CHANGED, listener, false);
    BufferedInputStream bf = new BufferedInputStream(getClass().getResourceAsStream(testFilename));
    byte[] bytes = new byte[bf.available()];
    bf.read(bytes);
    String testString = new String(bytes);
    String uploadFilename = "upload-test.txt";
    String uploadMediatype = "text/xml";
    processor.updateControlValue(id, uploadMediatype, uploadFilename, bytes);

    assertTrue(listener.type.equals(EventFactory.VALUE_CHANGED));
    assertTrue(listener.target.equals(id));

    //test the side effect of dispatching the DOMActivate to a setvalue
    //trigger -> the instance has a new value
    Document instance = processor.getContainer().getDefaultModel().getDefaultInstance().getInstanceDocument();
    JXPathContext context1 = JXPathContext.newContext(instance);
    char[] value = context1.getValue(nodePath).toString().toCharArray();
    assertEquals(testString, new String(Hex.decodeHex(value)));

    //Verify upload properties
    assertEquals(uploadFilename, context1.getValue(nodePath + "/@path").toString());
    assertEquals(uploadMediatype, context1.getValue(nodePath + "/@contentType").toString());

}

From source file:org.wso2.carbon.connector.integration.test.amazonsdb.AmazonSimpleDBConnectorIntegrationTest.java

private String getFileContent(String path) throws IOException {

    String fileContent = null;//ww w.j  a va 2 s. c o m
    BufferedInputStream bfist = new BufferedInputStream(new FileInputStream(path));

    byte[] buf = new byte[bfist.available()];
    bfist.read(buf);
    fileContent = new String(buf);

    if (bfist != null) {
        bfist.close();
    }
    return fileContent;

}

From source file:org.apache.carbondata.sdk.file.ImageTest.java

@Test
public void testWriteWithNull() throws IOException, InvalidLoadOptionException {
    String imagePath = "./src/test/resources/image/carbondatalogo.jpg";
    int num = 1;/* w w w .j  a  v  a  2  s.co  m*/
    int rows = 10;
    String path = "./target/binary";
    try {
        FileUtils.deleteDirectory(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    Field[] fields = new Field[5];
    fields[0] = new Field("name", DataTypes.STRING);
    fields[1] = new Field("age", DataTypes.INT);
    fields[2] = new Field("image1", DataTypes.BINARY);
    fields[3] = new Field("image2", DataTypes.BINARY);
    fields[4] = new Field("image3", DataTypes.BINARY);

    byte[] originBinary = null;

    // read and write image data
    for (int j = 0; j < num; j++) {
        CarbonWriter writer = CarbonWriter.builder().outputPath(path).withCsvInput(new Schema(fields))
                .writtenBy("SDKS3Example").withPageSizeInMb(1).withLoadOption("bad_records_action", "force")
                .build();

        for (int i = 0; i < rows; i++) {
            // read image and encode to Hex
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(imagePath));
            originBinary = new byte[bis.available()];
            while ((bis.read(originBinary)) != -1) {
            }
            // write data
            writer.write(new Object[] { "robot" + (i % 10), i, originBinary, originBinary, 1 });
            bis.close();
        }
        try {
            writer.close();
        } catch (Exception e) {
            assert (e.getMessage().contains("Binary only support String and byte[] data type"));
        }
    }

}