Example usage for java.nio.file Files newInputStream

List of usage examples for java.nio.file Files newInputStream

Introduction

In this page you can find the example usage for java.nio.file Files newInputStream.

Prototype

public static InputStream newInputStream(Path path, OpenOption... options) throws IOException 

Source Link

Document

Opens a file, returning an input stream to read from the file.

Usage

From source file:de.bund.bfr.pmfml.file.CombineArchiveUtil.java

static NuMLDocument readData(Path path) throws IOException, ParserConfigurationException, SAXException {
    try (InputStream is = Files.newInputStream(path, StandardOpenOption.READ)) {
        return NuMLReader.read(is);
    }/*from  ww  w  .  j a v a 2  s . c  om*/
}

From source file:io.github.dsheirer.record.wave.MonoWaveReader.java

/**
 * Opens the file//  w  w w  . j a  va 2s.  c  o m
 */
private void open() throws IOException {
    if (!Files.exists(mPath)) {
        throw new IOException("File not found");
    }

    mInputStream = Files.newInputStream(mPath, StandardOpenOption.READ);

    //Check for RIFF header
    byte[] buffer = new byte[4];
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.RIFF_CHUNK)) {
        throw new IOException("File is not .wav format - missing RIFF chunk");
    }

    //Get file size
    mInputStream.read(buffer);
    int fileSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Check for WAVE format
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.WAV_FORMAT)) {
        throw new IOException("File is not .wav format - missing WAVE format");
    }

    //Check for format chunk
    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_FORMAT)) {
        throw new IOException("File is not .wav format - missing format chunk");
    }

    //Get chunk size
    mInputStream.read(buffer);
    int chunkSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get format
    mInputStream.read(buffer);

    ShortBuffer shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short format = shortBuffer.get();
    if (format != WaveUtils.PCM_FORMAT) {
        throw new IOException("File format not supported - expecting PCM format");
    }

    //Get number of channels
    short channels = shortBuffer.get();
    if (channels != 1) {
        throw new IOException("Unsupported channel count - mono audio only");
    }

    //Get samples per second
    mInputStream.read(buffer);
    int sampleRate = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    //Get bytes per second
    mInputStream.read(buffer);
    int bytesPerSecond = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();

    mInputStream.read(buffer);

    //Get frame size
    shortBuffer = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    short frameSize = shortBuffer.get();
    if (frameSize != 2) {
        throw new IOException("PCM frame size not supported - expecting 2 bytes per frame");
    }

    //Get bits per sample
    short bitsPerSample = shortBuffer.get();
    if (bitsPerSample != 16) {
        throw new IOException("PCM sample size not supported - expecting 16 bits per sample");
    }

    mInputStream.read(buffer);

    if (!Arrays.equals(buffer, WaveUtils.CHUNK_DATA)) {
        throw new IOException("Unexpected chunk - expecting data chunk");
    }

    //Get data chunk size
    mInputStream.read(buffer);
    mDataByteSize = ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer().get();
}

From source file:com.github.horrorho.inflatabledonkey.chunk.store.disk.DiskChunk.java

@Override
public long copyTo(OutputStream output) throws UncheckedIOException {
    try (InputStream input = Files.newInputStream(file, READ)) {
        long bytes = IOUtils.copyLarge(input, output);

        logger.debug("-- copyTo() - written (bytes): {}", bytes);
        return bytes;

    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }//from   ww w. ja v  a 2 s.  com
}

From source file:org.cryptomator.ui.settings.SettingsProvider.java

@Override
public Settings get() {
    final Settings settings = new Settings(this::scheduleSave);
    try {//from   w  ww .j  av a 2 s  .  c  om
        final Path settingsPath = getSettingsPath();
        final InputStream in = Files.newInputStream(settingsPath, StandardOpenOption.READ);
        objectMapper.readerForUpdating(settings).readValue(in);
        LOG.info("Settings loaded from " + settingsPath);
    } catch (IOException e) {
        LOG.info("Failed to load settings, creating new one.");
    }
    return settings;
}

From source file:org.apache.nifi.minifi.FlowParser.java

/**
 * Generates a {@link Document} from the flow configuration file provided
 *//*from  ww w.  ja  v a2 s  .  c o  m*/
public Document parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        docBuilder.setErrorHandler(new LoggingXmlParserErrorHandler("Flow Configuration", logger));
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));
        return document;

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:de.bund.bfr.pmfml.file.CombineArchiveUtil.java

static SBMLDocument readModel(Path path) throws IOException, XMLStreamException {
    try (InputStream stream = Files.newInputStream(path, StandardOpenOption.READ)) {
        return READER.readSBMLFromStream(stream);
    }/*from   ww  w  .j av  a  2 s . c om*/
}

From source file:org.apache.nifi.authorization.FlowParser.java

/**
 * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts
 * the root group input ports and output ports, and their access controls.
 *
 *///from  ww  w  .j a  v  a2  s.c  o  m
public FlowInfo parse(final File flowConfigurationFile) {
    if (flowConfigurationFile == null) {
        logger.debug("Flow Configuration file was null");
        return null;
    }

    // if the flow doesn't exist or is 0 bytes, then return null
    final Path flowPath = flowConfigurationFile.toPath();
    try {
        if (!Files.exists(flowPath) || Files.size(flowPath) == 0) {
            logger.warn("Flow Configuration does not exist or was empty");
            return null;
        }
    } catch (IOException e) {
        logger.error("An error occurred determining the size of the Flow Configuration file");
        return null;
    }

    // otherwise create the appropriate input streams to read the file
    try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ);
            final InputStream gzipIn = new GZIPInputStream(in)) {

        final byte[] flowBytes = IOUtils.toByteArray(gzipIn);
        if (flowBytes == null || flowBytes.length == 0) {
            logger.warn("Could not extract root group id because Flow Configuration File was empty");
            return null;
        }

        // create validating document builder
        final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        docFactory.setNamespaceAware(true);
        docFactory.setSchema(flowSchema);

        // parse the flow
        final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes));

        // extract the root group id
        final Element rootElement = document.getDocumentElement();

        final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0);
        if (rootGroupElement == null) {
            logger.warn("rootGroup element not found in Flow Configuration file");
            return null;
        }

        final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0);
        if (rootGroupIdElement == null) {
            logger.warn("id element not found under rootGroup in Flow Configuration file");
            return null;
        }

        final String rootGroupId = rootGroupIdElement.getTextContent();

        final List<PortDTO> ports = new ArrayList<>();
        ports.addAll(getPorts(rootGroupElement, "inputPort"));
        ports.addAll(getPorts(rootGroupElement, "outputPort"));

        return new FlowInfo(rootGroupId, ports);

    } catch (final SAXException | ParserConfigurationException | IOException ex) {
        logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex });
        return null;
    }
}

From source file:org.cryptomator.ui.UnlockController.java

@FXML
private void didClickUnlockButton(ActionEvent event) {
    setControlsDisabled(true);/* w ww. j ava2  s .c om*/
    final String masterKeyFileName = usernameBox.getValue() + Aes256Cryptor.MASTERKEY_FILE_EXT;
    final Path masterKeyPath = directory.getPath().resolve(masterKeyFileName);
    final CharSequence password = passwordField.getCharacters();
    InputStream masterKeyInputStream = null;
    try {
        progressIndicator.setVisible(true);
        masterKeyInputStream = Files.newInputStream(masterKeyPath, StandardOpenOption.READ);
        directory.setVerifyFileIntegrity(checkIntegrity.isSelected());
        directory.getCryptor().decryptMasterKey(masterKeyInputStream, password);
        if (!directory.startServer()) {
            messageLabel.setText(rb.getString("unlock.messageLabel.startServerFailed"));
            directory.getCryptor().swipeSensitiveData();
            return;
        }
        directory.setUnlocked(true);
        final Future<Boolean> futureMount = FXThreads.runOnBackgroundThread(directory::mount);
        FXThreads.runOnMainThreadWhenFinished(futureMount, this::didUnlockAndMount);
        FXThreads.runOnMainThreadWhenFinished(futureMount, (result) -> {
            setControlsDisabled(false);
        });
    } catch (DecryptFailedException | IOException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(rb.getString("unlock.errorMessage.decryptionFailed"));
        LOG.error("Decryption failed for technical reasons.", ex);
    } catch (WrongPasswordException e) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(rb.getString("unlock.errorMessage.wrongPassword"));
        Platform.runLater(passwordField::requestFocus);
    } catch (UnsupportedKeyLengthException ex) {
        setControlsDisabled(false);
        progressIndicator.setVisible(false);
        messageLabel.setText(rb.getString("unlock.errorMessage.unsupportedKeyLengthInstallJCE"));
        LOG.warn("Unsupported Key-Length. Please install Oracle Java Cryptography Extension (JCE).", ex);
    } finally {
        passwordField.swipe();
        IOUtils.closeQuietly(masterKeyInputStream);
    }
}

From source file:com.github.technosf.posterer.models.KeyStoreBean.java

/**
 * Instantiates a {@code KeyStoreBean} wrapping the given keystore
 * <p>/*  w w  w  .  jav a  2 s.  c  om*/
 * Loads the Key Store file into a {@code KeyStore} and checks the password. If the Key Store
 * can be accessed successfully, validation is successful..
 * 
 * @param file
 *            the KeyStore file
 * @param password
 *            the Key Store password
 * @throws KeyStoreBeanException
 *             Thrown when a {@code KeyStoreBean} cannot be created.
 */
public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException {
    file = keyStoreFile;
    password = keyStorePassword;

    InputStream inputStream = null;

    /*
     * Check file existence
     */
    if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead())
    // Key Store File cannot be read
    {
        throw new KeyStoreBeanException("Cannot read Key Store file");
    }

    try
    // to get the file input stream
    {
        inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ);
    } catch (IOException e) {
        throw new KeyStoreBeanException("Error reading Key Store file", e);
    }

    // Get the file name and extension
    fileName = FilenameUtils.getName(keyStoreFile.getName());
    String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase());

    /*
     * Identify keystore type, and create an instance
     */
    try {
        switch (fileExtension) {
        case "p12":
            keyStore = KeyStore.getInstance("PKCS12");
            break;
        case "jks":
            keyStore = KeyStore.getInstance("JKS");
            break;
        default:
            throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot get keystore instance");
    }

    /*
     * Load the keystore data into the keystore instance
     */
    try {
        keyStore.load(inputStream, password.toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new KeyStoreBeanException("Cannot load the KeyStore", e);
    }

    /*
     * Key store loaded, so config the bean
     */
    try {
        type = keyStore.getType();
        size = keyStore.size();

        Enumeration<String> aliasIterator = keyStore.aliases();
        while (aliasIterator.hasMoreElements()) {
            String alias = aliasIterator.nextElement();
            certificates.put(alias, keyStore.getCertificate(alias));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot process the KeyStore", e);
    }
}

From source file:com.github.technosf.posterer.models.impl.KeyStoreBean.java

/**
 * Instantiates a {@code KeyStoreBean} wrapping the given keystore
 * <p>//from w w  w  . j a v a 2s  .  c om
 * Loads the Key Store file into a {@code KeyStore} and checks the password.
 * If the Key Store
 * can be accessed successfully, validation is successful..
 * 
 * @param file
 *            the KeyStore file
 * @param password
 *            the Key Store password
 * @throws KeyStoreBeanException
 *             Thrown when a {@code KeyStoreBean} cannot be created.
 */
@SuppressWarnings("null")
public KeyStoreBean(final File keyStoreFile, final String keyStorePassword) throws KeyStoreBeanException {
    file = keyStoreFile;
    password = keyStorePassword;

    InputStream inputStream = null;

    /*
     * Check file existence
     */
    if (keyStoreFile == null || !keyStoreFile.exists() || !keyStoreFile.canRead())
    // Key Store File cannot be read
    {
        throw new KeyStoreBeanException("Cannot read Key Store file");
    }

    try
    // to get the file input stream
    {
        inputStream = Files.newInputStream(keyStoreFile.toPath(), StandardOpenOption.READ);
    } catch (IOException e) {
        throw new KeyStoreBeanException("Error reading Key Store file", e);
    }

    // Get the file name and extension
    fileName = FilenameUtils.getName(keyStoreFile.getName());
    String fileExtension = FilenameUtils.getExtension(keyStoreFile.getName().toLowerCase());

    /*
     * Identify keystore type, and create an instance
     */
    try {
        switch (fileExtension) {
        case "p12":
            keyStore = KeyStore.getInstance("PKCS12");
            break;
        case "jks":
            keyStore = KeyStore.getInstance("JKS");
            break;
        default:
            throw new KeyStoreBeanException(String.format("Unknown keystore extention: [%1$s]", fileExtension));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot get keystore instance");
    }

    /*
     * Load the keystore data into the keystore instance
     */
    try {
        keyStore.load(inputStream, password.toCharArray());
        valid = true;
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new KeyStoreBeanException("Cannot load the KeyStore", e);
    }

    /*
     * Key store loaded, so config the bean
     */
    try {
        type = keyStore.getType();
        size = keyStore.size();

        Enumeration<String> aliasIterator = keyStore.aliases();
        while (aliasIterator.hasMoreElements()) {
            String alias = aliasIterator.nextElement();
            certificates.put(alias, keyStore.getCertificate(alias));
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreBeanException("Cannot process the KeyStore", e);
    }
}