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:edu.cornell.med.icb.goby.reads.ReadsReader.java

/**
 * Initialize the reader to read a segment of the input. Sequences represented by a
 * collection which starts between the input position start and end will be returned
 * upon subsequent calls to {@link #hasNext()} and {@link #next()}.
 *
 * @param start Start offset in the input file
 * @param end   End offset in the input file
 * @param path  Path to the input file/*from   w  ww .jav a  2s . c  o  m*/
 * @throws IOException If an error occurs reading the input
 */
public ReadsReader(final long start, final long end, final String path) throws IOException {
    this(start, end, new FastBufferedInputStream(FileUtils.openInputStream(new File(path))));
}

From source file:com.github.magicsky.sya.checkers.TestSourceReader.java

/**
 * Returns an array of StringBuilder objects for each comment section found preceding the named
 * test in the source code./*from w  w  w  .  jav  a 2  s  .c o m*/
 *
 * @param srcRoot     the directory inside the bundle containing the packages
 * @param clazz       the name of the class containing the test
 * @param testName    the name of the test
 * @param numSections the number of comment sections preceding the named test to return.
 *                    Pass zero to get all available sections.
 * @return an array of StringBuilder objects for each comment section found preceding the named
 * test in the source code.
 * @throws IOException
 */
public static StringBuilder[] getContentsForTest(String srcRoot, Class clazz, final String testName,
        int numSections) throws IOException {
    // Walk up the class inheritance chain until we find the test method.
    try {
        while (clazz.getMethod(testName).getDeclaringClass() != clazz) {
            clazz = clazz.getSuperclass();
        }
    } catch (SecurityException e) {
        Assert.fail(e.getMessage());
    } catch (NoSuchMethodException e) {
        Assert.fail(e.getMessage());
    }

    while (true) {
        // Find and open the .java file for the class clazz.
        String fqn = clazz.getName().replace('.', '/');
        fqn = fqn.indexOf("$") == -1 ? fqn : fqn.substring(0, fqn.indexOf("$"));
        String classFile = fqn + ".java";
        InputStream in;
        Class superclass = clazz.getSuperclass();
        try {
            in = FileUtils.openInputStream(new File(srcRoot + '/' + classFile));
        } catch (IOException e) {
            if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
                throw e;
            }
            clazz = superclass;
            continue;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        try {
            // Read the java file collecting comments until we encounter the test method.
            List<StringBuilder> contents = new ArrayList<StringBuilder>();
            StringBuilder content = new StringBuilder();
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                line = line.replaceFirst("^\\s*", ""); // Replace leading whitespace, preserve trailing
                if (line.startsWith("//")) {
                    content.append(line.substring(2) + "\n");
                } else {
                    if (!line.startsWith("@") && content.length() > 0) {
                        contents.add(content);
                        if (numSections > 0 && contents.size() == numSections + 1)
                            contents.remove(0);
                        content = new StringBuilder();
                    }
                    if (line.length() > 0 && !contents.isEmpty()) {
                        int idx = line.indexOf(testName);
                        if (idx != -1
                                && !Character.isJavaIdentifierPart(line.charAt(idx + testName.length()))) {
                            return contents.toArray(new StringBuilder[contents.size()]);
                        }
                        if (!line.startsWith("@")) {
                            contents.clear();
                        }
                    }
                }
            }
        } finally {
            br.close();
        }

        if (superclass == null || !superclass.getPackage().equals(clazz.getPackage())) {
            throw new IOException("Test data not found for " + clazz.getName() + "." + testName);
        }
        clazz = superclass;
    }
}

From source file:ddf.mime.mapper.MimeTypeMapperTest.java

@Test
public void testGuessMimeTypeForXmlIngest() throws Exception {

    List<MimeTypeResolver> resolvers = new ArrayList<MimeTypeResolver>();
    resolvers.add(new MockMimeTypeResolver("NitfResolver", 10,
            new String[] { "nitf=image/nitf", "ntf=image/nitf" }, null));
    resolvers.add(new MockMimeTypeResolver("XmlMetacardResolver", 10, new String[] { "xml=text/xml" },
            "urn:catalog:metacard"));
    resolvers.add(new MockMimeTypeResolver("CswResolver", 10, new String[] { "xml=text/xml;id=csw" },
            "http://www.opengis.net/cat/csw/2.0.2"));
    TikaMimeTypeResolver tikaMimeTypeResolver = new TikaMimeTypeResolver();
    tikaMimeTypeResolver.setPriority(-1);
    resolvers.add(tikaMimeTypeResolver);

    MimeTypeMapper mapper = new MimeTypeMapperImpl(resolvers);

    InputStream is = FileUtils.openInputStream(new File(CSW_RECORD_FILE));
    String mimeType = mapper.guessMimeType(is, "xml");
    LOGGER.debug("mimeType = {}", mimeType);
    assertEquals("text/xml;id=csw", mimeType);

    is = FileUtils.openInputStream(new File(XML_METACARD_FILE));
    mimeType = mapper.guessMimeType(is, "xml");
    LOGGER.debug("mimeType = {}", mimeType);
    assertEquals("text/xml", mimeType);

    // Verify an XML file with a root element namespace, e.g., a pom.xml file, that does not match any
    // MimeTypeResolver returns a null mime type
    is = FileUtils.openInputStream(new File(NO_NAMESPACE_MATCHES_XML_FILE));
    mimeType = mapper.guessMimeType(is, "xml");
    LOGGER.debug("mimeType = {}", mimeType);
    assertNull(mimeType);/* ww  w  . ja  v a  2s. co  m*/

    // Verify an XML file with no namespaces that does not match any
    // MimeTypeResolver returns a null mime type
    is = FileUtils.openInputStream(new File(NO_NAMESPACES_XML_FILE));
    mimeType = mapper.guessMimeType(is, "xml");
    LOGGER.debug("mimeType = {}", mimeType);
    assertNull(mimeType);
}

From source file:de.pawlidi.openaletheia.license.LicenseHandlerTest.java

@Test(expected = LicenseException.class)
public void test5_LoadInputStream() throws LicenseException, IOException {
    licenseHandler.load(FileUtils.openInputStream(new File(LICENSE_FILE)));
    assertTrue(licenseHandler.getLicense() != null);
}

From source file:de.extra.client.core.model.inputdata.impl.SingleFileInputData.java

@Override
public byte[] getInputDataAsByteArray() {
    InputStream in = null;//from  w w  w .j  av  a2 s. co m
    try {
        // Angepasst. Statt FileUtils.readFileToByteArray prevent
        // outOfMemory
        // FileUtils.readFileToByteArray(inputDataFile); OutOfMemory bei
        // sehr groen Dateien
        in = FileUtils.openInputStream(inputDataFile);
        return IOUtils.toByteArray(in);
    } catch (final IOException ioException) {
        throw new ExtraDataPluginRuntimeException(ioException);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:de.pawlidi.openaletheia.license.LicenseLoaderTest.java

/**
 * Test method for//from  w w  w. j  av a  2  s.c  o  m
 * {@link de.pawlidi.aletheia.license.LicenseLoader#load(java.util.Properties, java.lang.String)}
 * .
 * 
 * @throws IOException
 * @throws LicenseException
 */
@Test
public void testLoadPropertiesString() throws IOException, LicenseException {
    InputStream inputStream = FileUtils.openInputStream(new File("test.license"));
    properties.load(inputStream);
    properties = licenseLoader.load(properties);
    assertTrue(PropertiesUtils.isNotEmpty(properties));
}

From source file:eu.seaclouds.platform.dashboard.model.SeaCloudsApplicationDataStorageTest.java

@Test
public void testGetSeaCloudsApplicationData() throws Exception {
    Yaml yamlParser = new Yaml();
    URL resource = Resources.getResource(TOSCA_DAM_FILE_PATH);
    Map toscaDamMap = (Map) yamlParser.load(FileUtils.openInputStream(new File(resource.getFile())));

    SeaCloudsApplicationData seaCloudsApplicationData = new SeaCloudsApplicationData(toscaDamMap);
    dataStore.addSeaCloudsApplicationData(seaCloudsApplicationData);

    SeaCloudsApplicationData seaCloudsApplicationDataById = dataStore
            .getSeaCloudsApplicationDataById(seaCloudsApplicationData.getSeaCloudsApplicationId());
    assertEquals(seaCloudsApplicationData, seaCloudsApplicationDataById);
}

From source file:com.urbancode.terraform.tasks.vmware.util.GlobalIpAddressPool.java

private Properties parseIpPoolFile() {
    Properties result = new Properties();
    InputStream in = null;//from   w w  w. jav  a2s  . com
    String inputFname = System.getenv("TERRAFORM_HOME") + File.separator + "conf" + File.separator
            + "ippool.conf";
    try {
        in = FileUtils.openInputStream(new File(inputFname));
        result.load(in);
    } catch (IOException e) {
        log.error("Could not read properties from input stream", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // swallow
            }
        }
    }

    return result;
}

From source file:architecture.ee.web.attachment.DefaultAttachmentManager.java

public Attachment createAttachment(int objectType, long objectId, String name, String contentType, File file) {

    AttachmentImpl attachment = new AttachmentImpl();
    attachment.setObjectType(objectType);
    attachment.setObjectId(objectId);//from   w ww .  j  a  v a  2  s  .  c om
    attachment.setName(name);
    attachment.setContentType(contentType);
    attachment.setSize((int) FileUtils.sizeOf(file));
    try {
        attachment.setInputStream(FileUtils.openInputStream(file));
    } catch (IOException e) {
        log.debug(e);
    }
    return attachment;
}

From source file:ddf.camel.component.content.ContentProducer.java

@Override
public void process(Exchange exchange) throws ContentComponentException, ContentFrameworkException {
    LOGGER.debug("ENTERING: process");

    if (!exchange.getPattern().equals(ExchangePattern.InOnly)) {
        return;//from w ww.j  av a  2  s.  co  m
    }

    Message in = exchange.getIn();
    Object body = in.getBody();
    File ingestedFile = null;
    if (body instanceof GenericFile) {
        GenericFile<File> genericFile = (GenericFile<File>) body;
        ingestedFile = (File) genericFile.getFile();
    } else {
        LOGGER.warn("Unable to cast message body to Camel GenericFile, so unable to process ingested file");
        throw new ContentComponentException(
                "Unable to cast message body to Camel GenericFile, so unable to process ingested file");
    }

    if (ingestedFile == null) {
        LOGGER.debug("EXITING: process - ingestedFile is NULL");
        return;
    }

    String operation = in.getHeader(Request.OPERATION, String.class);
    if (StringUtils.isEmpty(operation)) {
        throw new ContentComponentException("Unable to process file " + ingestedFile.getName()
                + "  -  Must specify an operation of create, read, update, or delete");
    }

    String directive = in.getHeader(Request.DIRECTIVE, String.class);
    if (StringUtils.isEmpty(directive)) {
        throw new ContentComponentException("Unable to process file " + ingestedFile.getName()
                + "  -  Must specify a directive of STORE, PROCESS, or STORE_PROCESS");
    }

    String contentUri = (String) in.getHeader(Request.CONTENT_URI, "");

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("operation = " + operation);
        LOGGER.debug("directive = " + directive);
        LOGGER.debug("contentUri = " + contentUri);
    }

    FileInputStream fis = null;
    try {
        fis = FileUtils.openInputStream(ingestedFile);
    } catch (IOException e) {
        throw new ContentComponentException("Unable to open file " + ingestedFile.getName());
    }

    Request.Directive requestDirective = Request.Directive.valueOf(directive);

    String fileExtension = FilenameUtils.getExtension(ingestedFile.getAbsolutePath());

    String mimeType = null;
    if (fileExtension != null) {
        MimeTypeMapper mimeTypeMapper = endpoint.getComponent().getMimeTypeMapper();
        if (mimeTypeMapper != null) {
            try {
                mimeType = mimeTypeMapper.getMimeTypeForFileExtension(fileExtension);
            } catch (MimeTypeResolutionException e) {
                throw new ContentComponentException(e);
            }
        } else {
            LOGGER.error("Did not find a MimeTypeMapper service");
            throw new ContentComponentException(
                    "Unable to find a mime type for the ingested file " + ingestedFile.getName());
        }
    }

    try {
        LOGGER.debug("Preparing content item for mimeType = " + mimeType);

        if (!StringUtils.isEmpty(mimeType)) {
            ContentItem newItem = new IncomingContentItem(fis, mimeType, ingestedFile.getName());
            newItem.setUri(contentUri);

            LOGGER.debug("Creating content item.");

            CreateRequest createRequest = new CreateRequestImpl(newItem, null);
            CreateResponse createResponse = endpoint.getComponent().getContentFramework().create(createRequest,
                    requestDirective);
            ContentItem contentItem = createResponse.getCreatedContentItem();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("content item created with id = " + contentItem.getId());
                LOGGER.debug(contentItem.toString());
            }
        } else {
            LOGGER.debug("mimeType is NULL");
            throw new ContentComponentException(
                    "Unable to determine mime type for the file " + ingestedFile.getName());
        }
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                LOGGER.warn("Unable to close file " + ingestedFile.getName());
            }
        }
    }

    LOGGER.debug("EXITING: process");
}