Example usage for org.springframework.core.io ClassPathResource getInputStream

List of usage examples for org.springframework.core.io ClassPathResource getInputStream

Introduction

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

Prototype

@Override
public InputStream getInputStream() throws IOException 

Source Link

Document

This implementation opens an InputStream for the given class path resource.

Usage

From source file:org.alfresco.repo.workflow.WorkflowDeployer.java

/**
 * Deploy the Workflow Definitions/* ww w  .  j  av  a2  s.  c  om*/
 */
public void init() {
    PropertyCheck.mandatory(this, "transactionService", transactionService);
    PropertyCheck.mandatory(this, "authenticationContext", authenticationContext);
    PropertyCheck.mandatory(this, "workflowService", workflowService);

    String currentUser = authenticationContext.getCurrentUserName();
    if (currentUser == null) {
        authenticationContext.setSystemUserAsCurrentUser();
    }
    if ((!transactionService.getAllowWrite())
            && (AlfrescoTransactionSupport.getTransactionReadState() != TxnReadState.TXN_READ_WRITE)) {
        if (logger.isWarnEnabled())
            logger.warn("Repository is in read-only mode; not deploying workflows.");

        return;
    }

    UserTransaction userTransaction = transactionService.getUserTransaction();
    try {
        userTransaction.begin();

        // bootstrap the workflow models and static labels (from classpath)
        if (models != null && resourceBundles != null
                && ((models.size() > 0) || (resourceBundles.size() > 0))) {
            DictionaryBootstrap dictionaryBootstrap = new DictionaryBootstrap();
            dictionaryBootstrap.setDictionaryDAO(dictionaryDAO);
            dictionaryBootstrap.setTenantService(tenantService);
            dictionaryBootstrap.setModels(models);
            dictionaryBootstrap.setLabels(resourceBundles);
            dictionaryBootstrap.bootstrap(); // also registers with dictionary

            // MNT-10537 fix, since new model was deployed we need to destroy dictionary to force lazy re-init 
            AlfrescoTransactionSupport.bindListener(this.workflowDeployerTransactionListener);
        }

        // bootstrap the workflow definitions (from classpath)
        if (workflowDefinitions != null) {
            for (Properties workflowDefinition : workflowDefinitions) {
                // retrieve workflow specification
                String engineId = workflowDefinition.getProperty(ENGINE_ID);
                if (engineId == null || engineId.length() == 0) {
                    throw new WorkflowException("Workflow Engine Id must be provided");
                }

                String location = workflowDefinition.getProperty(LOCATION);
                if (location == null || location.length() == 0) {
                    throw new WorkflowException("Workflow definition location must be provided");
                }

                if (workflowAdminService.isEngineEnabled(engineId)) {
                    Boolean redeploy = Boolean.valueOf(workflowDefinition.getProperty(REDEPLOY));
                    String mimetype = workflowDefinition.getProperty(MIMETYPE);

                    // retrieve input stream on workflow definition
                    ClassPathResource workflowResource = new ClassPathResource(location);

                    // deploy workflow definition
                    if (!redeploy && workflowService.isDefinitionDeployed(engineId,
                            workflowResource.getInputStream(), mimetype)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Workflow deployer: Definition '" + location + "' already deployed");
                    } else {
                        WorkflowDeployment deployment = workflowService.deployDefinition(engineId,
                                workflowResource.getInputStream(), mimetype, workflowResource.getFilename());
                        logDeployment(location, deployment);
                    }
                } else {
                    if (logger.isDebugEnabled())
                        logger.debug("Workflow deployer: Definition '" + location + "' not deployed as the '"
                                + engineId + "' engine is disabled");
                }
            }
        }

        // deploy workflow definitions from repository (if any)
        if (repoWorkflowDefsLocation != null) {
            StoreRef storeRef = repoWorkflowDefsLocation.getStoreRef();
            NodeRef rootNode = nodeService.getRootNode(storeRef);
            List<NodeRef> nodeRefs = searchService
                    .selectNodes(rootNode,
                            repoWorkflowDefsLocation.getPath() + CRITERIA_ALL + "["
                                    + defaultSubtypeOfWorkflowDefinitionType + "]",
                            null, namespaceService, false);

            if (nodeRefs.size() > 0) {
                for (NodeRef nodeRef : nodeRefs) {
                    deploy(nodeRef, false);
                }
            }
        }

        userTransaction.commit();
    } catch (Throwable e) {
        // rollback the transaction
        try {
            if (userTransaction != null) {
                userTransaction.rollback();
            }
        } catch (Exception ex) {
            // NOOP 
        }
        throw new AlfrescoRuntimeException("Workflow deployment failed", e);
    } finally {
        if (currentUser == null) {
            authenticationContext.clearCurrentSecurityContext();
        }
    }
}

From source file:org.alfresco.repo.workflow.WorkflowReportServiceImpl.java

/**
 * Gets the cache size from config or fallback to default of
 * {@value #MAX_CACHE_SIZE}/*from  w  ww  . jav a 2s  . c  om*/
 *
 * @return the cache size
 */
private int getCacheSize() {
    int size = MAX_CACHE_SIZE;
    try {
        ClassPathResource globalProps = new ClassPathResource("alfresco-global.properties");
        Properties globalProperties = new Properties();
        globalProperties.load(globalProps.getInputStream());
        Object object = globalProperties.get("cache.inmemory.task.size");
        if (object != null) {
            size = Integer.valueOf(object.toString());
        }
    } catch (Exception e) {
        throw new SEIPRuntimeException("Fail to config task cache size!", e);
    }
    return size;
}

From source file:org.aon.esolutions.appconfig.client.web.SystemPropertiesListener.java

private void loadPropsFromClasspath(ServletContext sc) {
    String propertiesLocationProp = sc.getInitParameter("classpath.file.location");

    Properties systemProps = System.getProperties();
    Properties loadedProps = new Properties();
    ClassPathResource appConfigResource = new ClassPathResource(propertiesLocationProp);
    if (appConfigResource.exists()) {

        try {/* ww w .  j  av a  2s.c o  m*/
            loadedProps.load(appConfigResource.getInputStream());

            for (Map.Entry<Object, Object> e : loadedProps.entrySet()) {
                if (systemProps.containsKey(e.getKey()) == false)
                    systemProps.put(e.getKey(), e.getValue());
            }
        } catch (Exception e) {
            logger.error("Error loading properties", e);
        }
    }
}

From source file:org.broadleafcommerce.common.file.service.BroadleafFileServiceImpl.java

@Override
public InputStream getClasspathResource(String name) {
    try {/*from w w w  .  j  a v a  2s.co  m*/
        ClassPathResource resource = lookupResourceOnClassPath(name);
        if (resource != null && resource.exists()) {
            InputStream assetFile = resource.getInputStream();
            BufferedInputStream bufferedStream = new BufferedInputStream(assetFile);

            // Wrapping the buffered input stream with a globally shared stream allows us to 
            // vary the way the file names are generated on the file system.    
            // This benefits us (mainly in our demo site but their could be other uses) when we
            // have assets that are shared across sites that we also need to resize. 
            GloballySharedInputStream globallySharedStream = new GloballySharedInputStream(bufferedStream);
            globallySharedStream.mark(0);
            return globallySharedStream;
        } else {
            return null;
        }
    } catch (Exception e) {
        LOG.error("Error getting resource from classpath", e);
    }
    return null;
}

From source file:org.cloudfoundry.identity.uaa.metrics.UaaMetricsFilter.java

public List<UrlGroup> getUrlGroups() throws IOException {
    ClassPathResource resource = new ClassPathResource("performance-url-groups.yml");
    Yaml yaml = new Yaml();
    List<Map<String, Object>> load = (List<Map<String, Object>>) yaml.load(resource.getInputStream());
    return load.stream().map(map -> UrlGroup.from(map)).collect(Collectors.toList());
}

From source file:org.deeplearning4j.plot.dropwizard.RenderApplication.java

public static void main(String[] args) throws Exception {
    ClassPathResource resource = new ClassPathResource("/render/dropwizard.yml");
    InputStream is = resource.getInputStream();
    File tmpConfig = new File("dropwizard-render.yml");
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpConfig));
    IOUtils.copy(is, bos);// w  w w .java  2s. c o  m
    bos.flush();
    bos.close();
    is.close();
    tmpConfig.deleteOnExit();
    new RenderApplication().run("server", tmpConfig.getAbsolutePath());
}

From source file:org.easycloud.las.core.util.Resources.java

/**
 * If the passed file name contains directory info, load it
 * directly. Else, a bare file name with no directory info,
 * try to load it as a resource on the system class path
 *
 * @param fileName the name of the file to be loaded
 * @return all the properties in the file
 *//*from   w  ww .java2s  .  co m*/
public static Properties loadProperties(String fileName) {
    Properties props = new Properties();
    InputStream fis = null;
    try {
        if (StringUtils.isNotEmpty(fileName)) {
            if (fileName.contains(File.separator)) {
                fis = new FileInputStream(new File(fileName));
                props.load(fis);
                fis.close();
            } else {
                ClassPathResource res = new ClassPathResource(fileName);
                fis = res.getInputStream();
                props.load(fis);
            }
            Iterator itr = props.entrySet().iterator();
            while (itr.hasNext()) {
                Entry e = (Entry) itr.next();
                e.setValue(e.getValue().toString().trim());
            }
        }
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(e.getMessage(), e);
        }
        throw new FileOperationsException("Failed to load " + fileName, e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
    }
    return props;
}

From source file:org.fracturedatlas.athena.admin.AthenaAdmin.java

public static void main(String[] args) {

    Console c = System.console();
    if (c == null) {
        System.exit(1);//w  w w.  j  a v  a2s.  com
    }

    Properties props = new Properties();
    ClassPathResource cpr = new ClassPathResource("admin.properties");
    try {
        InputStream in = cpr.getInputStream();
        props.load(in);
        in.close();
    } catch (Exception e) {
        c.format("Could not read properties file admin.properties\n");
        System.exit(1);
    }

    ApplicationContext context = new ClassPathXmlApplicationContext("security.xml");
    JdbcUserDetailsManager userDao = (JdbcUserDetailsManager) context.getBean("userDao");
    Md5PasswordEncoder encoder = (Md5PasswordEncoder) context.getBean("passwordEncoder");

    //TODO: Props file
    String realmName = props.getProperty("athena.admin.realm");

    if (args.length == 0) {
        System.out.println("USAGE: admin [command]");
        System.out.println("Where [command] is one of: create-user");
        System.exit(1);
    }

    Boolean usernameGood = false;
    String login = null;
    while (!usernameGood) {
        login = c.readLine("Enter new username: ");
        if (StringUtils.isBlank(login)) {
            c.format("username cannot be blank, please try again\n");
        } else {
            usernameGood = true;
        }
    }
    Boolean match = false;
    char[] password = null;
    char[] confirmedPassword = null;
    while (!match) {
        password = c.readPassword("Enter password: ");
        confirmedPassword = c.readPassword("Enter password again: ");
        match = Arrays.equals(password, confirmedPassword);
        if (!match) {
            c.format("Passwords do not match please try again\n");
        }
    }

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl("ROLE_CLIENT_APPLICATION"));
    String clearPassword = new String(password);
    String saltedClearPassword = login + ":" + realmName + ":" + clearPassword;
    String encryptedPassword = encoder.encodePassword(saltedClearPassword, null);
    User user = new User(login, encryptedPassword, true, true, true, true, authorities);
    try {
        userDao.createUser(user);
    } catch (org.springframework.dao.DuplicateKeyException dke) {
        System.out.println("Username [" + user.getUsername() + "] already exists.");
        System.exit(1);
    }

    System.out.println("Successfully created [" + user.getUsername() + "]");
}

From source file:org.jtalks.jcommune.service.nontransactional.ImageService.java

/**
 * Gets content of the file by its classpath
 *
 * @param classPath classpath of the file to be loaded
 * @return content of the loaded file//from w w  w .j a  v  a 2s . c o m
 * @throws IOException
 */
private byte[] getFileBytes(String classPath) throws IOException {
    byte[] result;
    ClassPathResource fileClassPathSource = new ClassPathResource(classPath);
    InputStream stream = null;
    try {
        stream = fileClassPathSource.getInputStream();
        result = new byte[stream.available()];
        Validate.isTrue(stream.read(result) > 0);
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return result;
}

From source file:org.kuali.ext.mm.TestDataPreparator.java

/**
 * load properties from the given class path resource. The class path is different than the absolute path. If a resource is
 * located at /project/test/org/kuali/kfs/util/message.properties, then its class path is org/kuali/kfs/util/message.properties,
 * which is the fully-qualified Java package name plus the resource name.
 * //from  w w  w .j  av  a  2s  .  c  om
 * @param classPath the given class path of a resource
 * @return properties loaded from the given resource.
 */
public static Properties loadPropertiesFromClassPath(String classPath) {
    ClassPathResource classPathResource = new ClassPathResource(classPath);

    Properties properties = new Properties();
    try {
        properties.load(classPathResource.getInputStream());
    } catch (IOException e) {
        throw new RuntimeException("Invalid class path: " + classPath + e);
    }

    return properties;
}