Example usage for java.io FileInputStream available

List of usage examples for java.io FileInputStream available

Introduction

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

Prototype

public int available() throws IOException 

Source Link

Document

Returns an estimate of the number of remaining 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.opensextant.util.FileUtility.java

/**
 * Slurps a text file into a string and returns the string.
 *
 * @param fileinput/*from w w w .j  a v  a  2  s .co m*/
 *            file object
 * @param enc
 *            text encoding
 * @return buffer from file
 * @throws IOException
 *             on error
 */
public static String readFile(File fileinput, String enc) throws IOException {
    if (fileinput == null) {
        return null;
    }

    final FileInputStream instream = new FileInputStream(fileinput);
    final byte[] inputBytes = new byte[instream.available()];
    instream.read(inputBytes);
    instream.close();
    return new String(inputBytes, enc);
}

From source file:org.opensextant.util.FileUtility.java

/**
 * Given a file get the byte array//  w w  w  . j  a v  a  2 s .  co m
 *
 * @param fileinput
 *            file object
 * @return byte array
 * @throws IOException
 *             on error
 */
public static byte[] readBytesFrom(File fileinput) throws IOException {
    if (fileinput == null) {
        return null;
    }

    final FileInputStream instream = new FileInputStream(fileinput);
    final byte[] inputBytes = new byte[instream.available()];
    instream.read(inputBytes);
    instream.close();
    return inputBytes;
}

From source file:org.openflexo.toolbox.FileUtils.java

public static void copyFileToFile(File curFile, File newFile) throws IOException {
    FileInputStream is = new FileInputStream(curFile);
    try {/* w w  w. ja v  a  2 s  . com*/
        createNewFile(newFile);
        FileOutputStream os = new FileOutputStream(newFile);
        try {
            while (is.available() > 0) {
                byte[] byteArray = new byte[is.available()];
                is.read(byteArray);
                os.write(byteArray);
            }
            os.flush();
        } finally {
            os.close();
        }
    } finally {
        is.close();
    }
}

From source file:org.openflexo.toolbox.FileUtils.java

public static File copyFileToDir(FileInputStream is, String newFileName, File dest) throws IOException {
    File newFile = new File(dest, newFileName);
    createNewFile(newFile);/*from  ww w.j  av a  2  s .co  m*/
    FileOutputStream os = new FileOutputStream(newFile);
    try {
        while (is.available() > 0) {
            byte[] byteArray = new byte[is.available()];
            is.read(byteArray);
            os.write(byteArray);
        }
        os.flush();
    } finally {
        os.close();
    }
    return newFile;
}

From source file:com.openkm.util.impexp.RepositoryImporter.java

/**
 * Import document.//from w  ww  . j a  v  a2s  .  c o  m
 */
private static ImpExpStats importDocument(String token, File fs, String fldPath, String fileName, File fDoc,
        boolean metadata, boolean history, Writer out, InfoDecorator deco)
        throws IOException, RepositoryException, DatabaseException, PathNotFoundException,
        AccessDeniedException, ExtensionException, AutomationException {
    FileInputStream fisContent = new FileInputStream(fDoc);
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    DocumentModule dm = ModuleManager.getDocumentModule();
    ImpExpStats stats = new ImpExpStats();
    int size = fisContent.available();
    Document doc = new Document();
    Gson gson = new Gson();
    boolean api = false;

    try {
        // Metadata
        if (metadata) {
            // Read serialized document metadata
            File jsFile = new File(fDoc.getPath() + Config.EXPORT_METADATA_EXT);
            log.info("Document Metadata File: {}", jsFile.getPath());

            if (jsFile.exists() && jsFile.canRead()) {
                FileReader fr = new FileReader(jsFile);
                DocumentMetadata dmd = gson.fromJson(fr, DocumentMetadata.class);
                doc.setPath(fldPath + "/" + fileName);
                dmd.setPath(doc.getPath());
                IOUtils.closeQuietly(fr);
                log.info("Document Metadata: {}", dmd);

                if (history) {
                    File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                    List<File> listFiles = Arrays.asList(vhFiles);
                    Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                    boolean first = true;

                    for (File vhf : vhFiles) {
                        String vhfName = vhf.getName();
                        int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                        String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                        FileInputStream fis = new FileInputStream(vhf);
                        File jsVerFile = new File(vhf.getPath() + Config.EXPORT_METADATA_EXT);
                        log.info("Document Version Metadata File: {}", jsVerFile.getPath());

                        if (jsVerFile.exists() && jsVerFile.canRead()) {
                            FileReader verFr = new FileReader(jsVerFile);
                            VersionMetadata vmd = gson.fromJson(verFr, VersionMetadata.class);
                            IOUtils.closeQuietly(verFr);

                            if (first) {
                                dmd.setVersion(vmd);
                                size = fis.available();
                                ma.importWithMetadata(dmd, fis);
                                first = false;
                            } else {
                                log.info("Document Version Metadata: {}", vmd);
                                size = fis.available();
                                ma.importWithMetadata(doc.getPath(), vmd, fis);
                            }
                        } else {
                            log.warn("Unable to read metadata file: {}", jsVerFile.getPath());
                        }

                        IOUtils.closeQuietly(fis);
                        FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                                verName);
                        log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                    }
                } else {
                    // Apply metadata
                    ma.importWithMetadata(dmd, fisContent);
                    FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                    log.info("Created document '{}'", doc.getPath());
                }
            } else {
                log.warn("Unable to read metadata file: {}", jsFile.getPath());
                api = true;
            }
        } else {
            api = true;
        }

        if (api) {
            doc.setPath(fldPath + "/" + fileName);

            // Version history
            if (history) {
                File[] vhFiles = fs.listFiles(new RepositoryImporter.VersionFilenameFilter(fileName));
                List<File> listFiles = Arrays.asList(vhFiles);
                Collections.sort(listFiles, FilenameVersionComparator.getInstance());
                boolean first = true;

                for (File vhf : vhFiles) {
                    String vhfName = vhf.getName();
                    int idx = vhfName.lastIndexOf('#', vhfName.length() - 2);
                    String verName = vhfName.substring(idx + 2, vhfName.length() - 1);
                    FileInputStream fis = new FileInputStream(vhf);

                    if (first) {
                        dm.create(token, doc, fis);
                        first = false;
                    } else {
                        dm.checkout(token, doc.getPath());
                        dm.checkin(token, doc.getPath(), fis, "Imported from administration");
                    }

                    IOUtils.closeQuietly(fis);
                    FileLogger.info(BASE_NAME, "Created document ''{0}'' version ''{1}''", doc.getPath(),
                            verName);
                    log.info("Created document '{}' version '{}'", doc.getPath(), verName);
                }
            } else {
                dm.create(token, doc, fisContent);
                FileLogger.info(BASE_NAME, "Created document ''{0}''", doc.getPath());
                log.info("Created document ''{}''", doc.getPath());
            }
        }

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), null));
            out.flush();
        }

        // Stats
        stats.setSize(stats.getSize() + size);
        stats.setDocuments(stats.getDocuments() + 1);
    } catch (UnsupportedMimeTypeException e) {
        log.warn("UnsupportedMimeTypeException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UnsupportedMimeType"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UnsupportedMimeTypeException ''{0}''", doc.getPath());
    } catch (FileSizeExceededException e) {
        log.warn("FileSizeExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "FileSizeExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "FileSizeExceededException ''{0}''", doc.getPath());
    } catch (UserQuotaExceededException e) {
        log.warn("UserQuotaExceededException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "UserQuotaExceeded"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "UserQuotaExceededException ''{0}''", doc.getPath());
    } catch (VirusDetectedException e) {
        log.warn("VirusWarningException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "VirusWarningException"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VirusWarningException ''{0}''", doc.getPath());
    } catch (ItemExistsException e) {
        log.warn("ItemExistsException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "ItemExists"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", doc.getPath());
    } catch (LockException e) {
        log.warn("LockException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Lock"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "LockException ''{0}''", doc.getPath());
    } catch (VersionException e) {
        log.warn("VersionException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Version"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "VersionException ''{0}''", doc.getPath());
    } catch (JsonParseException e) {
        log.warn("JsonParseException: {}", e.getMessage());

        if (out != null) {
            out.write(deco.print(fDoc.getPath(), fDoc.length(), "Json"));
            out.flush();
        }

        stats.setOk(false);
        FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", doc.getPath());
    } finally {
        IOUtils.closeQuietly(fisContent);
    }

    return stats;
}

From source file:edu.internet2.middleware.shibboleth.common.config.security.FilesystemPKIXValidationInformationBeanDefinitionParser.java

/** {@inheritDoc} */
protected byte[] getEncodedCRL(String certCRLContent) {
    try {//from w w w .ja  v  a2 s  .  co m
        FileInputStream ins = new FileInputStream(certCRLContent);
        byte[] encoded = new byte[ins.available()];
        ins.read(encoded);
        return encoded;
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read CRL(s) from file " + certCRLContent, e);
    }
}

From source file:com.chargebee.Application.MappingHeaders.java

private JSONObject readJsonData(String fileName2) throws Exception { //processes the Json array and returns in the required format. 
    File f = new File(fileName2);
    FileInputStream fr = new FileInputStream(f);
    byte[] b = new byte[fr.available()];
    fr.read(b);/*  w ww  .ja  va 2s .co m*/
    //JSONArray jarr = new JSONArray(new String(b));
    JSONObject jobj = new JSONObject(new String(b));
    return jobj; // The required Json object

}

From source file:edu.internet2.middleware.shibboleth.common.config.security.FilesystemPKIXValidationInformationBeanDefinitionParser.java

/** {@inheritDoc} */
protected byte[] getEncodedCertificate(String certConfigContent) {
    try {//from   ww  w . ja  v  a 2 s  .c o  m
        FileInputStream ins = new FileInputStream(certConfigContent);
        byte[] encoded = new byte[ins.available()];
        ins.read(encoded);
        return encoded;
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read certificate(s) from file " + certConfigContent, e);
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.security.FilesystemBasicCredentialBeanDefinitionParser.java

/** {@inheritDoc} */
protected byte[] getEncodedPrivateKey(String keyConfigContent) {
    try {//from ww  w .  j  a  va2 s  .  c  o m
        FileInputStream ins = new FileInputStream(keyConfigContent);
        byte[] encoded = new byte[ins.available()];
        ins.read(encoded);
        return encoded;
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read private key from file " + keyConfigContent, e);
    }
}

From source file:edu.internet2.middleware.shibboleth.common.config.security.FilesystemBasicCredentialBeanDefinitionParser.java

/** {@inheritDoc} */
protected byte[] getEncodedSecretKey(String keyConfigContent) {
    try {/*from w w  w  .ja  v a 2s.c  o  m*/
        FileInputStream ins = new FileInputStream(keyConfigContent);
        byte[] encoded = new byte[ins.available()];
        ins.read(encoded);
        return encoded;
    } catch (IOException e) {
        throw new FatalBeanException("Unable to read secret key from file " + keyConfigContent, e);
    }
}