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

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

Introduction

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

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:org.eclipse.jubula.rc.common.util.PropertyUtil.java

/**
 * Returns a sorted map consisting of the bean properties of a component
 * //from   ww  w .j  a  v a 2  s  .com
 * @param currComp 
 *              the component
 * @return the sorted map of properties
 */
public static Map getMapOfComponentProperties(final Object currComp) {
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(currComp);
    Map componentProperties = new TreeMap();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor pd = propertyDescriptors[i];
        try {
            Method readMethod = pd.getReadMethod();
            if (readMethod != null) {
                Object obj = readMethod.invoke(currComp, new Object[] {});
                String value = String.valueOf(obj);
                if (value.length() > 200) {
                    value = StringUtils.substring(value, 0, 200);
                }
                if (obj instanceof Character) {
                    Character c = (Character) obj;
                    if (c.charValue() == 0) {
                        value = ""; //$NON-NLS-1$
                    }
                }
                componentProperties.put(pd.getName(), value);
            } else {
                componentProperties.put(pd.getName(), "This property is not readable"); //$NON-NLS-1$
            }
        } catch (IllegalArgumentException e) {
            componentProperties.put(pd.getName(), "Error"); //$NON-NLS-1$
        } catch (IllegalAccessException e) {
            componentProperties.put(pd.getName(), "Error accessing this property"); //$NON-NLS-1$
        } catch (InvocationTargetException e) {
            componentProperties.put(pd.getName(), "Error reading this property"); //$NON-NLS-1$
        }
    }
    return componentProperties;
}

From source file:org.eclipse.skalli.testutil.HttpServerMock.java

@Override
public void run() {
    BufferedReader request = null;
    DataOutputStream response = null;
    try {/*from   w ww  . j a v  a2 s.com*/
        server = new ServerSocket(port);
        while (true) {
            Socket connection = server.accept();

            request = new BufferedReader(new InputStreamReader(connection.getInputStream(), "ISO8859_1"));
            response = new DataOutputStream(connection.getOutputStream());

            String httpCode;
            String contentId = "";
            String requestLine = request.readLine();

            if (!StringUtils.startsWithIgnoreCase(requestLine, "GET")) {
                httpCode = "405";
            } else {
                String path = StringUtils.split(requestLine, " ")[1];
                int n = StringUtils.lastIndexOf(path, "/");
                contentId = StringUtils.substring(path, 1, n);
                httpCode = StringUtils.substring(path, n + 1);
            }

            String content = bodies.get(contentId);
            StringBuffer sb = new StringBuffer();
            sb.append("HTTP/1.1 ").append(httpCode).append(" CustomStatus\r\n");
            sb.append("Server: MiniMockUnitServer\r\n");
            sb.append("Content-Type: text/plain\r\n");
            if (content != null) {
                sb.append("Content-Length: ").append(content.length()).append("\r\n");
            }
            sb.append("Connection: close\r\n");
            sb.append("\r\n");
            if (content != null) {
                sb.append(content);
            }

            response.writeBytes(sb.toString());
            IOUtils.closeQuietly(response);
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(request);
        IOUtils.closeQuietly(response);
    } finally {
        try {
            server.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.eclipse.smarthome.binding.homematic.internal.type.MetadataUtils.java

/**
 * Returns the description for the given keys.
 *///from   w  w  w.  j  a  va  2s .c om
public static String getDescription(String... keys) {
    StringBuilder sb = new StringBuilder();
    for (int startIdx = 0; startIdx < keys.length; startIdx++) {
        String key = StringUtils.join(keys, "|", startIdx, keys.length);
        if (key.endsWith("|")) {
            key = key.substring(0, key.length() - 1);
        }
        String description = descriptions.get(key);
        if (description != null) {
            return description;
        }
        sb.append(key).append(", ");
    }
    if (logger.isTraceEnabled()) {
        logger.trace("Description not found for: {}", StringUtils.substring(sb.toString(), 0, -2));
    }
    return null;
}

From source file:org.eclipse.wb.android.internal.support.DeviceManager.java

/**
 * @return the {@link DisplayMetrics} for given xVGA+dpi string or <code>null</code> if unknown.
 *//* www  . j a va  2s.  c  om*/
public static DisplayMetrics getXvgaDpiMetrics(final String value) {
    int delimiter = StringUtils.indexOf(value, "/");
    if (delimiter == -1) {
        return null;
    }
    String xvgaString = StringUtils.substring(value, 0, delimiter);
    String densityString = StringUtils.substring(value, delimiter + 1);
    Dimension resolution = parseXvga(xvgaString);
    DisplayMetrics metrics;
    if (resolution != null) {
        Density density = parseDensity(densityString);
        metrics = new DisplayMetricsImpl(resolution.width, resolution.height, density) {
            @Override
            public String getPrompt() {
                return value;
            }

            @Override
            public void setThis(IResource resource) {
                try {
                    resource.setPersistentProperty(KEY_xVGA_DPI, value);
                } catch (Exception e) {
                    DesignerPlugin.log(e);
                }
            };
        };
    } else {
        // unknown
        metrics = null;
    }
    return metrics;
}

From source file:org.eclipse.wb.internal.core.model.description.rules.MethodsOperationRule.java

private void processRegexp(final String signature) throws Exception {
    final Pattern pattern = Pattern.compile(StringUtils.substring(signature, 1, -1));
    process(new Predicate<String>() {
        public boolean apply(String t) {
            return pattern.matcher(t).matches();
        }//from   w ww.  j  av a 2s  . c  o  m
    });
}

From source file:org.eclipse.wb.internal.core.nls.bundle.AbstractBundleSourceNewComposite.java

protected final void fillPropertyParameters(AbstractBundleSourceParameters parameters) throws Exception {
    parameters.m_propertySourceFolder = m_propertyPackageField.getRoot();
    parameters.m_propertyPackage = m_propertyPackageField.getPackage();
    parameters.m_propertyFileName = m_propertyFileField.getText();
    // prepare m_propertyBundleName
    {//from w  ww . j a  va  2 s  .  co m
        IPackageFragment property_package = m_propertyPackageField.getPackage();
        if (property_package != null) {
            String property_packageName = property_package.getElementName();
            String property_fileName = m_propertyFileField.getText();
            String property_bundleName = StringUtils.substring(property_fileName, 0, -".properties".length());
            if (property_packageName.length() != 0) {
                parameters.m_propertyBundleName = property_packageName + "." + property_bundleName;
            } else {
                parameters.m_propertyBundleName = property_bundleName;
            }
        }
    }
    // prepare m_propertyFileExists
    if (parameters.m_propertyPackage != null) {
        IFolder property_folder = (IFolder) parameters.m_propertyPackage.getUnderlyingResource();
        parameters.m_propertyFileExists = property_folder.getFile(parameters.m_propertyFileName).exists();
    }
}

From source file:org.eclipse.wb.internal.core.nls.bundle.BundleInfo.java

/**
 * @return the {@link LocaleInfo} extracted from {@link IFile} using name of bundle. For example,
 *         return ru_RU locale for bundle "com.mycorp.messages" and file
 *         "com/mycorp/messages_ru_RU.properties".
 *//*from w w w. ja  va2 s .c o m*/
public static LocaleInfo getLocale(String bundleName, IFile file) {
    // prepare name of locale, for example "_ru_RU"
    String shortBundleName = CodeUtils.getShortClass(bundleName);
    String localeName = file.getName();
    localeName = StringUtils.substring(localeName, 0, -".properties".length());
    localeName = localeName.substring(shortBundleName.length());
    //
    if (localeName.length() == 0) {
        return LocaleInfo.DEFAULT;
    } else {
        String localeDescription = "'" + localeName + "' for file '" + file + "'.";
        // should start with '_'
        if (!localeName.startsWith("_")) {
            throw new IllegalArgumentException("'_' expected, but " + localeDescription);
        }
        localeName = localeName.substring(1);
        // create
        return LocaleInfo.create(localeName, localeDescription);
    }
}

From source file:org.eclipse.wb.internal.core.nls.bundle.pure.direct.DirectSource.java

/**
 * Return "possible" sources that exist in given package.
 * /*from  w w w. ja  v  a  2 s .  c o  m*/
 * "Possible" source is source that exists in current package, but is not used in current unit. We
 * show "possible" sources only if there are no "real" sources.
 */
public static List<AbstractSource> getPossibleSources(JavaInfo root, IPackageFragment pkg) throws Exception {
    List<AbstractSource> sources = Lists.newArrayList();
    //
    Object[] nonJavaResources = pkg.getNonJavaResources();
    for (int i = 0; i < nonJavaResources.length; i++) {
        Object o = nonJavaResources[i];
        if (o instanceof IFile) {
            IFile file = (IFile) o;
            String fileName = file.getName();
            // we need .properties files
            if (!fileName.endsWith(".properties")) {
                continue;
            }
            // we need only main (default) bundles
            if (fileName.indexOf('_') != -1) {
                continue;
            }
            // check first line for required comment 
            InputStream is = file.getContents(true);
            String firstLine = IOUtils2.readFirstLine(is);
            if (firstLine == null || !firstLine.startsWith("#" + BUNDLE_COMMENT)) {
                continue;
            }
            // OK, this is probably correct source
            try {
                String bundleName = pkg.getElementName() + "."
                        + StringUtils.substring(fileName, 0, -".properties".length());
                AbstractSource source = new DirectSource(root, bundleName);
                sources.add(source);
            } catch (Throwable e) {
                DesignerPlugin.log(e);
            }
        }
    }
    //
    return sources;
}

From source file:org.eclipse.wb.internal.core.nls.bundle.pure.field.FieldSource.java

/**
 * Return "possible" sources that exist in given package.
 * //w ww  .j  av a  2 s.c  o  m
 * "Possible" source is source that exists in current package, but is not used in current unit. We
 * show "possible" sources only if there are no "real" sources.
 */
public static List<AbstractSource> getPossibleSources(JavaInfo root, IPackageFragment pkg) throws Exception {
    List<AbstractSource> sources = Lists.newArrayList();
    //
    Object[] nonJavaResources = pkg.getNonJavaResources();
    for (Object o : nonJavaResources) {
        if (o instanceof IFile) {
            IFile file = (IFile) o;
            String fileName = file.getName();
            // we need .properties files
            if (!fileName.endsWith(".properties")) {
                continue;
            }
            // we need only main (default) bundles
            if (fileName.indexOf('_') != -1) {
                continue;
            }
            // check first line for required comment
            String fieldName;
            {
                InputStream is = file.getContents(true);
                String firstLine = IOUtils2.readFirstLine(is);
                if (firstLine == null || !firstLine.startsWith("#" + BUNDLE_COMMENT)) {
                    continue;
                }
                fieldName = firstLine.substring(1 + BUNDLE_COMMENT.length());
            }
            // OK, this is probably correct source
            try {
                String bundleName = pkg.getElementName() + "."
                        + StringUtils.substring(fileName, 0, -".properties".length());
                AbstractSource source = new FieldSource(root, bundleName, fieldName);
                sources.add(source);
            } catch (Throwable e) {
                DesignerPlugin.log(e);
            }
        }
    }
    //
    return sources;
}

From source file:org.eclipse.wb.internal.css.semantics.LengthValue.java

/**
 * Assigns value as string, should be separated if possible on value and unit, or use full string
 * as value without unit./*from  www . jav a 2 s .  c om*/
 */
@Override
public void set(String s) {
    // try to find unit
    if (s != null) {
        for (int I = 0; I < UNIT_NAMES.length; I++) {
            String unit = UNIT_NAMES[I];
            if (s.endsWith(unit)) {
                // check that value is correct number
                String value = StringUtils.substring(s, 0, -unit.length());
                try {
                    VALUE_DECIMAL_FORMAT.parse(value);
                } catch (Throwable e) {
                    continue;
                }
                // OK, we have correct value and unit
                m_value = value;
                m_unit = unit;
                notifyListeners();
                return;
            }
        }
    }
    // no, we can not separate given string on value and unit, so use string itself as value
    m_value = s;
    m_unit = "px";
    notifyListeners();
}