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

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

Introduction

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

Prototype

public static String substringBeforeLast(String str, String separator) 

Source Link

Document

Gets the substring before the last occurrence of a separator.

Usage

From source file:org.eclipse.smarthome.config.dispatch.internal.ConfigDispatcher.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void processConfigFile(File configFile) throws IOException, FileNotFoundException {
    if (configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
        logger.debug("Ignoring file '{}'", configFile.getName());
        return;//from  ww  w  . j a v  a 2 s  . c om
    }
    logger.debug("Processing config file '{}'", configFile.getName());

    // we need to remember which configuration needs to be updated
    // because values have changed.
    Map<Configuration, Dictionary> configsToUpdate = new HashMap<Configuration, Dictionary>();

    // also cache the already retrieved configurations for each pid
    Map<Configuration, Dictionary> configMap = new HashMap<Configuration, Dictionary>();

    String pid;
    String filenameWithoutExt = StringUtils.substringBeforeLast(configFile.getName(), ".");
    if (filenameWithoutExt.contains(".")) {
        // it is a fully qualified namespace
        pid = filenameWithoutExt;
    } else {
        pid = getServicePidNamespace() + "." + filenameWithoutExt;
    }

    // configuration file contains a PID Marker
    List<String> lines = IOUtils.readLines(new FileInputStream(configFile));
    if (lines.size() > 0 && lines.get(0).startsWith(PID_MARKER)) {
        pid = lines.get(0).substring(PID_MARKER.length()).trim();
    }

    for (String line : lines) {
        String[] contents = parseLine(configFile.getPath(), line);
        // no valid configuration line, so continue
        if (contents == null) {
            continue;
        }

        if (contents[0] != null) {
            pid = contents[0];
            // PID is not fully qualified, so prefix with namespace
            if (!pid.contains(".")) {
                pid = getServicePidNamespace() + "." + pid;
            }
        }

        String property = contents[1];
        String value = contents[2];
        Configuration configuration = configAdmin.getConfiguration(pid, null);
        if (configuration != null) {
            Dictionary configProperties = configMap.get(configuration);
            if (configProperties == null) {
                configProperties = configuration.getProperties() != null ? configuration.getProperties()
                        : new Properties();
                configMap.put(configuration, configProperties);
            }
            if (!value.equals(configProperties.get(property))) {
                configProperties.put(property, value);
                configsToUpdate.put(configuration, configProperties);
            }
        }
    }

    for (Entry<Configuration, Dictionary> entry : configsToUpdate.entrySet()) {
        entry.getKey().update(entry.getValue());
    }
}

From source file:org.eclipse.smarthome.ui.icon.internal.AbstractResourceIconProviderTest.java

@Before
public void setUp() {

    provider = new AbstractResourceIconProvider() {
        @Override//w  w  w  .j  a  va  2  s  .c o  m
        protected InputStream getResource(String iconset, String resourceName) {
            switch (resourceName) {
            case "x-30.png":
                return new ByteArrayInputStream("x-30.png".getBytes());
            case "x-y z.png":
                return new ByteArrayInputStream("x-y z.png".getBytes());
            default:
                return null;
            }
        }

        @Override
        protected boolean hasResource(String iconset, String resourceName) {
            String state = StringUtils.substringAfterLast(resourceName, "-");
            state = StringUtils.substringBeforeLast(state, ".");
            return state.equals("30") || state.equals("y z");
        };

        @Override
        public Set<IconSet> getIconSets(Locale locale) {
            return Collections.emptySet();
        };

        @Override
        public Integer getPriority() {
            return 0;
        };
    };
}

From source file:org.eclipse.smarthome.ui.icon.internal.IconServlet.java

private String getCategory(HttpServletRequest req) {
    String category = StringUtils.substringAfterLast(req.getRequestURI(), "/");
    category = StringUtils.substringBeforeLast(category, ".");
    return StringUtils.substringBeforeLast(category, "-");
}

From source file:org.eclipse.smarthome.ui.icon.internal.IconServlet.java

private String getState(HttpServletRequest req) {
    String state = req.getParameter(PARAM_STATE);
    if (state != null) {
        return state;
    } else {/*w w  w  . j  a v a2  s.c o m*/
        String filename = StringUtils.substringAfterLast(req.getRequestURI(), "/");
        state = StringUtils.substringAfterLast(filename, "-");
        state = StringUtils.substringBeforeLast(state, ".");
        if (StringUtils.isNotEmpty(state)) {
            return state;
        } else {
            return null;
        }
    }
}

From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarAllClasses(JarInputStream jarStream) throws Exception {
    // load all classes
    List<PaletteElementInfo> elements = Lists.newArrayList();
    try {/*from w w  w. j a v a2  s  .c o  m*/
        while (true) {
            JarEntry jarEntry = jarStream.getNextJarEntry();
            if (jarEntry == null) {
                break;
            }
            String jarEntryName = jarEntry.getName();
            if (jarEntryName.endsWith(JAVA_BEAN_CLASS_SUFFIX)) {
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(jarEntryName, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    } catch (Throwable e) {
        DesignerPlugin.log(e);
    }
    // sort element over class name
    Collections.sort(elements, new Comparator<PaletteElementInfo>() {
        public int compare(PaletteElementInfo element0, PaletteElementInfo element1) {
            return element0.className.compareToIgnoreCase(element1.className);
        }
    });
    return elements;
}

From source file:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarByManifest(JarInputStream jarStream) throws Exception {
    List<PaletteElementInfo> elements = Lists.newArrayList();
    Manifest manifest = jarStream.getManifest();
    // check manifest, if null find it
    if (manifest == null) {
        try {//w ww  .  j a v a 2  s .c  o  m
            while (true) {
                JarEntry entry = jarStream.getNextJarEntry();
                if (entry == null) {
                    break;
                }
                if (JarFile.MANIFEST_NAME.equalsIgnoreCase(entry.getName())) {
                    // read manifest data
                    byte[] buffer = IOUtils.toByteArray(jarStream);
                    jarStream.closeEntry();
                    // create manifest
                    manifest = new Manifest(new ByteArrayInputStream(buffer));
                    break;
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
            manifest = null;
        }
    }
    if (manifest != null) {
        // extract all "Java-Bean: True" classes
        for (Iterator<Map.Entry<String, Attributes>> I = manifest.getEntries().entrySet().iterator(); I
                .hasNext();) {
            Map.Entry<String, Attributes> mapElement = I.next();
            Attributes attributes = mapElement.getValue();
            if (JAVA_BEAN_VALUE.equalsIgnoreCase(attributes.getValue(JAVA_BEAN_KEY))) {
                String beanClass = mapElement.getKey();
                if (beanClass == null || beanClass.length() <= JAVA_BEAN_CLASS_SUFFIX.length()) {
                    continue;
                }
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(beanClass, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    }
    return elements;
}

From source file:org.eclipse.wb.internal.core.gef.policy.layout.generic.SelectionEditPolicyInstaller.java

/**
 * Try to find {@link SelectionEditPolicy} and use to decorate child {@link EditPart}.
 *///  w w w  .  j av  a2  s.  c  om
public void decorate() {
    IParametersProvider parametersProvider = GlobalState.getParametersProvider();
    // use main package
    {
        String packageName = StringUtils.substringBeforeLast(containerClassName, ".model.");
        if (decorate(packageName)) {
            return;
        }
    }
    // use "related" packages
    for (int i = 1; i < 10; i++) {
        String parameterName = "GEF.relatedToolkitPackages." + i;
        String packageName = parametersProvider.getParameter(container, parameterName);
        if (packageName != null) {
            if (decorate(packageName)) {
                return;
            }
        }
    }
    // use default policy
    {
        String policyClassName = parametersProvider.getParameter(container, "GEF.defaultSelectionPolicy");
        if (!StringUtils.isBlank(policyClassName)) {
            policyClassName = policyClassName.trim();
            try {
                ClassLoader classLoader = container.getClass().getClassLoader();
                Class<?> policyClass = classLoader.loadClass(policyClassName);
                SelectionEditPolicy policy = createPolicy(policyClass);
                if (policy != null) {
                    childPart.installEditPolicy(EditPolicy.SELECTION_ROLE, policy);
                    return;
                }
            } catch (Throwable e) {
            }
        }
    }
}

From source file:org.eclipse.wb.internal.core.gef.policy.layout.generic.SelectionEditPolicyInstaller.java

/**
 * Loads policy {@link Class} with given name, from given package and its parents.
 *///from  w  ww. jav a2  s  .c om
private Class<?> loadClass2(String basePackageName, String name) {
    String baseClassName = basePackageName + ".gef.policy." + name + "SelectionEditPolicy";
    String packageName = StringUtils.substringBeforeLast(baseClassName, ".");
    String className = StringUtils.substringAfterLast(baseClassName, ".");
    // check package and its parents
    ClassLoader classLoader = container.getClass().getClassLoader();
    while (packageName.contains(".")) {
        try {
            String policyClassName = packageName + "." + className;
            return classLoader.loadClass(policyClassName);
        } catch (Throwable e) {
        }
        packageName = StringUtils.substringBeforeLast(packageName, ".");
    }
    // no class
    return null;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ProjectClassLoader.java

@Override
protected Class<?> findClass(String className) throws ClassNotFoundException {
    String classResourceName = className.replace('.', '/') + ".class";
    InputStream input = getResourceAsStream(classResourceName);
    if (input == null) {
        throw new ClassNotFoundException(className);
    } else {//from  www.jav a 2s.co  m
        try {
            // read class bytes
            byte[] bytes = IOUtils2.readBytes(input);
            // apply processors
            for (IByteCodeProcessor processor : m_processors) {
                bytes = processor.process(className, bytes);
            }
            // implement abstract methods (only for required classes)
            if (m_nonAbstractClasses.contains(className)) {
                ClassReader classReader = new ClassReader(bytes);
                AbstractMethodsImplementorVisitor rewriter = new AbstractMethodsImplementorVisitor(className);
                classReader.accept(rewriter, 0);
                bytes = rewriter.toByteArray();
            }
            // define package
            {
                String pkgName = StringUtils.substringBeforeLast(className, ".");
                if (getPackage(pkgName) == null) {
                    definePackage(pkgName, null, null, null, null, null, null, null);
                }
            }
            // return (possibly modified) class
            ensureCodeSource();
            return defineClass(className, bytes, 0, bytes.length, m_fakeCodeSource);
        } catch (Throwable e) {
            throw new ClassNotFoundException("Error loading class " + className, e);
        }
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * Returns the short name of {@link Class}, or same name for simple type name.
 * // w w w.  j  a v a2s . c  o  m
 * <pre>
  * getShortName("javax.swing.JPanel")  = "JPanel"
  * getShortName("boolean")             = "boolean"
  * </pre>
 * 
 * @return the short name of given {@link Class}.
 */
public static String getShortName(Class<?> clazz) {
    String className = getFullyQualifiedName(clazz, false);
    // member Class
    if (clazz.isMemberClass()) {
        Class<?> topClass = getTopLevelClass(clazz);
        String topName = topClass.getName();
        String topPackage = StringUtils.substringBeforeLast(topName, ".") + ".";
        return className.substring(topPackage.length());
    }
    // normal top level Class, may be array
    if (className.indexOf('.') != -1) {
        return StringUtils.substringAfterLast(className, ".");
    }
    // primitive or default package
    return className;
}