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

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

Introduction

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

Prototype

public static String replaceChars(String str, String searchChars, String replaceChars) 

Source Link

Document

Replaces multiple characters in a String in one go.

Usage

From source file:org.ebayopensource.turmeric.eclipse.utils.wsdl.WSDLUtil.java

private static String[] getParentFolder(String fullFileName) {
    String[] result = new String[2];
    final String slash = "/";
    if (StringUtils.isNotBlank(fullFileName)) {
        fullFileName = StringUtils.replaceChars(fullFileName, File.separator, slash);
        result[0] = fullFileName.indexOf(slash) >= 0 ? StringUtils.substringBeforeLast(fullFileName, slash)
                : "";
        result[1] = StringUtils.substringAfterLast(fullFileName, "/");
    }/*from   w w  w .  ja va 2  s . c om*/
    return result;
}

From source file:org.eclipse.gyrex.jobs.internal.manager.StorableBackedJobHistoryEntry.java

@Override
public String toString() {
    final StringBuilder builder = new StringBuilder();
    builder.append(DateFormatUtils.SMTP_DATETIME_FORMAT.format(getTimeStamp())).append(" ");
    switch (getResult().getSeverity()) {
    case IStatus.OK:
        builder.append("OK");
        break;/*w ww .  j  a  va 2 s  . c o  m*/
    case IStatus.ERROR:
        builder.append("ERROR");
        break;
    case IStatus.WARNING:
        builder.append("WARNING");
        break;
    case IStatus.INFO:
        builder.append("INFO");
        break;
    case IStatus.CANCEL:
        builder.append("CANCEL");
        break;

    default:
        builder.append("severity=");
        builder.append(getResult().getSeverity());
        break;
    }
    if (StringUtils.isNotBlank(getResult().getMessage())) {
        builder.append(" ").append(
                StringUtils.replaceChars(CharSetUtils.delete(getResult().getMessage(), "\t\r\b"), '\n', '|'));
    }
    return builder.toString();
}

From source file:org.eclipse.gyrex.services.common.provider.BaseService.java

/**
 * Convenience method to create a well formated metrics id based on a
 * service implementation identifier (eg. a
 * <code>"com.company.xyz.services.impl"</code>) and a specified context.
 * //from w  w  w .  j ava 2 s.c o m
 * @param serviceImplementationId
 *            the service implementation identifier
 * @param context
 *            the context
 * @return a well formatted metrics id
 */
protected static String createMetricsId(final String serviceImplementationId, final IRuntimeContext context) {
    // handle context paths
    final String contextPath = StringUtils.replaceChars(
            context.getContextPath().removeTrailingSeparator().makeRelative().toString(), '/', '.');
    // create id
    return serviceImplementationId + "." + contextPath + ".metrics";
}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.ParamProposalProvider.java

/**
 * Creates and returns content proposals based on the Parameters available
 * from the parent node./*  w  w  w  . j  a  va2  s .  c o  m*/
 * 
 * @param contents The text for which to generate content proposals.
 * @return the proposals for the given arguments.
 */
private Collection<IContentProposal> getParentParamProposals(String contents) {

    List<IContentProposal> proposals = new ArrayList<IContentProposal>();

    // find a SpecTestCase
    INodePO node = m_node;
    while ((node != null) && !(node instanceof ISpecTestCasePO)) {
        node = node.getParentNode();
    }
    ISpecTestCasePO paramNode = (ISpecTestCasePO) node;

    if (!(m_node instanceof ISpecTestCasePO)) {
        // add the parameter name as a suggestion
        if (m_paramDesc != null && paramNode != null) {
            if (!paramNode.isInterfaceLocked() && !paramNode.getParamNames().contains(m_paramDesc.getName())) {
                String p = PARAMETER_PREFIX + m_paramDesc.getName();
                p = StringUtils.replaceChars(p, ' ', '_');
                p = StringUtils.replaceChars(p, '-', '_');
                p = p.toUpperCase();
                if (p.startsWith(contents)) {
                    proposals.add(new ParamProposal(p.substring(contents.length()), p));
                }
            }
        }

        if (paramNode != null) {
            List<IParamDescriptionPO> params = paramNode.getParameterList();
            for (IParamDescriptionPO param : params) {
                if (param.getType().equals(m_paramDesc.getType())) {
                    String p = PARAMETER_PREFIX + param.getName();
                    if (p.startsWith(contents)) {
                        proposals.add(new ParamProposal(p.substring(contents.length()), p));
                    }
                }
            }

        }
    }

    return proposals;
}

From source file:org.eclipse.wb.internal.core.editor.errors.report2.EnvironmentFileReportInfo.java

private static String createContents(IProject project) {
    String c = "";
    c += "Product Name: " + BrandingUtils.getBranding().getProductName() + CR;
    c += "Product Version: " + ProductInfo.getProduct().getVersion() + "[" + ProductInfo.getProduct().getBuild()
            + "]" + CR;
    c += "Installation Path: " + getInstallationPath() + CR;
    c += "Eclipse Version: " + PlatformInfo.getEclipseVersion().toString() + CR;
    c += "Eclipse Build Name: " + PlatformInfo.getEclipseBuildName() + CR;
    c += "Eclipse Build ID: " + PlatformInfo.getEclipseBuildId() + CR;
    c += "IDE Name: " + PlatformInfo.getIDEName() + CR;
    c += "IDE Version: " + PlatformInfo.getIDEVersionString() + CR;
    c += "IDE NL: " + PlatformInfo.getIDENL() + CR;
    c += "Eclipse Commands: " + StringUtils.replaceChars(getSystemProperty("eclipse.commands"), "\n\r", " ")
            + CR;/*from   w  w  w  . j  a va 2  s.c  o  m*/
    c += "Eclipse VM: " + getSystemProperty("eclipse.vm") + CR;
    c += "Eclipse VM Args: " + getSystemProperty("eclipse.vmargs") + CR;
    c += "OS Name: " + getSystemProperty("os.name") + CR;
    c += "OS Arch: " + getSystemProperty("os.arch") + CR;
    c += "OS Version: " + getSystemProperty("os.version") + CR;
    String linuxDescription = getLinuxDescription();
    if (!StringUtils.isEmpty(linuxDescription)) {
        c += "Linux Description: " + linuxDescription + CR;
    }
    String m_mozillaResult = tryCreateMozilla();
    if (!StringUtils.isEmpty(m_mozillaResult)) {
        c += "Browser Creation Result: " + m_mozillaResult + CR;
    }
    Runtime runtime = Runtime.getRuntime();
    c += "Available Processors: " + runtime.availableProcessors() + CR;
    c += "Memory Max: " + runtime.maxMemory() + CR;
    c += "Memory Total: " + runtime.totalMemory() + CR;
    c += "Memory Free: " + runtime.freeMemory() + CR;
    c += "Java Vendor: " + getSystemProperty("java.vendor") + CR;
    c += "Java Version: " + getSystemProperty("java.version") + CR;
    c += "Java Library Path: " + CR + getSystemProperty("java.library.path") + CR;
    c += "Project Class Path: " + CR + getClassPath(project) + CR;
    return c;
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * Returns the factory-method specific {@link ComponentDescription}.
 * <p>/*from ww  w .ja va2 s.  com*/
 * Sometimes you want to add specific tweaks for component, when it is created using factory. For
 * example - hide some properties, copy factory properties, etc.
 */
public static ComponentDescription getDescription(AstEditor editor,
        FactoryMethodDescription factoryMethodDescription) throws Exception {
    Class<?> componentClass = factoryMethodDescription.getReturnClass();
    // prepare description key
    ComponentDescriptionKey key;
    {
        String signature = factoryMethodDescription.getSignature();
        String signatureUnix = StringUtils.replaceChars(signature, "(,)", "___");
        Class<?> declaringClass = factoryMethodDescription.getDeclaringClass();
        ComponentDescriptionKey declaringKey = new ComponentDescriptionKey(declaringClass);
        key = new ComponentDescriptionKey(componentClass, declaringKey, signatureUnix);
    }
    // get key specific description
    return getKeySpecificDescription(editor, componentClass, key);
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.ComponentDescriptionHelper.java

/**
 * @param editor//from w w w  .j a  v a 2s  . c o  m
 *          the {@link AstEditor} in context of which we work now.
 * @param hostDescription
 *          the {@link ComponentDescription} that has method with given parameter.
 * @param parameter
 *          the {@link SingleVariableDeclaration} parameter that considered as component.
 * 
 * @return the {@link ComponentDescription} of component represented by given
 *         {@link SingleVariableDeclaration}.
 * @throws Exception
 *           if no {@link ComponentDescription} can be found.
 */
public static ComponentDescription getDescription(AstEditor editor, ComponentDescription hostDescription,
        SingleVariableDeclaration parameter) throws Exception {
    // prepare parameter Class
    Class<?> parameterClass;
    {
        String parameterClassName = AstNodeUtils.getFullyQualifiedName(parameter.getType(), true);
        parameterClass = EditorState.get(editor).getEditorLoader().loadClass(parameterClassName);
    }
    // prepare suffix
    String suffix;
    {
        MethodDeclaration methodDeclaration = (MethodDeclaration) parameter.getParent();
        String signature = AstNodeUtils.getMethodSignature(methodDeclaration);
        String signatureUnix = StringUtils.replaceChars(signature, "(,)", "___");
        int parameterIndex = DomGenerics.parameters(methodDeclaration).indexOf(parameter);
        suffix = signatureUnix + "." + parameterIndex;
    }
    // prepare DescriptionInfo's for parameter in inheritance hierarchy
    List<ClassResourceInfo> additionalDescriptions = Lists.newArrayList();
    {
        Class<?> hostComponentClass = hostDescription.getComponentClass();
        List<Class<?>> types = ReflectionUtils.getSuperHierarchy(hostComponentClass);
        types = Lists.reverse(types);
        for (Class<?> type : types) {
            ComponentDescriptionKey hostKey = new ComponentDescriptionKey(type);
            // prepare specific ResourceInfo
            ResourceInfo resourceInfo;
            {
                EditorState state = EditorState.get(editor);
                ILoadingContext context = EditorStateLoadingContext.get(state);
                String descriptionPath = hostKey.getName() + "." + suffix + ".wbp-component.xml";
                resourceInfo = DescriptionHelper.getResourceInfo(context, type, descriptionPath);
            }
            // add specific DescriptionInfo
            if (resourceInfo != null) {
                ClassResourceInfo descriptionInfo = new ClassResourceInfo(parameterClass, resourceInfo);
                additionalDescriptions.add(descriptionInfo);
            }
        }
    }
    // get key specific description
    if (additionalDescriptions.isEmpty()) {
        return getDescription(editor, parameterClass);
    } else {
        ComponentDescriptionKey key = new ComponentDescriptionKey(parameterClass, hostDescription.getKey(),
                suffix);
        return getDescription0(editor, key, additionalDescriptions);
    }
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.FactoryDescriptionHelper.java

/**
 * Implementation of {@link #getDescriptionsMap0(AstEditor, Class, boolean)} that can throw
 * exceptions./*  w w  w .  j  a  va  2  s  .  c  om*/
 */
private static Map<String, FactoryMethodDescription> getDescriptionsMap0Ex(AstEditor editor,
        Class<?> factoryClass, boolean forStatic) throws Exception {
    EditorState state = EditorState.get(editor);
    ILoadingContext context = EditorStateLoadingContext.get(state);
    // try to find cached map
    {
        Map<String, FactoryMethodDescription> signaturesMap = state.getFactorySignatures(factoryClass,
                forStatic);
        if (signaturesMap != null) {
            return signaturesMap;
        }
    }
    //
    String factoryClassName = factoryClass.getName();
    IType factoryType = editor.getJavaProject().findType(factoryClassName);
    if (factoryType == null) {
        return Maps.newTreeMap();
    }
    Boolean allMethodsAreFactories = null;
    List<FactoryMethodDescription> descriptions = Lists.newArrayList();
    // read descriptions from XML
    {
        String descriptionName = factoryClassName.replace('.', '/') + ".wbp-factory.xml";
        ResourceInfo resourceInfo = DescriptionHelper.getResourceInfo(context, factoryClass, descriptionName);
        if (resourceInfo != null) {
            Map<Integer, FactoryMethodDescription> textualDescriptions = Maps.newHashMap();
            Digester digester = prepareDigester(factoryClass, state, textualDescriptions);
            digester.push(allMethodsAreFactories);
            digester.push(descriptions);
            allMethodsAreFactories = (Boolean) digester.parse(resourceInfo.getURL());
            readTextualDescriptions(resourceInfo, textualDescriptions);
        }
    }
    // prepare map: signature -> description
    Map<String, FactoryMethodDescription> signaturesMap = Maps.newTreeMap();
    for (FactoryMethodDescription description : descriptions) {
        signaturesMap.put(description.getSignature(), description);
    }
    // factory flag for not-wbp methods
    if (allMethodsAreFactories == null) {
        allMethodsAreFactories = hasFactorySuffix(factoryType) || hasFactoryTag(factoryType);
    }
    // if no methods from XML, may be no methods at all
    if (!allMethodsAreFactories.booleanValue() && descriptions.isEmpty() && !hasFactoryTagSource(factoryType)) {
        return Maps.newTreeMap();
    }
    // add descriptions for all methods, using JavaDoc
    {
        // prepare methods
        Method[] methods;
        IMethod[] modelMethods;
        {
            methods = factoryClass.getDeclaredMethods();
            // prepare signatures for "public static" methods
            String[] signatures = new String[methods.length];
            for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
                Method factoryMethod = methods[methodIndex];
                // check modifiers
                {
                    int modifiers = factoryMethod.getModifiers();
                    if (!hasValidVisibility(editor, factoryMethod)) {
                        continue;
                    }
                    if (forStatic && !java.lang.reflect.Modifier.isStatic(modifiers)) {
                        continue;
                    }
                }
                // check return type
                {
                    Class<?> returnType = factoryMethod.getReturnType();
                    // method that returns "primitive" can not be factory method
                    if (returnType.isPrimitive()) {
                        continue;
                    }
                    // special case - filter out getters
                    if (factoryMethod.getParameterTypes().length == 0
                            && factoryMethod.getName().startsWith("get")) {
                        continue;
                    }
                }
                // OK, valid method
                signatures[methodIndex] = ReflectionUtils.getMethodSignature(factoryMethod);
            }
            // prepare model methods
            modelMethods = CodeUtils.findMethods(factoryType, signatures);
        }
        // prepare factory description for each method
        for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
            Method factoryMethod = methods[methodIndex];
            IMethod modelMethod = modelMethods[methodIndex];
            if (modelMethod == null) {
                continue;
            }
            // prepare description
            FactoryMethodDescription description;
            {
                String signature = ReflectionUtils.getMethodSignature(factoryMethod);
                description = signaturesMap.get(signature);
                // create description if not exists
                if (description == null) {
                    description = new FactoryMethodDescription(factoryClass);
                    description.setName(factoryMethod.getName());
                    description.setFactory(allMethodsAreFactories);
                    signaturesMap.put(signature, description);
                }
            }
            // configure description
            description.setModelMethod(modelMethod);
            description.setReturnClass(factoryMethod.getReturnType());
            // check parameters
            {
                Class<?>[] parameterTypes = factoryMethod.getParameterTypes();
                for (int parameterIndex = 0; parameterIndex < parameterTypes.length; parameterIndex++) {
                    Class<?> parameterType = parameterTypes[parameterIndex];
                    // prepare parameter
                    ParameterDescription parameterDescription;
                    if (parameterIndex < description.getParameters().size()) {
                        parameterDescription = description.getParameter(parameterIndex);
                    } else {
                        parameterDescription = new ParameterDescription();
                        parameterDescription.setType(parameterType);
                        description.addParameter(parameterDescription);
                    }
                }
                //
                description.postProcess();
            }
            // try to mark as factory
            if (!description.isFactory()) {
                updateDescriptionsJavaDoc0(editor, description);
            }
        }
    }
    // remove incompatible instance/static methods
    for (Iterator<FactoryMethodDescription> I = signaturesMap.values().iterator(); I.hasNext();) {
        FactoryMethodDescription description = I.next();
        Method method = ReflectionUtils.getMethodBySignature(factoryClass, description.getSignature());
        int modifiers = method.getModifiers();
        if (forStatic ^ java.lang.reflect.Modifier.isStatic(modifiers)) {
            I.remove();
        }
    }
    // remove descriptions without "factory" flag
    for (Iterator<FactoryMethodDescription> I = signaturesMap.values().iterator(); I.hasNext();) {
        FactoryMethodDescription description = I.next();
        if (!description.isFactory()) {
            I.remove();
        }
    }
    // process JavaDoc
    for (FactoryMethodDescription description : signaturesMap.values()) {
        updateDescriptionsJavaDoc(editor, description);
    }
    // load icons
    for (Map.Entry<String, FactoryMethodDescription> entry : signaturesMap.entrySet()) {
        FactoryMethodDescription description = entry.getValue();
        // prepare icon
        Image icon;
        {
            String signature = entry.getKey();
            String signatureUnix = StringUtils.replaceChars(signature, "(,)", "___");
            String iconPath = factoryClassName.replace('.', '/') + "." + signatureUnix;
            icon = DescriptionHelper.getIconImage(context, iconPath);
            description.setIcon(icon);
        }
        // schedule disposing
        {
            String name = description.getDeclaringClass().getName() + "." + description.getSignature();
            ImageDisposer.add(description, name, icon);
        }
    }
    // remember descriptions in cache
    state.putFactorySignatures(factoryClass, forStatic, signaturesMap);
    return signaturesMap;
}

From source file:org.eclipse.wb.internal.core.model.variable.NamesManager.java

/**
 * @return the default acronym of the given component class.
 * // www  .  j  av a  2 s  . c o m
 * <pre>
  * org.eclipse.swt.widgets.Button    = btn
  * javax.swing.JButton               = btn
  * org.eclipse.swt.custom.StyledText = stldtxt
  * </pre>
 */
private static String getDefaultAcronym(String qualifiedClassName) {
    String shortClassName = CodeUtils.getShortClass(qualifiedClassName);
    String acronym = StringUtilities.stripLeadingUppercaseChars(shortClassName, 1).toLowerCase();
    // remove vowels
    acronym = StringUtils.replaceChars(acronym, "aeiouy", null);
    // remove sequential duplicate symbols
    acronym = StringUtilities.removeDuplicateCharacters(acronym);
    // check final result
    if (acronym.length() == 0) {
        return shortClassName;
    } else {
        return acronym;
    }
}

From source file:org.ejbca.ui.web.pub.CertDistServlet.java

private void handleCaChainCommands(AuthenticationToken administrator, String issuerdn, int caid, String format,
        HttpServletResponse res) throws IOException, NoSuchFieldException {
    try {//from ww w.  j av  a  2 s  .c  o  m
        Certificate[] chain = getCertificateChain(administrator, caid, issuerdn);
        // Reverse the chain to get proper ordering for chain file
        // (top-level CA first, requested CA last).
        ArrayUtils.reverse(chain);

        // Construct the filename based on requested CA. Fail-back to
        // name "ca-chain.EXT".
        String filename = RequestHelper.getFileNameFromCertNoEnding(chain[chain.length - 1], "ca") + "-chain."
                + format.toLowerCase();

        byte[] outbytes = new byte[0];
        // Encode and send back
        if ((format == null) || StringUtils.equalsIgnoreCase(format, "pem")) {
            outbytes = CertTools.getPemFromCertificateChain(Arrays.asList(chain));
        } else {
            // Create a JKS truststore with the CA certificates in
            final KeyStore store = KeyStore.getInstance("JKS");
            store.load(null, null);
            for (int i = 0; i < chain.length; i++) {
                String cadn = CertTools.getSubjectDN(chain[i]);
                String alias = CertTools.getPartFromDN(cadn, "CN");
                if (alias == null) {
                    alias = CertTools.getPartFromDN(cadn, "O");
                }
                if (alias == null) {
                    alias = "cacert" + i;
                }
                alias = StringUtils.replaceChars(alias, ' ', '_');
                alias = StringUtils.substring(alias, 0, 15);
                store.setCertificateEntry(alias, chain[i]);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                store.store(out, "changeit".toCharArray());
                out.close();
                outbytes = out.toByteArray();
            }
        }
        // We must remove cache headers for IE
        ServletUtils.removeCacheHeaders(res);
        res.setHeader("Content-disposition",
                "attachment; filename=\"" + StringTools.stripFilename(filename) + "\"");
        res.setContentType("application/octet-stream");
        res.setContentLength(outbytes.length);
        res.getOutputStream().write(outbytes);
        log.debug("Sent CA certificate chain to client, len=" + outbytes.length + ".");
    } catch (CertificateEncodingException e) {
        log.debug("Error getting CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error getting CA certificate chain.");
    } catch (KeyStoreException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (NoSuchAlgorithmException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (CertificateException e) {
        log.debug("Error creating JKS with CA certificate chain: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND, "Error creating JKS with CA certificate chain.");
    } catch (EJBException e) {
        log.debug("CA does not exist: ", e);
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "CA does not exist: " + HTMLTools.htmlescape(e.getMessage()));
    } catch (AuthorizationDeniedException e) {
        log.debug("Authotization denied: ", e);
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Authorization denied: " + HTMLTools.htmlescape(e.getMessage()));
    }
}