Example usage for org.apache.commons.lang StringUtils substringBetween

List of usage examples for org.apache.commons.lang StringUtils substringBetween

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substringBetween.

Prototype

public static String substringBetween(String str, String open, String close) 

Source Link

Document

Gets the String that is nested in between two Strings.

Usage

From source file:org.eclipse.wb.internal.rcp.databinding.xwt.parser.DatabindingParser.java

private BindingInfo parseBinding(DocumentElement element, String property, Map<String, String> attributes)
        throws Exception {
    WidgetBindableInfo target = m_widgetContainer.resolve(element);
    if (target == null) {
        m_provider.addWarning(MessageFormat.format(Messages.DatabindingParser_widgetNotFound, element),
                new Throwable());
        return null;
    }/*from w ww . j a  v  a  2 s.  c  om*/
    //
    WidgetPropertyBindableInfo targetProperty = target.resolvePropertyByText(property);
    if (targetProperty == null) {
        m_provider.addWarning(
                MessageFormat.format(Messages.DatabindingParser_widgetPropertyNotFound, element, property),
                new Throwable());
        return null;
    }
    //
    String path = attributes.get("path");
    String elementName = attributes.get("elementname");
    //
    if (elementName != null) {
        WidgetBindableInfo model = m_widgetContainer.resolve(elementName);
        if (model == null) {
            m_provider.addWarning(MessageFormat.format(Messages.DatabindingParser_widgetNotFound, elementName),
                    new Throwable());
            return null;
        }
        //
        if (path.toLowerCase().startsWith("singleselection.(") && path.endsWith(")")) {
            if (property.equalsIgnoreCase("input")) {
                // XXX
            }
            // XXX
            return null;
        }
        //
        WidgetPropertyBindableInfo modelProperty = model.resolvePropertyByText(path.toLowerCase());
        if (modelProperty == null) {
            m_provider.addWarning(
                    MessageFormat.format(Messages.DatabindingParser_widgetPropertyNotFound, element, path),
                    new Throwable());
            return null;
        }
        //
        return createBinding(target, targetProperty, model, modelProperty, attributes);
    }
    //
    BeanBindableInfo model = null;
    String source = attributes.get("source");
    //
    if (source != null) {
        String sourceReference = StringUtils.substringBetween(source, "{StaticResource", "}").trim();
        model = (BeanBindableInfo) m_beanContainer.resolve(sourceReference);
    } else {
        model = m_beanContainer.getDataContext();
    }
    //
    if (model == null) {
        m_provider.addWarning(Messages.DatabindingParser_beanNotFound, new Throwable());
        return null;
    }
    //
    PropertyBindableInfo modelProperty = model.resolvePropertyReference("\"" + path.toLowerCase() + "\"");
    if (modelProperty == null) {
        m_provider.addWarning(MessageFormat.format(Messages.DatabindingParser_beanPropertyNotFound, path),
                new Throwable());
        return null;
    }
    //
    if (property.equalsIgnoreCase("input")) {
        // XXX
        return null;
    }
    //
    return createBinding(target, targetProperty, model, modelProperty, attributes);
}

From source file:org.eclipse.wb.internal.swing.databinding.wizards.autobindings.SwingDatabindingProvider.java

public String performSubstitutions(String code, ImportsManager imports) throws Exception {
    // calculate states
    boolean blockMode = useBlockMode();
    boolean lazyVariables = createLazyVariables();
    ////from  ww w .  j av  a  2 s  .  com
    DataBindingsCodeUtils.ensureDBLibraries(m_javaProject);
    CodeGenerationSupport generationSupport = new CodeGenerationSupport(CoreUtils.useGenerics(m_javaProject));
    // prepare imports
    Collection<String> importList = Sets.newHashSet();
    importList.add("java.awt.GridBagLayout");
    importList.add("java.awt.GridBagConstraints");
    importList.add("java.awt.Insets");
    importList.add("javax.swing.JLabel");
    importList.add("org.jdesktop.beansbinding.AutoBinding");
    importList.add("org.jdesktop.beansbinding.Bindings");
    importList.add("org.jdesktop.beansbinding.BeanProperty");
    //
    if (!generationSupport.useGenerics()) {
        importList.add("org.jdesktop.beansbinding.Property");
    }
    // bean class, field, name, field access
    String beanClassName = m_beanClass.getName().replace('$', '.');
    String beanClassShortName = ClassUtils.getShortClassName(beanClassName);
    String fieldPrefix = JavaCore.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES);
    String fieldName = fieldPrefix + StringUtils.uncapitalize(beanClassShortName);
    //
    code = StringUtils.replace(code, "%BeanClass%", beanClassName);
    //
    if (ReflectionUtils.getConstructorBySignature(m_beanClass, "<init>()") == null) {
        code = StringUtils.replace(code, "%BeanField%", fieldName);
    } else {
        code = StringUtils.replace(code, "%BeanField%", fieldName + " = new " + beanClassName + "()");
    }
    //
    IPreferenceStore preferences = ToolkitProvider.DESCRIPTION.getPreferences();
    String accessPrefix = preferences.getBoolean(FieldUniqueVariableSupport.P_PREFIX_THIS) ? "this." : "";
    String beanFieldAccess = accessPrefix + fieldName;
    //
    code = StringUtils.replace(code, "%BeanName%", StringUtils.capitalize(beanClassShortName));
    code = StringUtils.replace(code, "%BeanFieldAccess%", accessPrefix + fieldName);
    // prepare properties
    final List<PropertyAdapter> properties = Lists.newArrayList();
    Display.getDefault().syncExec(new Runnable() {
        public void run() {
            CollectionUtils.addAll(properties, m_propertiesViewer.getCheckedElements());
        }
    });
    // prepare code
    StringBuffer componentFields = new StringBuffer();
    StringBuffer components = new StringBuffer();
    String swingContainer = StringUtils.substringBetween(code, "%Components%", "%");
    String swingContainerWithDot = "this".equals(swingContainer) ? "" : swingContainer + ".";
    //
    int propertiesCount = properties.size();
    int lastPropertyIndex = propertiesCount - 1;
    StringBuffer bindings = new StringBuffer();
    // prepare layout code
    components.append("\t\tGridBagLayout gridBagLayout = new GridBagLayout();\r\n");
    components.append("\t\tgridBagLayout.columnWidths = new int[]{0, 0, 0};\r\n");
    components.append("\t\tgridBagLayout.rowHeights = new int[]{" + StringUtils.repeat("0, ", propertiesCount)
            + "0};\r\n");
    components.append("\t\tgridBagLayout.columnWeights = new double[]{0.0, 1.0, 1.0E-4};\r\n");
    components.append("\t\tgridBagLayout.rowWeights = new double[]{"
            + StringUtils.repeat("0.0, ", propertiesCount) + "1.0E-4};\r\n");
    components.append("\t\t" + swingContainerWithDot + "setLayout(gridBagLayout);\r\n");
    //
    StringBuffer group = new StringBuffer();
    generationSupport.generateLocalName("bindingGroup");
    //
    StringBuffer lazy = new StringBuffer();
    //
    for (int i = 0; i < propertiesCount; i++) {
        String index = Integer.toString(i);
        //
        PropertyAdapter property = properties.get(i);
        Object[] editorData = m_propertyToEditor.get(property);
        SwingComponentDescriptor componentDescriptor = (SwingComponentDescriptor) editorData[0];
        //
        String propertyName = property.getName();
        // label
        addLabelCode(componentFields, components, lazy, swingContainerWithDot, blockMode, lazyVariables,
                propertyName, index);
        //
        String componentClassName = componentDescriptor.getComponentClass();
        String componentShortClassName = ClassUtils.getShortClassName(componentClassName);
        String componentFieldName = fieldPrefix + propertyName + componentShortClassName;
        String componentFieldAccess = accessPrefix + componentFieldName;
        String componentLazyAccess = "get" + StringUtils.capitalize(propertyName) + componentShortClassName
                + "()";
        String componentAccess = lazyVariables ? componentLazyAccess : componentFieldAccess;
        //
        importList.add(componentClassName);
        // field
        componentFields
                .append("\r\nfield\r\n\tprivate " + componentShortClassName + " " + componentFieldName + ";");
        // component
        addComponentCode(components, lazy, swingContainerWithDot, blockMode, lazyVariables,
                componentShortClassName, componentFieldAccess, componentLazyAccess, index);
        // binding properties
        AutoBindingUpdateStrategyDescriptor strategyDescriptor = (AutoBindingUpdateStrategyDescriptor) editorData[1];
        //
        String modelPropertyName = generationSupport.generateLocalName(propertyName, "Property");
        String targetPropertyName = generationSupport.generateLocalName(componentDescriptor.getName(1),
                "Property");
        String bindingName = generationSupport.generateLocalName("autoBinding");
        String modelGeneric = null;
        String targetGeneric = null;
        //
        if (generationSupport.useGenerics()) {
            modelGeneric = beanClassName + ", "
                    + GenericUtils.convertPrimitiveType(property.getType().getName());
            bindings.append("\t\tBeanProperty<" + modelGeneric + "> ");
        } else {
            bindings.append("\t\tProperty ");
        }
        bindings.append(modelPropertyName + " = BeanProperty.create(\"" + propertyName + "\");\r\n");
        //
        if (generationSupport.useGenerics()) {
            targetGeneric = componentDescriptor.getComponentClass() + ", "
                    + componentDescriptor.getPropertyClass();
            bindings.append("\t\tBeanProperty<" + targetGeneric + "> ");
        } else {
            bindings.append("\t\tProperty ");
        }
        bindings.append(
                targetPropertyName + " = BeanProperty.create(\"" + componentDescriptor.getName(1) + "\");\r\n");
        // binding
        bindings.append("\t\tAutoBinding");
        if (generationSupport.useGenerics()) {
            bindings.append("<" + modelGeneric + ", " + targetGeneric + ">");
        }
        bindings.append(" " + bindingName + " = Bindings.createAutoBinding("
                + strategyDescriptor.getSourceCode() + ", " + beanFieldAccess + ", " + modelPropertyName + ", "
                + componentAccess + ", " + targetPropertyName + ");\r\n");
        bindings.append("\t\t" + bindingName + ".bind();");
        //
        group.append("\t\tbindingGroup.addBinding(" + bindingName + ");");
        //
        if (i < lastPropertyIndex) {
            componentFields.append("\r\n");
            components.append("\r\n");
            bindings.append("\r\n\t\t//\r\n");
            group.append("\r\n");
        }
        //
    }
    // replace template patterns
    code = StringUtils.replace(code, "%ComponentFields%", componentFields.toString());
    code = StringUtils.replace(code, "%Components%" + swingContainer + "%", components.toString());
    code = StringUtils.replace(code, "%Bindings%", bindings.toString());
    code = StringUtils.replace(code, "%Group%", group.toString());
    code = StringUtils.replace(code, "%LAZY%", lazy.toString());
    // add imports
    for (String qualifiedTypeName : importList) {
        imports.addImport(qualifiedTypeName);
    }
    //
    return code;
}

From source file:org.endiansummer.tools.soaprunner.VariableStore.java

public String getVariable(String key) {

    String idxStr = StringUtils.substringBetween(key, "[", "]");
    if (idxStr != null) {
        key = StringUtils.substringBefore(key, "[").trim();
        idxStr = idxStr.trim();//from  w  w w .  j  a v a  2 s  .c  o m
    }

    int index = idxStr != null ? Integer.parseInt(idxStr) : getVariableCount(key) - 1;
    return getVariable(key, index);
}

From source file:org.fundacionjala.enforce.sonarqube.apex.checks.soql.SoqlParser.java

/**
 * Re-parses a query that was retrieved as a String.
 *
 * @param astNode The String's node./*from w  w  w  .  j a  v  a 2 s.  co m*/
 * @return The query as a new QUERY_EXPRESSION node.
 */
public static AstNode parseQuery(AstNode astNode) {
    AstNode parsedQuery = null;
    try {
        String string = astNode.getTokenOriginalValue();
        String queryAsString = StringUtils.substringBetween(string, "'", "'");
        Parser<Grammar> queryParser = ApexParser.create(new ApexConfiguration(Charsets.UTF_8));
        queryParser.setRootRule(queryParser.getGrammar().rule(ApexGrammarRuleKey.QUERY_EXPRESSION));
        parsedQuery = queryParser.parse(queryAsString);
    } catch (Exception e) {
        ChecksLogger.logCheckError(CLASS_TO_LOG, METHOD_TO_LOG, e.toString());
    }
    return parsedQuery;
}

From source file:org.jahia.ajax.gwt.helper.NavigationHelper.java

public List<GWTJahiaNode> retrieveRoot(List<String> paths, List<String> nodeTypes, List<String> mimeTypes,
        List<String> filters, final List<String> fields, final JCRSiteNode site, Locale uiLocale,
        JCRSessionWrapper currentUserSession, boolean checkSubChild, boolean displayHiddenTypes,
        List<String> hiddenTypes, String hiddenRegex) throws RepositoryException, GWTJahiaServiceException {
    final List<GWTJahiaNode> userNodes = new ArrayList<GWTJahiaNode>();
    final boolean checkLicense = haveToCheckLicense(fields);

    for (String path : paths) {
        // replace $user and $site by the right values
        String displayName = null;
        if (site != null) {
            if (path.contains("$site/") || path.endsWith("$site")) {
                String sitePath = site.getPath();
                if (StringUtils.startsWith(sitePath, "/modules/")) {
                    String moduleName = sitePath.indexOf('/', "/modules/".length()) != -1
                            ? StringUtils.substringBetween(sitePath, "/modules/", "/")
                            : StringUtils.substringAfter(sitePath, "/modules/");
                    JahiaTemplatesPackage module = ServicesRegistry.getInstance()
                            .getJahiaTemplateManagerService().getTemplatePackageById(moduleName);
                    if (module == null) {
                        return userNodes;
                    }/*from   w w w .  ja  v a 2 s. c om*/
                    path = StringUtils.replace(path, "$site", sitePath + "/" + module.getVersion().toString());
                } else {
                    path = StringUtils.replace(path, "$site", sitePath);
                }
            }
            if (path.contains("$siteKey/")) {
                path = path.replace("$siteKey", site.getSiteKey());
            }
        }
        if (path.contains("$moduleversion")) {
            String moduleName = StringUtils.split(path, '/')[1];
            if (ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                    .getTemplatePackageById(moduleName) != null) {
                path = path.replace("$moduleversion",
                        ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                                .getTemplatePackageById(moduleName).getVersion().toString());
            } else {
                logger.warn("read version - Unable to get bundle " + moduleName + " from registry");
                continue;
            }
        }
        if (path.contains("$systemsite")) {
            String systemSiteKey = JCRContentUtils.getSystemSitePath();
            path = path.replace("$systemsite", systemSiteKey);
        }
        if (site != null && path.contains("$sites")) {
            JCRTemplate.getInstance().doExecuteWithSystemSession(new JCRCallback<Object>() {
                public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                    final JCRNodeWrapper parent = site.getParent();
                    NodeIterator nodes = parent.getNodes();
                    while (nodes.hasNext()) {
                        JCRNodeWrapper nodeWrapper = (JCRNodeWrapper) nodes.next();
                        if (!checkLicense || isAllowedByLicense(nodeWrapper)) {
                            userNodes.add(getGWTJahiaNode(nodeWrapper, fields));
                        }
                    }
                    return null;
                }
            });
        }
        if (path.contains("$user")) {
            final JCRNodeWrapper userFolder = JCRContentUtils.getInstance()
                    .getDefaultUserFolder(currentUserSession, StringUtils.substringAfter(path, "$user"));

            path = userFolder.getPath();
            displayName = Messages.getInternal("label.personalFolder", uiLocale, "label.personalFolder");
        }
        if (path.startsWith("/")) {
            try {
                if (path.endsWith("/*")) {
                    getMatchingChildNodes(nodeTypes, mimeTypes, filters, fields,
                            currentUserSession.getNode(StringUtils.substringBeforeLast(path, "/*")), userNodes,
                            checkSubChild, displayHiddenTypes, hiddenTypes, hiddenRegex, false, uiLocale);
                } else {
                    GWTJahiaNode root = getNode(path, fields, currentUserSession, uiLocale);
                    if (root != null) {
                        if (displayName != null) {
                            root.setDisplayName(JCRContentUtils.unescapeLocalNodeName(displayName));
                        }
                        userNodes.add(root);
                    }
                }
            } catch (PathNotFoundException e) {
                // do nothing is the path is not found
            }
        }
    }
    return userNodes;
}

From source file:org.jahia.bin.WelcomeServlet.java

protected void defaultRedirect(HttpServletRequest request, HttpServletResponse response, ServletContext context)
        throws Exception {
    request.getSession(true);/*  w w w.  j  ava2 s.  c  o m*/

    final JahiaSitesService siteService = JahiaSitesService.getInstance();
    JahiaSite defaultSite = null;
    String defaultSitePath = null;
    final JCRSiteNode site;
    String siteKey = !Url.isLocalhost(request.getServerName())
            ? siteService.getSitenameByServerName(request.getServerName())
            : null;
    if (siteKey != null) {
        // site resolved by the hostname -> read it with user session to check the access rights
        site = (JCRSiteNode) siteService.getSiteByKey(siteKey);
    } else {
        // use the default site
        defaultSite = siteService.getDefaultSite();
        defaultSitePath = defaultSite != null ? defaultSite.getJCRLocalPath() : null;
        site = (JCRSiteNode) defaultSite;
    }

    String redirect = null;
    String pathInfo = request.getPathInfo();

    String defaultLocation = null;
    String mapping = null;

    if (pathInfo != null && (pathInfo.endsWith("mode") || pathInfo.endsWith("mode/"))) {
        String mode = pathInfo.endsWith("/") ? StringUtils.substringBetween(pathInfo, "/", "/")
                : StringUtils.substringAfter(pathInfo, "/");
        if (SpringContextSingleton.getInstance().getContext().containsBean(mode)) {
            EditConfiguration editConfiguration = (EditConfiguration) SpringContextSingleton.getInstance()
                    .getContext().getBean(mode);
            defaultLocation = editConfiguration.getDefaultLocation();
            mapping = editConfiguration.getDefaultUrlMapping();
        }
    }

    if (site == null && (defaultLocation == null || defaultLocation.contains("$defaultSiteHome"))) {
        userRedirect(request, response, context);
    } else {
        if (defaultSite == null) {
            defaultSite = siteService.getDefaultSite();
            defaultSitePath = defaultSite != null ? defaultSite.getJCRLocalPath() : null;
        }

        JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER);
        JCRUserNode userNode = user != null
                ? JahiaUserManagerService.getInstance().lookupUserByPath(user.getLocalPath())
                : null;
        String language = resolveLanguage(request, site, userNode, false);
        if (defaultLocation != null) {
            if (site != null && defaultLocation.contains("$defaultSiteHome")) {
                JCRNodeWrapper home = site.getHome();
                if (home == null) {
                    home = resolveSite(request, Constants.EDIT_WORKSPACE, defaultSitePath).getHome();
                }
                defaultLocation = defaultLocation.replace("$defaultSiteHome", home.getPath());
            }

            redirect = request.getContextPath() + mapping + "/" + language + defaultLocation;
        } else {
            JCRNodeWrapper home = site.getHome();
            if (home != null) {
                redirect = request.getContextPath() + "/cms/render/" + Constants.LIVE_WORKSPACE + "/" + language
                        + home.getPath() + ".html";
            } else if (!SettingsBean.getInstance().isDistantPublicationServerMode()) {
                JCRSiteNode defSite = null;
                try {
                    defSite = (JCRSiteNode) JCRStoreService.getInstance().getSessionFactory()
                            .getCurrentUserSession().getNode(site.getPath());
                } catch (PathNotFoundException e) {
                    if (!Url.isLocalhost(request.getServerName()) && defaultSite != null
                            && !site.getSiteKey().equals(defaultSite.getSiteKey())
                            && (!SettingsBean.getInstance() // the check in this parenthesis is added to prevent immediate servername change in the url, which leads to the side effect with an automatic login on default site after logout on other site 
                                    .isUrlRewriteUseAbsoluteUrls()
                                    || site.getServerName().equals(defaultSite.getServerName())
                                    || Url.isLocalhost(defaultSite.getServerName()))) {
                        JCRSiteNode defaultSiteNode = (JCRSiteNode) JCRStoreService.getInstance()
                                .getSessionFactory().getCurrentUserSession(Constants.LIVE_WORKSPACE)
                                .getNode(defaultSitePath);
                        if (defaultSiteNode.getHome() != null) {
                            redirect = request.getContextPath() + "/cms/render/" + Constants.LIVE_WORKSPACE
                                    + "/" + language + defaultSiteNode.getHome().getPath() + ".html";
                        }
                    }
                }
                if (redirect == null && defSite != null && defSite.getHome() != null) {
                    if (defSite.getHome().hasPermission("editModeAccess")) {
                        redirect = request.getContextPath() + "/cms/edit/" + Constants.EDIT_WORKSPACE + "/"
                                + language + defSite.getHome().getPath() + ".html";
                    } else if (defSite.getHome().hasPermission("contributeModeAccess")) {
                        redirect = request.getContextPath() + "/cms/contribute/" + Constants.EDIT_WORKSPACE
                                + "/" + language + defSite.getHome().getPath() + ".html";
                    }
                }
            }
        }
        if (redirect == null) {
            redirect(request.getContextPath() + "/start", response);
            return;
        }
        redirect(redirect, response);
    }
}

From source file:org.jahia.modules.bootstrap.rules.BootstrapCompiler.java

private void compileBootstrap(JCRNodeWrapper siteOrModuleVersion, List<Resource> lessResources,
        String variables) throws IOException, LessException, RepositoryException {
    if (lessResources != null && !lessResources.isEmpty()) {
        File tmpLessFolder = new File(FileUtils.getTempDirectory(), "less-" + System.currentTimeMillis());
        tmpLessFolder.mkdir();/*w w  w .j ava  2s .c  o m*/
        try {
            List<String> allContent = new ArrayList<String>();
            for (Resource lessResource : lessResources) {
                File lessFile = new File(tmpLessFolder, lessResource.getFilename());
                if (!lessFile.exists()) {
                    InputStream inputStream;
                    if (variables != null && VARIABLES_LESS.equals(lessResource.getFilename())) {
                        inputStream = new SequenceInputStream(lessResource.getInputStream(),
                                new ByteArrayInputStream(variables.getBytes()));
                    } else {
                        inputStream = lessResource.getInputStream();
                    }
                    final FileOutputStream output = new FileOutputStream(lessFile);
                    IOUtils.copy(inputStream, output);
                    IOUtils.closeQuietly(inputStream);
                    IOUtils.closeQuietly(output);
                }
                final FileInputStream input = new FileInputStream(lessFile);
                allContent.addAll(IOUtils.readLines(input));
                IOUtils.closeQuietly(input);
            }
            String md5 = DigestUtils.md5Hex(StringUtils.join(allContent, '\n'));

            JCRNodeWrapper node = siteOrModuleVersion;
            for (String pathPart : StringUtils.split(CSS_FOLDER_PATH, '/')) {
                if (node.hasNode(pathPart)) {
                    node = node.getNode(pathPart);
                } else {
                    node = node.addNode(pathPart, "jnt:folder");
                }
            }

            boolean compileCss = true;
            JCRNodeWrapper bootstrapCssNode;

            if (node.hasNode(BOOTSTRAP_CSS)) {
                bootstrapCssNode = node.getNode(BOOTSTRAP_CSS);
                String content = bootstrapCssNode.getFileContent().getText();
                String timestamp = StringUtils.substringBetween(content, "/* sources hash ", " */");
                if (timestamp != null && md5.equals(timestamp)) {
                    compileCss = false;
                }
            } else {
                bootstrapCssNode = node.addNode(BOOTSTRAP_CSS, "jnt:file");
            }
            if (compileCss) {
                File bootstrapCss = new File(tmpLessFolder, BOOTSTRAP_CSS);
                lessCompiler.compile(new File(tmpLessFolder, "bootstrap.less"), bootstrapCss);
                FileOutputStream f = new FileOutputStream(bootstrapCss, true);
                IOUtils.write("\n/* sources hash " + md5 + " */\n", f);
                IOUtils.closeQuietly(f);
                FileInputStream inputStream = new FileInputStream(bootstrapCss);
                bootstrapCssNode.getFileContent().uploadFile(inputStream, "text/css");
                bootstrapCssNode.getSession().save();
                IOUtils.closeQuietly(inputStream);
            }
        } catch (IOException e) {
            throw new RepositoryException(e);
        } catch (LessException e) {
            throw new RepositoryException(e);
        } finally {
            FileUtils.deleteQuietly(tmpLessFolder);
        }
    }
}

From source file:org.jahia.modules.external.modules.ModulesDataSource.java

private ExternalData enhanceData(String path, ExternalData data) {
    try {// w w  w.j  a v  a  2s .co  m
        ExtendedNodeType type = NodeTypeRegistry.getInstance().getNodeType(data.getType());
        if (type.isNodeType("jnt:moduleVersionFolder")) {
            String name = module.getName();
            String v = module.getVersion().toString();
            data.getProperties().put("j:title", new String[] { name + " (" + v + ")" });
        } else if (type.isNodeType(JNT_EDITABLE_FILE)) {
            Set<String> lazyProperties = data.getLazyProperties();
            if (lazyProperties == null) {
                lazyProperties = new HashSet<String>();
                data.setLazyProperties(lazyProperties);
            }
            String nodeTypeName = StringUtils
                    .replace(StringUtils.substringBetween(path, SRC_MAIN_RESOURCES, "/"), "_", ":");
            // add nodetype only if it is resolved
            if (nodeTypeName != null) {
                nodeTypeName = nodeTypeName.replace('-', '_');
                data.getProperties().put("nodeTypeName", new String[] { nodeTypeName });
            }
            lazyProperties.add(SOURCE_CODE);
            // set Properties
            if (type.isNodeType(Constants.JAHIAMIX_VIEWPROPERTIES)) {
                Properties properties = new SortedProperties();
                InputStream is = null;
                try {
                    is = getFile(StringUtils.substringBeforeLast(path, ".") + PROPERTIES_EXTENSION).getContent()
                            .getInputStream();
                    properties.load(is);
                    Map<String, String[]> dataProperties = new HashMap<String, String[]>();
                    for (Map.Entry<?, ?> property : properties.entrySet()) {
                        ExtendedPropertyDefinition propertyDefinition = type.getPropertyDefinitionsAsMap()
                                .get(property.getKey());
                        String[] values;
                        if (propertyDefinition != null && propertyDefinition.isMultiple()) {
                            values = StringUtils.split(((String) property.getValue()), ",");
                        } else {
                            values = new String[] { (String) property.getValue() };
                        }
                        dataProperties.put((String) property.getKey(), values);
                    }
                    data.getProperties().putAll(dataProperties);
                } catch (FileSystemException e) {
                    //no properties files, do nothing
                } catch (IOException e) {
                    logger.error("Cannot read property file", e);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        } else {
            String ext = StringUtils.substringAfterLast(path, ".");
            Map<?, ?> extensions = (Map<?, ?>) SpringContextSingleton.getBean("fileExtensionIcons");
            if ("img".equals(extensions.get(ext))) {
                InputStream is = null;
                try {
                    is = getFile(data.getPath()).getContent().getInputStream();
                    BufferedImage bimg = ImageIO.read(is);
                    if (bimg != null) {
                        data.setMixin(JMIX_IMAGE_LIST);
                        data.getProperties().put("j:height",
                                new String[] { Integer.toString(bimg.getHeight()) });
                        data.getProperties().put("j:width", new String[] { Integer.toString(bimg.getWidth()) });
                    }
                } catch (FileSystemException e) {
                    //no properties files, do nothing
                } catch (IOException e) {
                    logger.error("Cannot read property file", e);
                } catch (Exception e) {
                    logger.error("unable to enhance image " + data.getPath(), e);
                } finally {
                    if (is != null) {
                        IOUtils.closeQuietly(is);
                    }
                }
            }
        }
    } catch (NoSuchNodeTypeException e) {
        logger.error("Unknown type", e);
    }
    SourceControlManagement sourceControl = module.getSourceControl();
    if (sourceControl != null) {
        try {
            SourceControlManagement.Status status = getScmStatus(path);
            if (status != SourceControlManagement.Status.UNMODIFIED) {
                List<String> mixin = data.getMixin();
                if (mixin == null) {
                    mixin = new ArrayList<String>();
                }
                if (!mixin.contains("jmix:sourceControl")) {
                    mixin.add("jmix:sourceControl");
                }
                data.setMixin(mixin);
                data.getProperties().put("scmStatus", new String[] { status.name().toLowerCase() });
            }
        } catch (IOException e) {
            logger.error("Failed to get SCM status", e);
        }
    }
    return data;
}

From source file:org.jahia.modules.external.modules.osgi.ModulesSourceHttpServiceTracker.java

/**
 * register the resource as a View//from w  w w.j  av  a  2s.c  o m
 * @param resource to register
 */
public void registerResource(File resource) {
    String filePath = getResourcePath(resource);
    String fileServletAlias = "/" + bundle.getSymbolicName() + filePath;
    httpService.unregister(fileServletAlias);
    bundleScriptResolver.addBundleScript(bundle, filePath);
    templatePackageRegistry.addModuleWithViewsForComponent(StringUtils.substringBetween(filePath, "/", "/"),
            module);
    if (logger.isDebugEnabled()) {
        logger.debug("Register file {} in bundle {}", filePath, bundleName);
    }
}

From source file:org.jahia.modules.external.modules.osgi.ModulesSourceHttpServiceTracker.java

/**
 * Unregister the resource, remove it from the availables Views
 * @param file is the resource to unregister
 *///from   ww w.  ja  v a 2 s  .  c  o m
public void unregisterResouce(File file) {
    String filePath = getResourcePath(file);
    String fileServletAlias = "/" + bundle.getSymbolicName() + filePath;

    if (bundle.getEntry(filePath) != null) {
        // A jsp is still present in the bundle, don't unregister it
        return;
    }

    httpService.unregister(fileServletAlias);
    bundleScriptResolver.removeBundleScript(bundle, filePath);
    String propertiesFileName = FilenameUtils.removeExtension(file.getName()) + ".properties";
    File parentFile = file.getParentFile();
    File[] matching = parentFile != null ? parentFile.listFiles(new FilenameFilterNotEquals(propertiesFileName))
            : null;
    if (matching == null || matching.length == 0) {
        templatePackageRegistry
                .removeModuleWithViewsForComponent(StringUtils.substringBetween(filePath, "/", "/"), module);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Unregister file {} in bundle {}", filePath, bundleName);
    }
}