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.gradle.groovy.scripts.AbstractUriScriptSource.java

/**
 * Returns the class name for use for this script source.  The name is intended to be unique to support mapping
 * class names to source files even if many sources have the same file name (e.g. build.gradle).
 *//*from  ww w .  ja va2  s  .  c o  m*/
public String getClassName() {
    if (className == null) {
        URI sourceUri = getResource().getURI();
        String name = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(sourceUri.toString(), "/"),
                ".");
        StringBuilder className = new StringBuilder(name.length());
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                className.append(ch);
            } else {
                className.append('_');
            }
        }
        if (!Character.isJavaIdentifierStart(className.charAt(0))) {
            className.insert(0, '_');
        }
        className.setLength(Math.min(className.length(), 30));
        className.append('_');
        String path = sourceUri.toString();
        className.append(HashUtil.createCompactMD5(path));

        this.className = className.toString();
    }

    return className;
}

From source file:org.gradle.groovy.scripts.UriScriptSource.java

/**
 * Returns the class name for use for this script source.  The name is intended to be unique to support mapping
 * class names to source files even if many sources have the same file name (e.g. build.gradle).
 *//*from   w w  w.  java  2  s.  co  m*/
public String getClassName() {
    if (className == null) {
        URI sourceUri = resource.getURI();
        String name = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(sourceUri.toString(), "/"),
                ".");
        StringBuilder className = new StringBuilder(name.length());
        for (int i = 0; i < name.length(); i++) {
            char ch = name.charAt(i);
            if (Character.isJavaIdentifierPart(ch)) {
                className.append(ch);
            } else {
                className.append('_');
            }
        }
        if (!Character.isJavaIdentifierStart(className.charAt(0))) {
            className.insert(0, '_');
        }
        className.setLength(Math.min(className.length(), 30));
        className.append('_');
        String path = sourceUri.toString();
        className.append(HashUtil.createCompactMD5(path));

        this.className = className.toString();
    }

    return className;
}

From source file:org.gradle.initialization.ExceptionDecoratingClassGenerator.java

private <T> Class<? extends T> doGenerate(Class<T> type) {
    ClassWriter visitor = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    String typeName = StringUtils.substringBeforeLast(type.getName(), ".") + ".LocationAware"
            + type.getSimpleName();//w w  w. j a  v  a2s .c o  m
    Type generatedType = Type.getType("L" + typeName.replaceAll("\\.", "/") + ";");
    Type superclassType = Type.getType(type);

    visitor.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, generatedType.getInternalName(), null,
            superclassType.getInternalName(),
            new String[] { Type.getType(LocationAwareException.class).getInternalName() });

    Type helperType = Type.getType(ExceptionHelper.class);
    Type throwableType = Type.getType(Throwable.class);
    Type scriptSourceType = Type.getType(ScriptSource.class);
    Type integerType = Type.getType(Integer.class);

    // GENERATE private ExceptionHelper helper;
    visitor.visitField(Opcodes.ACC_PRIVATE, "helper", helperType.getDescriptor(), null, null);

    // GENERATE <init>(<type> target, ScriptSource source, Integer lineNumber)

    String methodDescriptor = Type.getMethodDescriptor(Type.VOID_TYPE,
            new Type[] { superclassType, scriptSourceType, integerType });
    MethodVisitor methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null,
            new String[0]);
    methodVisitor.visitCode();

    boolean noArgsConstructor;
    try {
        type.getConstructor(type);
        noArgsConstructor = false;
    } catch (NoSuchMethodException e) {
        try {
            type.getConstructor();
            noArgsConstructor = true;
        } catch (NoSuchMethodException e1) {
            throw new IllegalArgumentException(String.format(
                    "Cannot create subtype for exception '%s'. It needs a zero-args or copy constructor.",
                    type.getName()));
        }
    }

    if (noArgsConstructor) {
        // GENERATE super()
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[0]));
        // END super()
    } else {
        // GENERATE super(target)
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
        methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, superclassType.getInternalName(), "<init>",
                Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { superclassType }));
        // END super(target)
    }

    // GENERATE helper = new ExceptionHelper(this, target, source, lineNumber)
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);

    methodVisitor.visitTypeInsn(Opcodes.NEW, helperType.getInternalName());
    methodVisitor.visitInsn(Opcodes.DUP);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 1);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 2);
    methodVisitor.visitVarInsn(Opcodes.ALOAD, 3);
    methodVisitor.visitMethodInsn(Opcodes.INVOKESPECIAL, helperType.getInternalName(), "<init>",
            Type.getMethodDescriptor(Type.VOID_TYPE,
                    new Type[] { throwableType, throwableType, scriptSourceType, integerType }));

    methodVisitor.visitFieldInsn(Opcodes.PUTFIELD, generatedType.getInternalName(), "helper",
            helperType.getDescriptor());

    // END helper = new ExceptionHelper(target)

    methodVisitor.visitInsn(Opcodes.RETURN);
    methodVisitor.visitMaxs(0, 0);
    methodVisitor.visitEnd();

    // END <init>(<type> target, ScriptSource source, Integer lineNumber)

    for (Method method : ExceptionHelper.class.getDeclaredMethods()) {
        // GENERATE public <type> <method>() { return helper.<method>(); }
        methodDescriptor = Type.getMethodDescriptor(Type.getType(method.getReturnType()), new Type[0]);
        methodVisitor = visitor.visitMethod(Opcodes.ACC_PUBLIC, method.getName(), methodDescriptor, null,
                new String[0]);
        methodVisitor.visitCode();

        methodVisitor.visitVarInsn(Opcodes.ALOAD, 0);
        methodVisitor.visitFieldInsn(Opcodes.GETFIELD, generatedType.getInternalName(), "helper",
                helperType.getDescriptor());
        methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, helperType.getInternalName(), method.getName(),
                methodDescriptor);

        methodVisitor.visitInsn(Opcodes.ARETURN);
        methodVisitor.visitMaxs(0, 0);
        methodVisitor.visitEnd();
        // END public <type> <method>() { return helper.<method>(); }
    }

    visitor.visitEnd();

    byte[] bytecode = visitor.toByteArray();
    return (Class<T>) ReflectionUtil.invoke(type.getClassLoader(), "defineClass",
            new Object[] { typeName, bytecode, 0, bytecode.length });
}

From source file:org.gradle.internal.classloader.TransformingClassLoader.java

@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    if (!shouldTransform(name)) {
        return super.findClass(name);
    }/*  ww  w  .  j  a v  a 2  s.  com*/

    String resourceName = name.replace('.', '/') + ".class";
    URL resource = findResource(resourceName);

    byte[] bytes;
    CodeSource codeSource;
    try {
        if (resource != null) {
            bytes = loadBytecode(resource);
            bytes = transform(name, bytes);
            URL codeBase = ClasspathUtil.getClasspathForResource(resource, resourceName).toURI().toURL();
            codeSource = new CodeSource(codeBase, (Certificate[]) null);
        } else {
            bytes = generateMissingClass(name);
            codeSource = null;
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not load class '%s' from %s.", name, resource), e);
    }

    if (bytes == null) {
        throw new ClassNotFoundException(name);
    }

    String packageName = StringUtils.substringBeforeLast(name, ".");
    Package p = getPackage(packageName);
    if (p == null) {
        definePackage(packageName, null, null, null, null, null, null, null);
    }
    return defineClass(name, bytes, 0, bytes.length, codeSource);
}

From source file:org.gradle.messaging.remote.internal.HandshakeOutgoingConnector.java

private URI toConnectionAddress(URI destinationAddress) {
    String content = destinationAddress.getSchemeSpecificPart();
    URI connectionAddress;//from  ww w.ja va 2  s  .  c o  m
    try {
        connectionAddress = new URI(StringUtils.substringBeforeLast(content, "!"));
    } catch (URISyntaxException e) {
        throw new UncheckedException(e);
    }
    return connectionAddress;
}

From source file:org.hippoecm.frontend.plugins.console.menu.copy.CopyDialog.java

public CopyDialog(IModelReference<Node> modelReference) {
    super(new JcrTreeNode(new JcrNodeModel("/"), null, new JcrTreeNodeComparator()), modelReference.getModel());
    this.modelReference = modelReference;
    JcrNodeModel model = (JcrNodeModel) modelReference.getModel();
    setSelectedNode(model);/*from  w w  w .java  2 s . co m*/

    try {
        if (model.getParentModel() != null) {
            setSelectedNode(model.getParentModel());

            add(new Label("source", model.getNode().getPath()));

            target = StringUtils.substringBeforeLast(model.getNode().getPath(), "/") + "/";
            targetLabel = new Label("target", new PropertyModel(this, "target"));
            targetLabel.setOutputMarkupId(true);
            add(targetLabel);

            name = model.getNode().getName();
            TextFieldWidget nameField = new AutoFocusSelectTextFieldWidget("name",
                    new PropertyModel<String>(this, "name"));
            nameField.setSize(String.valueOf(name.length() + 5));
            add(nameField);

            LabelledBooleanFieldWidget checkbox = new LabelledBooleanFieldWidget("generate",
                    new PropertyModel<Boolean>(this, "generate"), Model.of("Generate new translation ids"));
            add(checkbox);
        } else {
            add(new Label("source", "Cannot copy the root node"));
            add(new EmptyPanel("target"));
            add(new EmptyPanel("name"));
            add(new EmptyPanel("generate"));
            setOkVisible(false);
            setFocusOnCancel();
        }
    } catch (RepositoryException e) {
        log.error(e.getMessage());
        add(new Label("source", e.getClass().getName()));
        add(new Label("target", e.getMessage()));
        add(new EmptyPanel("name"));
        setOkVisible(false);
        setFocusOnCancel();
    }
}

From source file:org.hippoecm.frontend.plugins.console.menu.move.MoveDialog.java

public MoveDialog(IModelReference<Node> modelReference) {
    super(new JcrTreeNode(new JcrNodeModel("/"), null, new JcrTreeNodeComparator()), modelReference.getModel());
    this.modelReference = modelReference;
    JcrNodeModel model = (JcrNodeModel) modelReference.getModel();

    try {//from w w  w  . ja va  2 s .  co  m
        if (model.getParentModel() != null) {
            setSelectedNode(model.getParentModel());

            add(new Label("source", model.getNode().getPath()));

            target = StringUtils.substringBeforeLast(model.getNode().getPath(), "/") + "/";
            targetLabel = new Label("target", new PropertyModel(this, "target"));
            targetLabel.setOutputMarkupId(true);
            add(targetLabel);

            name = model.getNode().getName();
            TextFieldWidget nameField = new AutoFocusSelectTextFieldWidget("name",
                    new PropertyModel<String>(this, "name"));
            nameField.setSize(String.valueOf(name.length() + 5));
            add(nameField);
        } else {
            add(new Label("source", "Cannot move the root node"));
            add(new EmptyPanel("target"));
            add(new EmptyPanel("name"));
            setOkVisible(false);
            setFocusOnCancel();
        }
    } catch (RepositoryException e) {
        log.error(e.getMessage());
        add(new Label("source", e.getClass().getName()));
        add(new Label("target", e.getMessage()));
        add(new EmptyPanel("name"));
        setOkVisible(false);
        setFocusOnCancel();
    }
}

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

private static String getLanguageCode(String resourceBundleFileName) {
    String name = StringUtils.substringBeforeLast(resourceBundleFileName, ".properties");
    String lang = GWTResourceBundle.DEFAULT_LANG;
    if (name.contains("_")) {
        String[] parts = Patterns.UNDERSCORE.split(name);
        int l = parts.length;
        if (l == 2) {
            lang = parts[1];/*from  w w w .j a v  a 2  s.c om*/
        } else if (l == 3) {
            lang = parts[1] + "_" + parts[2];
        } else if (l >= 4) {
            lang = parts[l - 3] + "_" + parts[l - 2] + "_" + parts[l - 1];
        }
    }

    return lang;
}

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

private static void populate(GWTResourceBundle gwtBundle, JCRNodeWrapper node, Set<String> languages) {

    String name = StringUtils.substringBeforeLast(node.getName(), ".properties");
    String lang = GWTResourceBundle.DEFAULT_LANG;
    if (name.contains("_")) {
        lang = getLanguageCode(name);//from  w  w  w.  ja v  a2s . co m
        if (gwtBundle.getName() == null) {
            name = StringUtils.substringBeforeLast(StringUtils.substringBeforeLast(name, lang), "_");
        }
    }
    if (gwtBundle.getName() == null) {
        gwtBundle.setName(name);
    }
    languages.add(lang);

    InputStream is = null;
    try {
        is = node.getFileContent().downloadFile();
        Properties p = new Properties();
        p.load(is);
        for (Object keyObj : p.keySet()) {
            String key = keyObj.toString();
            if (isValidKey(key)) {
                gwtBundle.setValue(key, lang, p.getProperty(key));
            }
        }
    } catch (IOException e) {
        logger.error("Error reading content of the " + node.getPath() + " node as a properties file. Cause: "
                + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

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

public static boolean store(GWTJahiaNode gwtNode, GWTResourceBundle bundle, JCRSessionWrapper session)
        throws GWTJahiaServiceException {
    boolean needPermissionReload = false;
    try {//w  w  w. j a v  a2  s .  co  m
        JCRNodeWrapper node = session.getNode(
                gwtNode.isFile() ? StringUtils.substringBeforeLast(gwtNode.getPath(), "/") : gwtNode.getPath());

        Map<String, JCRNodeWrapper> nodesByLanguage = new HashMap<String, JCRNodeWrapper>();
        for (JCRNodeWrapper rbFileNode : JCRContentUtils.getChildrenOfType(node, "jnt:propertiesFile")) {
            nodesByLanguage.put(getLanguageCode(rbFileNode.getName()), rbFileNode);
        }

        for (String lang : bundle.getLanguages()) {
            JCRNodeWrapper current = nodesByLanguage.remove(lang);
            InputStream is = null;
            try {
                is = new ByteArrayInputStream(getAsString(lang, bundle).getBytes("ISO-8859-1"));
                if (current == null) {
                    // new language
                    logger.debug("Processing new resource bundle for language '{}'", lang);
                    String bundleName;
                    if (StringUtils.equals(lang, GWTResourceBundle.DEFAULT_LANG)) {
                        bundleName = bundle.getName() + ".properties";
                    } else {
                        bundleName = bundle.getName() + "_" + lang + ".properties";
                    }
                    node.uploadFile(bundleName, is, "text/plain");
                } else {
                    // updating existing language
                    logger.debug("Processing resource bundle {} for language '{}'", current.getPath(), lang);
                    current.getFileContent().uploadFile(is, "text/plain");
                }
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException(e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }

        // removing deleted languages if any
        for (Iterator<JCRNodeWrapper> iterator = nodesByLanguage.values().iterator(); iterator.hasNext();) {
            JCRNodeWrapper toDelete = iterator.next();
            logger.debug("Removing resource bundle node {}", toDelete.getPath());
            toDelete.remove();
        }
        ResourceBundle.clearCache();
        NodeTypeRegistry.getInstance().flushLabels();
        needPermissionReload = !node.getResolveSite().getLanguages().containsAll(bundle.getLanguages());
        node.getResolveSite().setLanguages(bundle.getLanguages());
    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
        throw new GWTJahiaServiceException(e.getMessage());
    }
    return needPermissionReload;
}