Example usage for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader

List of usage examples for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader

Introduction

In this page you can find the example usage for org.springframework.core.io DefaultResourceLoader DefaultResourceLoader.

Prototype

public DefaultResourceLoader() 

Source Link

Document

Create a new DefaultResourceLoader.

Usage

From source file:fi.solita.phantomrunner.jetty.PhantomJettyServer.java

public PhantomJettyServer(JavascriptTestInterpreter interpreter, PhantomServerConfiguration serverConfig) {
    // we don't want to see the Jetty logging, disable it
    org.eclipse.jetty.util.log.Log.setLog(new DiscardingJettyLogger());

    this.server = new Server(serverConfig.port());

    this.websocketHandler = new PhantomWebSocketHandler();
    this.websocketHandler.setHandler(createResourceHandler(serverConfig.resourceBase()));
    this.server.setHandler(websocketHandler);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override//from w  w  w  .j  av a  2 s .c  om
        public void run() {
            try {
                PhantomJettyServer.this.stop();
            } catch (Exception e) {
                // oh dear, something evil happened. At this point we are just about to stop the
                // execution of the JVM and thus we really cannot do anything anymore. Just write the
                // exception to log and be sad :(
                log.error("An exception occured while stopping JettyServer", e);
            }
        }
    });

    try {
        this.serverScriptFile = FileUtils.extractResourceToTempDirectory(
                new DefaultResourceLoader().getResource("classpath:jetty-server/jetty-server.js"),
                "jetty-server", true);
    } catch (IOException ioe) {
        throw new RuntimeException("jetty-server.js couldn't be loaded", ioe);
    }
}

From source file:de.viaboxx.flurfunk.bots.camel.CamelBot.java

private ConstrettoConfiguration configureConstretto() {

    InputStream inputStream = this.getClass().getClassLoader()
            .getResourceAsStream("META-INF/maven/de.viaboxx.flurfunk/flurfunk-camelbot/pom.properties");
    if (inputStream != null) {
        System.out.println("==========================");
        System.out.println("Flurfunk C A M E L B O T !");
        System.out.println("==========================");
        System.out.println("http://flurfunk.github.com");
        System.out.println("==========================");
        Properties prop = new Properties();
        try {// w w w  .  j a v  a2  s  .c o  m
            prop.load(inputStream);
            String version = prop.getProperty("version");
            System.out.println("Starting flurfunk-camelbot:" + version);
        } catch (IOException e) {
            System.out.println(
                    "WARNING: No meta information found in this camelbot distribution. Could be it's broken!");
        }
    }

    String propFile = System.getProperty("camelbotProps");
    if (propFile == null) {
        System.out.println(
                "No camelbotProps system property specified. Will look in /etc/camelbot.properties for configuration.");
        propFile = "file:/etc/camelbot.properties";
    } else
        propFile = "file:" + propFile;

    ConstrettoConfiguration config = new ConstrettoBuilder().createPropertiesStore()
            .addResource(new DefaultResourceLoader().getResource("camelbot.properties"))
            .addResource(new DefaultResourceLoader().getResource("camelbot-overrides.properties"))
            .addResource(new DefaultResourceLoader().getResource(propFile)).done().getConfiguration();
    return config;
}

From source file:lichen.orm.LichenOrmModule.java

public static DataSource buildDataSource(@Symbol(LichenOrmSymbols.DATABASE_CFG_FILE) String dbCfgFile,
        RegistryShutdownHub shutdownHub) throws IOException, ProxoolException {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(dbCfgFile);
    Properties info = new Properties();
    info.load(resource.getInputStream());
    PropertyConfigurator.configure(info);

    String poolNameKey = F.flow(info.keySet()).filter(new Predicate<Object>() {
        public boolean accept(Object element) {
            return element.toString().contains("alias");
        }/*from   w ww .  j a  v a 2 s .  c  o  m*/
    }).first().toString();

    if (poolNameKey == null) {
        throw new RuntimeException("?poolName");
    }
    final String poolName = info.getProperty(poolNameKey);

    //new datasource
    ProxoolDataSource ds = new ProxoolDataSource(poolName);
    //register to shutdown
    shutdownHub.addRegistryShutdownListener(new RegistryShutdownListener() {
        public void registryDidShutdown() {
            Flow<?> flow = F.flow(ProxoolFacade.getAliases()).filter(new Predicate<String>() {
                public boolean accept(String element) {
                    return element.equals(poolName);
                }
            });
            if (flow.count() == 1) {
                try {
                    ProxoolFacade.removeConnectionPool(poolName);
                } catch (ProxoolException e) {
                    //do nothing
                }
            }
        }
    });
    return ds;
}

From source file:com.ofbizian.infinispan.AtomikosJtaConfiguration.java

private void executeScript(Connection connection, String location) {
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
    populator.addScript(resourceLoader.getResource(location));
    try {//from   w ww. j a v  a  2  s . co  m
        populator.populate(connection);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.devnexus.ting.DefaultApplicationContextInitializer.java

@Override
public void initialize(ConfigurableApplicationContext applicationContext) {

    final CloudEnvironment env = new CloudEnvironment();
    if (env.getInstanceInfo() != null) {
        LOGGER.info("Running in the cloud - API: " + env.getCloudApiUri());
        applicationContext.getEnvironment().setActiveProfiles(SpringProfile.CLOUD);
    } else {//from  w ww .j av  a2  s . c  o m

        final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation();
        SpringContextMode springContextMode;

        LOGGER.info("DevNexus Apphome: " + apphome);

        if (SystemInformationUtils.existsConfigFile(apphome.getAppHomePath())) {
            springContextMode = SpringContextMode.ProductionContextConfiguration;
        } else {
            springContextMode = SpringContextMode.DemoContextConfiguration;
        }

        applicationContext.getEnvironment().setActiveProfiles(springContextMode.getCode());
    }

    final ConfigurableEnvironment environment = applicationContext.getEnvironment();

    if (environment.acceptsProfiles(SpringProfile.STANDALONE)) {
        final String tingHome = environment.getProperty(Apphome.APP_HOME_DIRECTORY);
        final PropertySource<?> propertySource;
        final YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();

        final String productionPropertySourceLocation;
        final Apphome apphome = SystemInformationUtils.retrieveBasicSystemInformation();
        if (apphome.getAppHomeSource() == AppHomeSource.USER_DIRECTORY) {
            productionPropertySourceLocation = "file:" + apphome.getAppHomePath() + File.separator
                    + SystemInformationUtils.TING_CONFIG_FILENAME;
        } else {
            productionPropertySourceLocation = "file:" + tingHome + File.separator
                    + SystemInformationUtils.TING_CONFIG_FILENAME;
        }

        try {
            propertySource = yamlPropertySourceLoader.load("devnexus-standalone",
                    new DefaultResourceLoader().getResource(productionPropertySourceLocation), null);
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to get ResourcePropertySource '" + productionPropertySourceLocation + "'", e);
        }
        environment.getPropertySources().addFirst(propertySource);
        LOGGER.info("Properties for standalone mode loaded [" + productionPropertySourceLocation + "].");
    } else {
        LOGGER.info("Using Properties for demo mode.");
    }

    final String emailProviderAsString = environment.getProperty("devnexus.mail.emailProvider");
    final EmailProvider emailProvider = EmailProvider.valueOf(emailProviderAsString.trim().toUpperCase());
    final boolean twitterEnabled = environment.getProperty("devnexus.twitter.enabled", Boolean.class,
            Boolean.FALSE);
    final boolean websocketEnabled = environment.getProperty("devnexus.websocket.enabled", Boolean.class,
            Boolean.FALSE);
    final boolean payPalEnabled = environment.containsProperty("PAYPAL_MODE");

    LOGGER.info("Uses Settings:" + "\nEmail Provider: " + emailProvider + "\nTwitter Enabled: " + twitterEnabled
            + "\nPayPal Enabled: " + payPalEnabled + "\nWebsocket Enabled: " + websocketEnabled);

    if (EmailProvider.SENDGRID.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.SENDGRID_ENABLED);
    } else if (EmailProvider.SMTP.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.SMTP_ENABLED);
    } else if (EmailProvider.AMAZON_SES.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.AMAZON_SES_ENABLED);
    } else if (EmailProvider.NONE.equals(emailProvider)) {
    } else {
        throw new IllegalArgumentException("Unknown EmailProvider: " + emailProvider);
    }

    if (!EmailProvider.NONE.equals(emailProvider)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.MAIL_ENABLED);
    }

    if (twitterEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.TWITTER_ENABLED);
    }
    if (websocketEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.WEBSOCKET_ENABLED);
    }
    if (payPalEnabled) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_ENABLED);
        switch (environment.getProperty("PAYPAL_MODE")) {
        case "live":
            applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_LIVE);
            break;
        default:
            applicationContext.getEnvironment().addActiveProfile(SpringProfile.PAYPAL_SANDBOX);
            break;
        }
    }
    if (environment.getProperty("DEVELOPMENT_MODE", Boolean.class, Boolean.FALSE)) {
        applicationContext.getEnvironment().addActiveProfile(SpringProfile.DEVELOPMENT_ENABLED);
    }
}

From source file:org.cfr.capsicum.test.AbstractSimpleCayenneJUnitTests.java

@SuppressWarnings("unchecked")
protected ICayenneRuntimeContext createCayenneContext() throws Exception {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    ServerRuntimeFactoryBean factory = new ServerRuntimeFactoryBean();
    factory.setDefaultSchemaUpdateStrategy(
            (Class<SchemaUpdateStrategy>) (overrideStrategy != null ? overrideStrategy
                    : CreateIfNoSchemaStrategy.class));
    factory.setDataSource(createDatasource());
    DataDomainDefinition dataDomainDefinition = new DataDomainDefinition();
    dataDomainDefinition.setName(domainName);
    dataDomainDefinition.setDomainResource(resourceLoader.getResource(domainFileLocation));
    factory.setDataDomainDefinitions(Lists.newArrayList(dataDomainDefinition));
    factory.afterPropertiesSet();//from w ww . jav a  2  s. co  m
    return factory;
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS.//from   ww w  . ja va  2s  .com
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:se.vgregion.alfresco.repo.content.transform.JodContentTransformer.java

@Override
public void afterPropertiesSet() throws Exception {
    // load the document conversion configuration
    if (this.documentFormatsConfiguration != null) {
        final DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        try {//  w w  w . ja va 2s.c o m
            final InputStream is = resourceLoader.getResource(this.documentFormatsConfiguration)
                    .getInputStream();
            this.formatRegistry = new JooReportsXmlDocumentFormatRegistryAdapter(is);
            // We do not need to explicitly close this InputStream as it is closed
            // for us within the XmlDocumentFormatRegistry
        } catch (final IOException e) {
            throw new AlfrescoRuntimeException(
                    "Unable to load document formats configuration file: " + this.documentFormatsConfiguration);
        }
    } else {
        this.formatRegistry = new JooReportsXmlDocumentFormatRegistryAdapter();
    }
}

From source file:org.obiba.mica.security.SecurityManagerFactory.java

private String getShiroIniPath() {
    try {// w w  w  . ja  v a2  s .  com
        return new DefaultResourceLoader().getResource("classpath:/shiro.ini").getFile().getAbsolutePath();
    } catch (IOException e) {
        throw new RuntimeException("Cannot load shiro.ini", e);
    }
}

From source file:com.processpuzzle.application.domain.Application.java

protected Application(String configurationDescriptorPath) {
    this(configurationDescriptorPath, new DefaultResourceLoader());
}