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.wrml.mojo.schema.builder.SchemaBuilderMojo.java

private void generateJsonSchema(File sourceFile) throws IOException, ClassNotFoundException {

    getLog().info("Working: " + sourceFile.getAbsolutePath());
    SchemaLoader loader = _Engine.getContext().getSchemaLoader();
    InputStream in = FileUtils.openInputStream(sourceFile);
    JsonSchemaLoader jsonSchemaLoader = loader.getJsonSchemaLoader();
    JsonSchema jsonSchema = jsonSchemaLoader.load(in, createModelUri(sourceFile, _RootJsonSchemaUri));
    Schema schema = loader.load(jsonSchema);
    Class<?> classz = loader.getSchemaInterface(schema.getUri());
    getLog().info("Created: " + classz.getName());
}

From source file:org.wrml.runtime.EngineConfiguration.java

public final static EngineConfiguration load(final File fileOrDirectory) throws IOException {

    File configFile = fileOrDirectory;

    if (fileOrDirectory == null) {
        // Check the system property
        String fileName = PropertyUtil.getSystemProperty(WRML_CONFIGURATION_FILE_PATH_PROPERTY_NAME);
        if (fileName != null) {
            configFile = FileUtils.getFile(fileName);
        } else {/*from   w  ww .j a v  a  2 s.c o m*/
            // Look in the local directory for the configuration file with the default name
            configFile = FileUtils.getFile(new File("."), DEFAULT_WRML_CONFIGURATION_FILE_NAME);

            if (!configFile.exists()) {
                configFile = FileUtils.getFile(FileUtils.getUserDirectory(),
                        DEFAULT_WRML_CONFIGURATION_FILE_NAME);
            }
        }
    } else if (fileOrDirectory.isDirectory()) {
        // Named a directory (assume default file name)
        configFile = FileUtils.getFile(fileOrDirectory, DEFAULT_WRML_CONFIGURATION_FILE_NAME);
    }

    if (!configFile.exists()) {
        throw new FileNotFoundException("The path \"" + configFile.getAbsolutePath() + "\" does not exist.");
    }

    LOGGER.trace("loading EngineConfiguration from  '{}'...", configFile);
    final InputStream in = FileUtils.openInputStream(configFile);
    final EngineConfiguration config = EngineConfiguration.load(in);
    IOUtils.closeQuietly(in);
    LOGGER.debug("loaded EngineConfiguration from  '{}'", configFile);
    return config;
}

From source file:org.wrml.runtime.format.application.schema.json.JsonSchemaLoader.java

public JsonSchema load(final File file) throws IOException {

    if (file == null) {
        throw new FileNotFoundException("The JSON schema file is null.");
    }//from   ww w  .  j  a v a  2 s .c om

    if (!file.exists()) {
        throw new FileNotFoundException(
                "The JSON schema file named \"" + file.getAbsolutePath() + "\" does not exist.");
    }

    final InputStream in = FileUtils.openInputStream(file);
    final JsonSchema jsonSchema = load(in, null);
    IOUtils.closeQuietly(in);
    return jsonSchema;
}

From source file:org.wrml.runtime.service.file.FileSystemService.java

@Override
public Model get(final Keys keys, final Dimensions dimensions) {

    if (keys == null) {
        final ServiceException e = new ServiceException("The keys cannot be null.", null, this);
        LOG.error(e.getMessage(), e);//from   w  w w  .  j  ava 2 s  .c  o m
        throw e;
    }

    if (dimensions == null) {
        final ServiceException e = new ServiceException("The dimensions cannot be null.", null, this);
        LOG.error(e.getMessage(), e);
        throw e;
    }

    final File file = getDataFile(keys);

    if (file == null) {
        return null;
    }

    InputStream in;
    try {
        in = FileUtils.openInputStream(file);
    } catch (final Exception e) {
        throw new ServiceException("Failed to open stream content.", e, this);
    }

    final Context context = getContext();
    final Model model;
    try {
        model = context.readModel(in, keys, dimensions, _FileFormatUri);
    } catch (final ModelFormattingException e) {
        throw new ServiceException("Failed to read model.", e, this);
    } finally {
        IOUtils.closeQuietly(in);
    }

    if (model instanceof Filed) {
        ((Filed) model).setFile(file);
    }

    return model;

}

From source file:org.wso2.carbon.apimgt.hybrid.gateway.usage.publisher.dao.UploadedUsageFileInfoDAOTest.java

private static void initializeDatabase(String configFilePath) {
    InputStream in;/* w w w. ja v a 2 s .c om*/
    try {
        in = FileUtils.openInputStream(new File(configFilePath));
        StAXOMBuilder builder = new StAXOMBuilder(in);
        String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
                .getText();
        OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
        String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
        String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
        String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
        String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriver);
        basicDataSource.setUrl(databaseURL);
        basicDataSource.setUsername(databaseUser);
        basicDataSource.setPassword(databasePass);

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        try {
            InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
        } catch (NamingException e) {
            InitialContext ic = new InitialContext();
            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");
            ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
        }
    } catch (XMLStreamException | IOException | NamingException e) {
        log.error(e);
    }
}

From source file:org.wso2.carbon.apimgt.impl.APIManagerConfiguration.java

/**
 * Populate this configuration by reading an XML file at the given location. This method
 * can be executed only once on a given APIManagerConfiguration instance. Once invoked and
 * successfully populated, it will ignore all subsequent invocations.
 *
 * @param filePath Path of the XML descriptor file
 * @throws APIManagementException If an error occurs while reading the XML descriptor
 *//*  ww w .j  av  a 2s. c om*/
public void load(String filePath) throws APIManagementException {
    if (initialized) {
        return;
    }
    InputStream in = null;
    int offset = APIUtil.getPortOffset();
    int receiverPort = 9611 + offset;
    int authUrlPort = 9711 + offset;
    int jmsPort = 5672 + offset;
    System.setProperty(RECEIVER_URL_PORT, "" + receiverPort);
    System.setProperty(AUTH_URL_PORT, "" + authUrlPort);
    System.setProperty(JMS_PORT, "" + jmsPort);
    try {
        in = FileUtils.openInputStream(new File(filePath));
        StAXOMBuilder builder = new StAXOMBuilder(in);
        secretResolver = SecretResolverFactory.create(builder.getDocumentElement(), true);
        readChildElements(builder.getDocumentElement(), new Stack<String>());
        initialized = true;
        addKeyManagerConfigsAsSystemProperties();
        String url = getFirstProperty(APIConstants.API_KEY_VALIDATOR_URL);
        if (url == null) {
            log.error("API_KEY_VALIDATOR_URL is null");
        }
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new APIManagementException(
                "I/O error while reading the API manager " + "configuration: " + filePath, e);
    } catch (XMLStreamException e) {
        log.error(e.getMessage());
        throw new APIManagementException("Error while parsing the API manager " + "configuration: " + filePath,
                e);
    } catch (OMException e) {
        log.error(e.getMessage());
        throw new APIManagementException("Error while parsing API Manager configuration: " + filePath, e);
    } catch (Exception e) {
        log.error(e.getMessage());
        throw new APIManagementException("Unexpected error occurred while parsing configuration: " + filePath,
                e);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:org.wso2.carbon.apimgt.impl.dao.test.APIMgtDAOTest.java

private void initializeDatabase(String configFilePath) {

    InputStream in = null;/* ww  w. j  a va  2  s .  c o m*/
    try {
        in = FileUtils.openInputStream(new File(configFilePath));
        StAXOMBuilder builder = new StAXOMBuilder(in);
        String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
                .getText();
        OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
        String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
        String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
        String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
        String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(databaseDriver);
        basicDataSource.setUrl(databaseURL);
        basicDataSource.setUsername(databaseUser);
        basicDataSource.setPassword(databasePass);

        // Create initial context
        System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
        System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
        try {
            InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
        } catch (NamingException e) {
            InitialContext ic = new InitialContext();
            ic.createSubcontext("java:");
            ic.createSubcontext("java:/comp");
            ic.createSubcontext("java:/comp/env");
            ic.createSubcontext("java:/comp/env/jdbc");

            ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
        }
    } catch (XMLStreamException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.apimgt.impl.dao.test.CertificateMgtDaoTest.java

private static void initializeDatabase(String configFilePath)
        throws IOException, XMLStreamException, NamingException {

    InputStream in;//ww w .  j a  va2 s .c  om
    in = FileUtils.openInputStream(new File(configFilePath));
    StAXOMBuilder builder = new StAXOMBuilder(in);
    String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName"))
            .getText();
    OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database"));
    String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText();
    String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText();
    String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText();
    String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText();

    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(databaseDriver);
    basicDataSource.setUrl(databaseURL);
    basicDataSource.setUsername(databaseUser);
    basicDataSource.setPassword(databasePass);

    // Create initial context
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
    System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming");
    try {
        InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB");
    } catch (NamingException e) {
        InitialContext ic = new InitialContext();
        ic.createSubcontext("java:");
        ic.createSubcontext("java:/comp");
        ic.createSubcontext("java:/comp/env");
        ic.createSubcontext("java:/comp/env/jdbc");

        ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource);
    }
}

From source file:org.wso2.carbon.apimgt.impl.internal.APIManagerComponent.java

private void addTierPolicy(String tierLocation, String defaultTierFileName) throws APIManagementException {

    File defaultTiers = new File(defaultTierFileName);
    if (!defaultTiers.exists()) {
        log.info("Default tier policies not found in : " + defaultTierFileName);
        return;//from   www.ja  v a2  s.com
    }

    RegistryService registryService = ServiceReferenceHolder.getInstance().getRegistryService();
    InputStream inputStream = null;
    try {
        UserRegistry registry = registryService.getGovernanceSystemRegistry();
        if (registry.resourceExists(tierLocation)) {
            log.debug("Tier policies already uploaded to the registry");
            return;
        }

        log.debug("Adding API tier policies to the registry");

        inputStream = FileUtils.openInputStream(defaultTiers);
        byte[] data = IOUtils.toByteArray(inputStream);
        Resource resource = registry.newResource();
        resource.setContent(data);

        registry.put(tierLocation, resource);
    } catch (RegistryException e) {
        throw new APIManagementException("Error while saving policy information to the registry", e);
    } catch (IOException e) {
        throw new APIManagementException("Error while reading policy file content", e);
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.error("Error when closing input stream", e);
            }
        }
    }
}

From source file:project.cs.lisa.application.html.NetInfWebViewClient.java

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

    Intent intent = new Intent(MainApplicationActivity.SEARCH_TRANSMISSION);
    MainApplicationActivity.getActivity().sendBroadcast(intent);

    if (!URLUtil.isHttpUrl(url)) {
        super.shouldInterceptRequest(view, url);
        return null;

    } else if (URLUtil.isHttpUrl(url)) {
        WebObject resource = null;/*from  w w w .j  a va  2  s .  c o  m*/
        File file = null;
        String contentType = null;
        String hash = null;
        // Get and publish resource
        try {

            // Search for url
            NetInfSearchResponse searchResponse = search(url);

            // Get url data
            hash = selectHash(searchResponse);

            NetInfRetrieveResponse retrieveResponse = retrieve(hash);
            file = retrieveResponse.getFile();
            contentType = retrieveResponse.getContentType();

        } catch (Exception e1) {
            Log.e(TAG, "Request for resource failed. Downloading from uplink.");

            resource = downloadResource(url);
            if (resource == null) {
                return null;
            }

            file = resource.getFile();
            contentType = resource.getContentType();
            hash = resource.getHash();
        }

        // Publish
        try {
            if (shouldPublish()) {
                publish(file, new URL(url), hash, contentType);
            }
        } catch (MalformedURLException e1) {
            Log.e(TAG, "Malformed url. Can't publish file.");
        }

        // Creating the resource that will be used by the webview
        WebResourceResponse response = null;
        try {
            response = new WebResourceResponse(contentType, "base64", FileUtils.openInputStream(file));
        } catch (IOException e) {
            Log.e("TAG", "Could not open file");
        }

        System.gc();
        return response;
    } else {
        Log.e(TAG, "Unexpected url while intercepting resources.");
        return super.shouldInterceptRequest(view, url);
    }
}