Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.eclipse.lyo.client.oslc.samples.automation.WriteThroughProperties.java

/**
 * Default constructor./*from  w ww  .  j a  v a 2s  .co m*/
 * 
 * @param fileUri
 *            URI for a local File containing the properties
 * @throws IOException 
 */
public WriteThroughProperties(URI fileUri) throws IOException {

    this.adapterPropertiesFile = new File(fileUri);

    FileInputStream fis = FileUtils.openInputStream(adapterPropertiesFile);

    load(fis);

    fis.close();

}

From source file:org.eclipse.smarthome.model.core.internal.folder.FolderObserver.java

private void checkFolder(String foldername) {
    File folder = getFolder(foldername);
    if (!folder.exists()) {
        return;// w ww .  java2 s .c  o  m
    }
    String[] extensions = folderFileExtMap.get(foldername);

    // check current files and add or refresh them accordingly
    Set<String> currentFileNames = new HashSet<String>();
    for (File file : folder.listFiles()) {
        if (file.isDirectory())
            continue;
        if (!file.getName().contains("."))
            continue;
        if (file.getName().startsWith("."))
            continue;

        // if there is an extension filter defined, continue if the file has a different extension
        String fileExt = getExtension(file.getName());
        if (extensions != null && extensions.length > 0 && !ArrayUtils.contains(extensions, fileExt))
            continue;

        currentFileNames.add(file.getName());
        Long timeLastCheck = lastCheckedMap.get(file.getName());
        if (timeLastCheck == null)
            timeLastCheck = 0L;
        if (FileUtils.isFileNewer(file, timeLastCheck)) {
            if (modelRepo != null) {
                try {
                    if (modelRepo.addOrRefreshModel(file.getName(), FileUtils.openInputStream(file))) {
                        lastCheckedMap.put(file.getName(), new Date().getTime());
                    }
                } catch (IOException e) {
                    logger.warn("Cannot open file '" + file.getAbsolutePath() + "' for reading.", e);
                }
            }
        }
    }

    // check for files that have been deleted meanwhile
    if (lastFileNames.get(foldername) != null) {
        ;
        for (String fileName : lastFileNames.get(foldername)) {
            if (!currentFileNames.contains(fileName)) {
                logger.info("File '{}' has been deleted", fileName);
                if (modelRepo != null) {
                    modelRepo.removeModel(fileName);
                }
            }
        }
    }
    lastFileNames.put(foldername, currentFileNames);
}

From source file:org.eclipse.smila.blackboard.impl.PersistingBlackboardImpl.java

/**
 * {@inheritDoc}/*  ww w.j av  a  2 s. com*/
 */
@Override
public void setAttachmentFromFile(final String id, final String name, final File attachmentFile)
        throws BlackboardAccessException {
    InputStream attachmentStream = null;
    try {
        final Record record = getRecord(id);
        attachmentStream = FileUtils.openInputStream(attachmentFile);
        storeAttachment(id, name, attachmentFile);
        checkCachedFileAttachment(id, name);
        record.setAttachment(name, null);
    } catch (final IOException exception) {
        throw new BlackboardAccessException(exception);
    } finally {
        IOUtils.closeQuietly(attachmentStream);
    }
}

From source file:org.eclipse.smila.blackboard.impl.PersistingBlackboardImpl.java

/**
 * Saves attachment to binary storage from given File and replaces actual attachment with null into corresponding
 * record.//w w  w  . j ava 2  s.c o  m
 * 
 * @param id
 *          Record Id
 * @param name
 *          Attachment name
 * @param attachment
 *          Attachment object
 * 
 * @throws BlackboardAccessException
 *           BlackboardAccessException
 */
private void storeAttachment(final String id, final String name, final File attachment)
        throws BlackboardAccessException {
    final String attachmentId = getAttachmentId(id, name);
    if (_log.isDebugEnabled()) {
        _log.debug("Saving attachment " + attachmentId + " to binary storage");
    }
    InputStream attachmentStream = null;
    try {
        attachmentStream = FileUtils.openInputStream(attachment);
        _binaryStorage.store(attachmentId, attachmentStream);
    } catch (final Exception exception) {
        throw new BlackboardAccessException(
                "Failed to save attachment in binary storage for record having id :" + id, exception);
    } finally {
        IOUtils.closeQuietly(attachmentStream);
    }
}

From source file:org.fcrepo.auth.xacml.PolicyUtilTest.java

@Test
public void test() throws Exception {
    final String id = PolicyUtil
            .getID(FileUtils.openInputStream(new File("src/main/resources/policies/GlobalRolesPolicySet.xml")));
    Assert.assertEquals("info:fedora/policies/GlobalRolesPolicySet", id);

    final String path = PolicyUtil.getPathForId(id);
    Assert.assertEquals("/policies/GlobalRolesPolicySet", path);
}

From source file:org.fcrepo.auth.xacml.XACMLWorkspaceInitializer.java

/**
 * Create nodes for the default XACML policy set. Policies are created at paths according to their IDs.
 *///  w ww . j a v a  2  s  . c om
private void loadInitialPolicies() {
    FedoraSession session = null;
    try {
        session = sessionFactory.getInternalSession();
        for (final File p : initialPoliciesDirectory.listFiles()) {
            final String id = PolicyUtil.getID(FileUtils.openInputStream(p));
            final String repoPath = PolicyUtil.getPathForId(id);
            final FedoraBinary binary = binaryService.findOrCreate(session, repoPath);
            try (FileInputStream stream = new FileInputStream(p)) {
                binary.setContent(stream, "application/xml", null, p.getName(), null);
            }
            LOGGER.info("Add initial policy {} at {}", p.getAbsolutePath(), binary.getPath());
        }
        session.commit();
    } catch (final InvalidChecksumException | IOException e) {
        throw new Error("Cannot create default root policies", e);
    } finally {
        if (session != null) {
            session.expire();
        }
    }
}

From source file:org.fcrepo.auth.xacml.XACMLWorkspaceInitializer.java

/**
 * Set the policy that is effective at the root node.
 *///from  ww w  .jav a2  s  .c  o  m
private void linkRootToPolicy() {
    Session session = null;
    try {
        session = getJcrSession(sessionFactory.getInternalSession());
        session.getRootNode().addMixin("authz:xacmlAssignable");
        final String id = PolicyUtil.getID(FileUtils.openInputStream(initialRootPolicyFile));
        final String repoPath = PolicyUtil.getPathForId(id);
        final Node globalPolicy = session.getNode(repoPath);
        session.getRootNode().setProperty("authz:policy", globalPolicy);
        session.save();
    } catch (final RepositoryException | IOException e) {
        throw new Error("Cannot configure root mix-in or policy", e);
    } finally {
        if (session != null) {
            session.logout();
        }
    }
}

From source file:org.flowerplatform.core.file.PlainFileAccessController.java

/**
 * @see IOUtils/*from   w  w w . j a va 2s.c  o m*/
 * @see FileUtils   
 */
@Override
public InputStream getContent(Object file) {
    try {
        return FileUtils.openInputStream((File) file);
    } catch (Throwable e) {
        throw new RuntimeException("Error while loading file content " + file, e);
    }
}

From source file:org.geoserver.taskmanager.external.impl.FileServiceImpl.java

@Override
public InputStream read(String filePath) throws IOException {
    if (checkFileExists(filePath)) {
        File file = new File(getAbsolutePath(filePath).toUri());
        return FileUtils.openInputStream(file);
    } else {/*w ww .jav a2  s . c o  m*/
        throw new IOException("The file does not exit:" + filePath.toString());
    }
}

From source file:org.gluu.oxtrust.action.JoinFederationAction.java

public String downloadFederation() throws IOException {
    boolean result = false;
    if (StringHelper.isNotEmpty(inum)) {
        GluuSAMLFederationProposal federation = federationService.getProposalByInum(inum);
        if (!federation.isFederation() || !federation.getStatus().equals(GluuStatus.ACTIVE)) {
            return OxTrustConstants.RESULT_FAILURE;
        }/*  w w  w  .  j  av  a2 s.c o  m*/

        Shibboleth2ConfService shibboleth2ConfService = Shibboleth2ConfService.instance();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(16384);
        String head = String.format(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<EntitiesDescriptor Name=\"%s\"  xmlns=\"urn:oasis:names:tc:SAML:2.0:metadata\">\n",
                StringHelper.removePunctuation(federation.getInum()));
        bos.write(head.getBytes());
        for (GluuSAMLFederationProposal proposal : federationService.getAllActiveFederationProposals()) {
            if (proposal.getContainerFederation() != null
                    && proposal.getContainerFederation().equals(federation)) {
                String filename = proposal.getSpMetaDataFN();
                if (!StringUtils.isEmpty(filename)) {
                    File metadataFile = new File(shibboleth2ConfService.getMetadataFilePath(filename));
                    InputStream is = FileUtils.openInputStream(metadataFile);
                    ExcludeFilterInputStream filtered = new ExcludeFilterInputStream(is, "<?", "?>");
                    IOUtils.copy(filtered, bos);
                }
            }
        }
        String tail = "</EntitiesDescriptor>";
        bos.write(tail.getBytes());

        result = ResponseHelper.downloadFile("federation.xml", OxTrustConstants.CONTENT_TYPE_TEXT_PLAIN,
                bos.toByteArray(), facesContext);
    }
    return result ? OxTrustConstants.RESULT_SUCCESS : OxTrustConstants.RESULT_FAILURE;
}