Example usage for org.springframework.core.io Resource getFilename

List of usage examples for org.springframework.core.io Resource getFilename

Introduction

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

Prototype

@Nullable
String getFilename();

Source Link

Document

Determine a filename for this resource, i.e.

Usage

From source file:org.grails.web.mapping.DefaultUrlMappingEvaluator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public List evaluateMappings(Resource resource) {
    InputStream inputStream = null;
    try {//from w  w  w . j a  v a  2s  . c o  m
        inputStream = resource.getInputStream();
        return evaluateMappings(classLoader.parseClass(IOGroovyMethods.getText(inputStream, "UTF-8")));
    } catch (IOException e) {
        throw new UrlMappingException(
                "Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.jahia.services.importexport.ImportExportBaseService.java

/**
 * Import a full site zip into a newly created site.
 * <p/>// ww w  .j  a  va  2s  .c  om
 * zip file can contain all kind of legacy jahia import files or jcr import format.
 *
 * @param file                      Zip file
 * @param site                      The new site where to import
 * @param infos                     site infos
 * @param legacyMappingFilePath     path to the legacy mappings
 * @param legacyDefinitionsFilePath path for the legacy definitions
 * @param session                   the current JCR session to use for the import
 * @throws RepositoryException
 * @throws IOException
 */
public void importSiteZip(Resource file, JahiaSite site, Map<Object, Object> infos,
        Resource legacyMappingFilePath, Resource legacyDefinitionsFilePath, JCRSessionWrapper session)
        throws RepositoryException, IOException {
    long timerSite = System.currentTimeMillis();
    logger.info("Start import for site {}", site != null ? site.getSiteKey() : "");

    final CategoriesImportHandler categoriesImportHandler = new CategoriesImportHandler();
    final UsersImportHandler usersImportHandler = new UsersImportHandler(site, session);

    boolean legacyImport = false;
    List<String[]> catProps = null;
    List<String[]> userProps = null;

    Map<String, Long> sizes = new HashMap<String, Long>();
    List<String> fileList = new ArrayList<String>();

    logger.info("Start analyzing import file {}", file);
    long timer = System.currentTimeMillis();
    getFileList(file, sizes, fileList);
    logger.info("Done analyzing import file {} in {}", file,
            DateUtils.formatDurationWords(System.currentTimeMillis() - timer));

    Map<String, String> pathMapping = session.getPathMapping();
    for (JahiaTemplatesPackage pkg : templatePackageRegistry.getRegisteredModules().values()) {
        String key = "/modules/" + pkg.getId() + "/";
        if (!pathMapping.containsKey(key)) {
            pathMapping.put(key, "/modules/" + pkg.getId() + "/" + pkg.getVersion() + "/");
        }
    }

    ZipInputStream zis;
    if (sizes.containsKey(USERS_XML)) {
        // Import users first
        zis = getZipInputStream(file);
        try {
            while (true) {
                ZipEntry zipentry = zis.getNextEntry();
                if (zipentry == null)
                    break;
                String name = zipentry.getName();
                if (name.equals(USERS_XML)) {
                    userProps = importUsers(zis, usersImportHandler);
                    break;
                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }
    }

    // Check if it is an 5.x or 6.1 import :
    for (Map.Entry<String, Long> entry : sizes.entrySet()) {
        if (entry.getKey().startsWith("export_")) {
            legacyImport = true;
            break;
        }
    }

    if (sizes.containsKey(SITE_PROPERTIES)) {
        zis = getZipInputStream(file);
        try {
            while (true) {
                ZipEntry zipentry = zis.getNextEntry();
                if (zipentry == null)
                    break;
                String name = zipentry.getName();
                if (name.equals(SITE_PROPERTIES)) {
                    importSiteProperties(zis, site, session);
                    break;
                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }
    }

    if (sizes.containsKey(REPOSITORY_XML)) {
        // Parse import file to detect sites
        zis = getZipInputStream(file);
        try {
            while (true) {
                ZipEntry zipentry = zis.getNextEntry();
                if (zipentry == null)
                    break;
                String name = zipentry.getName();
                if (name.equals(REPOSITORY_XML)) {
                    timer = System.currentTimeMillis();
                    logger.info("Start importing " + REPOSITORY_XML);

                    DocumentViewValidationHandler h = new DocumentViewValidationHandler();
                    h.setSession(session);
                    List<ImportValidator> validators = new ArrayList<ImportValidator>();
                    SitesValidator sitesValidator = new SitesValidator();
                    validators.add(sitesValidator);
                    h.setValidators(validators);
                    handleImport(zis, h, name);

                    Map<String, Properties> sites = ((SitesValidatorResult) sitesValidator.getResult())
                            .getSitesProperties();
                    for (String s : sites.keySet()) {
                        // Only the first site returned is mapped (if its not the systemsite, which is always the same key)
                        if (!s.equals("systemsite") && !site.getSiteKey().equals("systemsite")) {
                            // Map to the new sitekey
                            pathMapping.put("/sites/" + s + "/", "/sites/" + site.getSiteKey() + "/");
                            break;
                        }
                    }

                    if (!sizes.containsKey(SITE_PROPERTIES)) {
                        // todo : site properties can be removed and properties get from here
                    }
                    logger.info("Done importing " + REPOSITORY_XML + " in {}",
                            DateUtils.formatDurationWords(System.currentTimeMillis() - timer));
                    break;
                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }

        importZip(null, file, DocumentViewImportHandler.ROOT_BEHAVIOUR_IGNORE, session,
                Sets.newHashSet(USERS_XML, CATEGORIES_XML), true);
    } else {
        // No repository descriptor - prepare to import files directly
        pathMapping.put("/", "/sites/" + site.getSiteKey() + "/files/");
    }

    NodeTypeRegistry reg = NodeTypeRegistry.getInstance();
    DefinitionsMapping mapping = null;

    // Import additional files - site.properties, old cateogries.xml , sitepermissions.xml
    // and eventual plain file from 5.x imports
    if (!sizes.containsKey(REPOSITORY_XML) || sizes.containsKey(SITE_PROPERTIES)
            || sizes.containsKey(CATEGORIES_XML) || sizes.containsKey(SITE_PERMISSIONS_XML)
            || sizes.containsKey(DEFINITIONS_CND) || sizes.containsKey(DEFINITIONS_MAP)) {
        zis = getZipInputStream(file);
        try {
            while (true) {
                ZipEntry zipentry = zis.getNextEntry();
                if (zipentry == null)
                    break;
                String name = zipentry.getName();
                if (name.indexOf('\\') > -1) {
                    name = name.replace('\\', '/');
                }
                if (name.indexOf('/') > -1) {
                    if (!sizes.containsKey(REPOSITORY_XML) && !sizes.containsKey(FILESACL_XML)) {
                        // No repository descriptor - Old import format only
                        name = "/" + name;
                        if (name.startsWith("/content/sites")) {
                            name = pathMapping.get("/") + StringUtils
                                    .stripStart(name.replaceFirst("/content/sites/[^/]+/files/", ""), "/");
                        } else if (name.startsWith("/users")) {
                            Matcher m = Pattern.compile("/users/([^/]+)(/.*)?").matcher(name);
                            if (m.matches()) {
                                name = ServicesRegistry.getInstance().getJahiaUserManagerService()
                                        .getUserSplittingRule().getPathForUsername(m.group(1));
                                name = name + "/files" + ((m.group(2) != null) ? m.group(2) : "");
                            }
                        } else if (name.startsWith("/content/users")) {
                            Matcher m = Pattern.compile("/content/users/([^/]+)(/.*)?").matcher(name);
                            if (m.matches()) {
                                name = ServicesRegistry.getInstance().getJahiaUserManagerService()
                                        .getUserSplittingRule().getPathForUsername(m.group(1));
                                name = name + ((m.group(2) != null) ? m.group(2) : "");
                            }
                        } else {
                            name = pathMapping.get("/") + StringUtils.stripStart(name, "/");
                        }
                        if (!zipentry.isDirectory()) {
                            try {
                                String filename = name.substring(name.lastIndexOf('/') + 1);
                                ensureFile(session, name, zis, JCRContentUtils.getMimeType(filename), site);
                            } catch (Exception e) {
                                logger.error("Cannot upload file " + zipentry.getName(), e);
                            }
                        } else {
                            ensureDir(session, name, site);
                        }
                    }
                } else if (name.equals(CATEGORIES_XML)) {
                    catProps = importCategoriesAndGetUuidProps(zis, categoriesImportHandler);
                } else if (name.equals(DEFINITIONS_CND)) {
                    reg = new NodeTypeRegistry(); // this is fishy: a new instance is created here when NodeTypeRegistry is meant to be used as a singleton
                    try {
                        for (Map.Entry<String, File> entry : NodeTypeRegistry.getSystemDefinitionsFiles()
                                .entrySet()) {
                            reg.addDefinitionsFile(entry.getValue(), entry.getKey());
                        }
                        if (legacyImport) {
                            JahiaCndReaderLegacy r = new JahiaCndReaderLegacy(
                                    new InputStreamReader(zis, Charsets.UTF_8), zipentry.getName(),
                                    file.getURL().getPath(), reg);
                            r.parse();
                        } else {
                            reg.addDefinitionsFile(new InputStreamResource(zis, zipentry.getName()),
                                    file.getURL().getPath());
                        }
                    } catch (RepositoryException | ParseException e) {
                        logger.error(e.getMessage(), e);
                    }
                } else if (name.equals(DEFINITIONS_MAP)) {
                    mapping = new DefinitionsMapping();
                    mapping.load(zis);

                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }
    }

    // Import legacy content from 5.x and 6.x
    if (legacyImport) {
        long timerLegacy = System.currentTimeMillis();
        final String originatingJahiaRelease = (String) infos.get("originatingJahiaRelease");
        logger.info("Start legacy import, source version is " + originatingJahiaRelease);
        if (legacyMappingFilePath != null) {
            mapping = new DefinitionsMapping();
            final InputStream fileInputStream = legacyMappingFilePath.getInputStream();
            try {
                mapping.load(fileInputStream);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
            }
        }
        if (legacyDefinitionsFilePath != null) {
            reg = new NodeTypeRegistry();
            if ("6.1".equals(originatingJahiaRelease)) {
                logger.info("Loading the built in 6.1 definitions before processing the provided custom ones");
                final List<String> builtInLegacyDefs = Arrays.asList("01-system-nodetypes.cnd",
                        "02-jahiacore-nodetypes.cnd", "03-files-nodetypes.cnd", "04-jahiacontent-nodetypes.cnd",
                        "05-standard-types.cnd", "10-extension-nodetypes.cnd", "11-preferences-nodetypes.cnd");

                for (String builtInLegacyDefsFile : builtInLegacyDefs) {
                    InputStreamReader inputStreamReader = null;
                    try {
                        final InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(
                                "org/jahia/migration/legacyDefinitions/jahia6/" + builtInLegacyDefsFile);
                        if (inputStream != null) {
                            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
                            final JahiaCndReaderLegacy r = new JahiaCndReaderLegacy(inputStreamReader,
                                    builtInLegacyDefsFile, file.getURL().getPath(), reg);
                            r.parse();
                        } else {
                            logger.error("Couldn't load " + builtInLegacyDefsFile);
                        }
                    } catch (ParseException e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        IOUtils.closeQuietly(inputStreamReader);
                    }
                }
            } else {
                try {
                    for (Map.Entry<String, File> entry : NodeTypeRegistry.getSystemDefinitionsFiles()
                            .entrySet()) {
                        reg.addDefinitionsFile(entry.getValue(), entry.getKey());
                    }
                } catch (ParseException e) {
                    logger.error("Cannot parse definitions : " + e.getMessage(), e);
                }
            }
            InputStreamReader streamReader = null;
            try {
                streamReader = new InputStreamReader(legacyDefinitionsFilePath.getInputStream(), "UTF-8");
                JahiaCndReaderLegacy r = new JahiaCndReaderLegacy(streamReader,
                        legacyDefinitionsFilePath.getFilename(), file.getURL().getPath(), reg);
                r.parse();
            } catch (ParseException e) {
                logger.error(e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(streamReader);
            }
        }
        // Old import
        JCRNodeWrapper siteFolder = session.getNode("/sites/" + site.getSiteKey());

        zis = new NoCloseZipInputStream(new BufferedInputStream(file.getInputStream()));
        try {
            int legacyImportHandlerCtnId = 1;
            while (true) {
                ZipEntry zipentry = zis.getNextEntry();
                if (zipentry == null)
                    break;
                String name = zipentry.getName();
                if (name.equals(FILESACL_XML)) {
                    logger.info("Importing file " + FILESACL_XML);
                    importFilesAcl(site, file, zis, mapping, fileList);
                } else if (name.startsWith("export")) {
                    logger.info("Importing file " + name);
                    String languageCode;
                    if (name.indexOf("_") != -1) {
                        languageCode = name.substring(7, name.lastIndexOf("."));
                    } else {
                        languageCode = site.getLanguagesAsLocales().iterator().next().toString();
                    }
                    zipentry.getSize();

                    LegacyImportHandler importHandler = new LegacyImportHandler(session, siteFolder, reg,
                            mapping, LanguageCodeConverters.languageCodeToLocale(languageCode),
                            infos != null ? originatingJahiaRelease : null, legacyPidMappingTool,
                            legacyImportHandlerCtnId);
                    Map<String, List<String>> references = new LinkedHashMap<String, List<String>>();
                    importHandler.setReferences(references);

                    InputStream documentInput = zis;
                    if (this.xmlContentTransformers != null && this.xmlContentTransformers.size() > 0) {
                        documentInput = new ZipInputStream(file.getInputStream());
                        while (!name.equals(((ZipInputStream) documentInput).getNextEntry().getName()))
                            ;
                        byte[] buffer = new byte[2048];
                        final File tmpDirectoryForSite = new File(
                                new File(System.getProperty("java.io.tmpdir"), "jahia-migration"),
                                FastDateFormat.getInstance("yyyy_MM_dd-HH_mm_ss_SSS").format(timerSite) + "_"
                                        + site.getSiteKey());
                        tmpDirectoryForSite.mkdirs();
                        File document = new File(tmpDirectoryForSite,
                                "export_" + languageCode + "_00_extracted.xml");
                        final OutputStream output = new BufferedOutputStream(new FileOutputStream(document),
                                2048);
                        int count = 0;
                        while ((count = documentInput.read(buffer, 0, 2048)) > 0) {
                            output.write(buffer, 0, count);
                        }
                        output.flush();
                        output.close();
                        documentInput.close();
                        for (XMLContentTransformer xct : xmlContentTransformers) {
                            document = xct.transform(document, tmpDirectoryForSite);
                        }
                        documentInput = new FileInputStream(document);
                    }

                    handleImport(documentInput, importHandler, name);
                    legacyImportHandlerCtnId = importHandler.getCtnId();
                    ReferencesHelper.resolveCrossReferences(session, references);
                    siteFolder.getSession().save(JCRObservationManager.IMPORT);
                }
                zis.closeEntry();
            }
            ReferencesHelper.resolveReferencesKeeper(session);
            siteFolder.getSession().save(JCRObservationManager.IMPORT);
        } finally {
            closeInputStream(zis);
        }
        logger.info("Done legacy import in {}",
                DateUtils.formatDurationWords(System.currentTimeMillis() - timerLegacy));
    }

    categoriesImportHandler.setUuidProps(catProps);
    usersImportHandler.setUuidProps(userProps);

    // session.save();
    session.save(JCRObservationManager.IMPORT);
    cleanFilesList(fileList);

    if (legacyImport && this.postImportPatcher != null) {
        final long timerPIP = System.currentTimeMillis();
        logger.info("Executing post import patches");
        this.postImportPatcher.executePatches(site);
        logger.info("Executed post import patches in {}",
                DateUtils.formatDurationWords(System.currentTimeMillis() - timerPIP));
    }

    logger.info("Done importing site {} in {}", site != null ? site.getSiteKey() : "",
            DateUtils.formatDurationWords(System.currentTimeMillis() - timerSite));
}

From source file:org.jahia.services.importexport.ImportExportBaseService.java

private void importFilesAcl(JahiaSite site, Resource file, InputStream is, DefinitionsMapping mapping,
        List<String> fileList) {
    Map<String, File> filePath = new HashMap<String, File>();
    File temp = null;/*from   w  w  w .  ja v  a2 s  . c om*/
    try {
        Path tempPath = Files.createTempDirectory("migration");
        temp = tempPath.toFile();
        ZipInputStream zis = getZipInputStream(file);
        try {
            ZipEntry zipentry;
            while ((zipentry = zis.getNextEntry()) != null) {
                String fileName = zipentry.getName();
                if (!zipentry.isDirectory()) {
                    fileName = fileName.replace('\\', '/');
                    File newFile = new File(temp, fileName);
                    newFile.getParentFile().mkdirs();
                    FileUtils.copyInputStreamToFile(zis, newFile);
                    filePath.put("/" + fileName, newFile);
                }
                zis.closeEntry();
            }
        } finally {
            closeInputStream(zis);
        }

        handleImport(is, new FilesAclImportHandler(site, mapping, file, fileList, filePath),
                file.getFilename());
    } catch (IOException e) {
        logger.error("Cannot extract zip", e);
    } finally {
        FileUtils.deleteQuietly(temp);
    }
}

From source file:org.jahia.services.templates.TemplatePackageRegistry.java

/**
 * Adds the template package to the repository.
 *
 * @param templatePackage the template package to add
 *///from   w ww. j a  va2  s.  c  o m
public void register(final JahiaTemplatesPackage templatePackage) {
    templatePackages = null;
    if (packagesByName.get(templatePackage.getName()) != null) {
        JahiaTemplatesPackage previousPack = packagesByName.get(templatePackage.getName());
        previousPack.setActiveVersion(false);
    }

    packagesByName.put(templatePackage.getName(), templatePackage);
    packagesById.put(templatePackage.getId(), templatePackage);

    // handle dependencies
    computeDependencies(templatePackage);
    computeResourceBundleHierarchy(templatePackage);

    try {
        JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
            @Override
            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                if (session.itemExists("/modules/" + templatePackage.getIdWithVersion() + "/permissions")) {
                    JahiaPrivilegeRegistry.addModulePrivileges(session,
                            "/modules/" + templatePackage.getIdWithVersion());
                }
                return null;
            }
        });
    } catch (RepositoryException e) {
        logger.error("Cannot get permissions in module", e);
    }

    Resource[] rootResources = templatePackage.getResources("");
    for (Resource rootResource : rootResources) {
        if (templatePackage.getResources(rootResource.getFilename()).length > 0
                && rootResource.getFilename().contains("_")) {
            String key = rootResource.getFilename();
            if (!modulesWithViewsPerComponents.containsKey(key)) {
                modulesWithViewsPerComponents.put(key,
                        new TreeSet<JahiaTemplatesPackage>(TEMPLATE_PACKAGE_COMPARATOR));
            }
            modulesWithViewsPerComponents.get(key).remove(templatePackage);
            modulesWithViewsPerComponents.get(key).add(templatePackage);
        }
    }

    logger.info("Registered '{}' [{}] version {}",
            new Object[] { templatePackage.getName(), templatePackage.getId(), templatePackage.getVersion() });
}

From source file:org.jahia.services.workflow.jbpm.JBPMModuleProcessLoader.java

private void deployDeclaredProcesses() throws IOException {
    //        URL kmoduleURL = module.getBundle().getEntry("META-INF/kmodule.xml");
    if (processes != null && processes.length > 0) {
        logger.info("Found {} workflow processes to be deployed.", processes.length);

        for (Resource process : processes) {
            String fileName = process.getFilename();
            logger.info("Found workflow process " + fileName + ". Updating...");

            jbpm6WorkflowProvider.addResource(process);
            logger.info("... done");
        }/*  w ww. j av  a  2s.co  m*/
        logger.info("...workflow processes deployed.");
        if (jbpm6WorkflowProvider.isInitialized()) {
            jbpm6WorkflowProvider.recompilePackages();
        }
    }
    if (mailTemplates != null && mailTemplates.length > 0) {
        logger.info("Found {} workflow mail templates to be deployed.", mailTemplates.length);

        for (Resource mailTemplateResource : mailTemplates) {
            MailTemplate mailTemplate = new MailTemplate();
            mailTemplate.setLanguage("velocity");
            mailTemplate.setFrom(new AddressTemplate());
            mailTemplate.setTo(new AddressTemplate());
            mailTemplate.setCc(new AddressTemplate());
            mailTemplate.setBcc(new AddressTemplate());

            int currentField = -1;
            String currentLine;
            StringBuilder buf = new StringBuilder();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(mailTemplateResource.getInputStream(), "UTF-8"));
            try {
                while ((currentLine = reader.readLine()) != null) {
                    if (currentLine.contains(":")) {
                        String prefix = StringUtils.substringBefore(currentLine, ":").toLowerCase();
                        if (FIELDS.contains(prefix)) {
                            setMailTemplateField(mailTemplate, currentField, buf);
                            buf = new StringBuilder();
                            currentField = FIELDS.indexOf(prefix);
                            currentLine = StringUtils.substringAfter(currentLine, ":").trim();
                        }
                    } else {
                        buf.append('\n');
                    }
                    buf.append(currentLine);
                }
            } finally {
                IOUtils.closeQuietly(reader);
            }
            setMailTemplateField(mailTemplate, currentField, buf);
            mailTemplateRegistry.addTemplate(
                    StringUtils.substringBeforeLast(mailTemplateResource.getFilename(), "."), mailTemplate);
        }
    }
}

From source file:org.jahia.services.workflow.jbpm.JBPMModuleProcessLoader.java

private void undeployDeclaredProcesses() throws IOException {
    if (!JahiaContextLoaderListener.isRunning()) {
        return;//ww  w .j  a  v  a 2s .c o m
    }

    if (processes != null && processes.length > 0) {
        logger.info("Found {} workflow processes to be undeployed.", processes.length);

        for (Resource process : processes) {
            String fileName = process.getFilename();
            logger.info("Undeploy workflow process " + fileName + ". Updating...");

            jbpm6WorkflowProvider.removeResource(process);
            logger.info("... done");
        }
        logger.info("...workflow processes undeployed.");
        if (JahiaContextLoaderListener.isContextInitialized()) {
            jbpm6WorkflowProvider.recompilePackages();
        }
    }
    if (mailTemplates != null && mailTemplates.length > 0) {
        logger.info("Found {} workflow mail templates to be undeployed.", mailTemplates.length);

        for (Resource mailTemplateResource : mailTemplates) {
            mailTemplateRegistry
                    .removeTemplate(StringUtils.substringBeforeLast(mailTemplateResource.getFilename(), "."));
        }
    }

}

From source file:org.jahia.services.workflow.jbpm.JBPMProvider.java

private void deployDeclaredProcesses() throws IOException {
    if (processes != null && processes.length > 0) {
        logger.info("Found " + processes.length + " workflow processes to be deployed.");
        List<Deployment> deploymentList = repositoryService.createDeploymentQuery().list();
        for (Resource process : processes) {
            long lastModified = FileUtils.getLastModified(process);

            boolean needUpdate = true;
            boolean found = false;
            String fileName = process.getFilename();
            for (Deployment deployment : deploymentList) {
                if (deployment.getName().equals(fileName)) {
                    found = true;/*w  ww  .  ja  va  2  s. c  o m*/
                    if (deployment.getTimestamp() >= lastModified) {
                        needUpdate = false;
                        break;
                    }
                }
            }
            if (needUpdate) {
                if (found) {
                    logger.info("Found workflow process " + fileName + ". Updating...");
                } else {
                    logger.info("Found new workflow process " + fileName + ". Deploying...");
                }
                NewDeployment newDeployment = repositoryService.createDeployment();
                newDeployment.addResourceFromInputStream(process.getFilename(), process.getInputStream());
                newDeployment.setTimestamp(lastModified);
                newDeployment.setName(fileName);
                newDeployment.deploy();
                logger.info("... done");
            } else {
                logger.info("Found workflow process " + fileName + ". It is up-to-date.");
            }
        }
        logger.info("...workflow processes deployed.");
    }
    if (mailTemplates != null && mailTemplates.length > 0) {
        logger.info("Found " + processes.length + " workflow mail templates to be deployed.");

        List keys = Arrays.asList("from", "to", "cc", "bcc", "from-users", "to-users", "cc-users", "bcc-users",
                "from-groups", "to-groups", "cc-groups", "bcc-groups", "subject", "text", "html", "language");

        for (Resource mailTemplateResource : mailTemplates) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(mailTemplateResource.getInputStream(), "UTF-8"));
            MailTemplate mailTemplate = new MailTemplate();
            mailTemplate.setLanguage("velocity");
            mailTemplate.setFrom(new AddressTemplate());
            mailTemplate.setTo(new AddressTemplate());
            mailTemplate.setCc(new AddressTemplate());
            mailTemplate.setBcc(new AddressTemplate());

            int currentField = -1;
            String currentLine;
            StringBuilder buf = new StringBuilder();
            while ((currentLine = reader.readLine()) != null) {
                if (currentLine.contains(":")) {
                    String prefix = StringUtils.substringBefore(currentLine, ":");
                    if (keys.contains(prefix.toLowerCase())) {
                        setMailTemplateField(mailTemplate, currentField, buf);
                        buf = new StringBuilder();
                        currentField = keys.indexOf(prefix.toLowerCase());
                        currentLine = StringUtils.substringAfter(currentLine, ":").trim();
                    }
                } else {
                    buf.append('\n');
                }
                buf.append(currentLine);
            }
            setMailTemplateField(mailTemplate, currentField, buf);
            mailTemplateRegistry.addTemplate(
                    StringUtils.substringBeforeLast(mailTemplateResource.getFilename(), "."), mailTemplate);
        }
    }

}

From source file:org.jumpmind.metl.core.util.DatabaseScriptContainer.java

public DatabaseScriptContainer(String scriptLocation, IDatabasePlatform platform) {
    try {//w  ww .jav a  2  s.c o m
        this.scriptLocation = scriptLocation;
        this.platform = platform;
        this.jdbcTemplate = new JdbcTemplate(platform.getDataSource());

        replacementTokens = new HashMap<String, String>();
        // Add any replacement tokens

        Resource[] resources = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader())
                .getResources(String.format("classpath*:%s/*.sql", scriptLocation));
        for (Resource r : resources) {
            DatabaseScript script = new DatabaseScript(r.getFilename());
            script.setResource(r);

            if (script.getWhen() == DatabaseScript.WHEN_PREINSTALL) {
                preInstallScripts.add(script);
            } else if (script.getWhen() == DatabaseScript.WHEN_POSTINSTALL) {
                postInstallScripts.add(script);
            }
        }
    } catch (IOException e) {
        throw new IoException(e);
    }
}

From source file:org.kuali.mobility.icons.service.IconsServiceImpl.java

/**
 * Import all icon configurations found in the classpath.
 * Any files matching the pattern "*IconsConfig.xml" will
 * be loaded as icon configuration files
 *///  w  w  w .j a  v  a 2 s. c o  m
private void autoImport() throws Exception {
    PathMatchingResourcePatternResolver m = new PathMatchingResourcePatternResolver();
    Resource[] resources = m.getResources("*IconsConfig.xml");
    for (Resource r : resources) {
        LOG.debug(r.getFilename());
        importIcons(r.getInputStream());
    }

}

From source file:org.kuali.rice.core.api.impex.xml.LocationXmlDoc.java

static String getName(String location) {
    Resource resource = getResource(location);
    return resource.getFilename();
}