Example usage for org.apache.commons.lang3 StringUtils startsWith

List of usage examples for org.apache.commons.lang3 StringUtils startsWith

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils startsWith.

Prototype

public static boolean startsWith(final CharSequence str, final CharSequence prefix) 

Source Link

Document

Check if a CharSequence starts with a specified prefix.

null s are handled without exceptions.

Usage

From source file:info.financialecology.finance.utilities.datastruct.VersatileDataTable.java

/**
 * Prints all rows containing values.//from   www.  j a  v a  2s  . c o  m
 * @return the header
 */
public String printValues() {
    String ts = "";
    String tsLast = "";
    List<String> rowKeys = getRowKeys();
    List<String> columnKeys = getColumnKeys();

    for (String rowKey : rowKeys) {
        if (StringUtils.startsWith(rowKey, "#")) {
            tsLast += "  " + StringUtils.rightPad(rowKey, 8) + " | "; // TODO leftmost column width should be a parameter
            for (String columnKey : columnKeys)
                tsLast += " " + String.format(" " + internalParams.getNumberFormat(),
                        getValue(rowKey, columnKey).doubleValue());
            tsLast += "\n";
        } else {
            ts += "  " + StringUtils.rightPad(rowKey, 8) + " | ";
            for (String columnKey : columnKeys)
                ts += " " + String.format(" " + internalParams.getNumberFormat(),
                        getValue(rowKey, columnKey).doubleValue());
            ts += "\n";
        }
    }

    //        for (int i = 0; i < getRowCount(); i++) {
    //            ts += "  " + StringUtils.rightPad((String) getRowKey(i), 4) + " | ";
    //            for (int j = 0; j < getColumnCount(); j++)
    //                ts += " " + String.format(" " + internalParams.getNumberFormat(), getValue(i, j).doubleValue());
    //            ts += "\n";
    //        }

    if (!tsLast.equalsIgnoreCase(""))
        ts += printRowSeparator(".") + "\n" + tsLast;

    return ts + " ";
}

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

@Override
public void initializeDatabaseSettings() {
    try {/*w  w w. ja v  a2 s.co  m*/
        databaseConfig = new DatabaseSettings(ConfigurationConverter.getProperties(mirthConfig));

        // dir.base is not included in mirth.properties, so set it manually
        databaseConfig.setDirBase(getBaseDir());

        String password = databaseConfig.getDatabasePassword();

        if (StringUtils.isNotEmpty(password)) {
            ConfigurationController configurationController = ControllerFactory.getFactory()
                    .createConfigurationController();
            EncryptionSettings encryptionSettings = configurationController.getEncryptionSettings();
            Encryptor encryptor = configurationController.getEncryptor();

            if (encryptionSettings.getEncryptProperties()) {
                if (StringUtils.startsWith(password, EncryptionSettings.ENCRYPTION_PREFIX)) {
                    String encryptedPassword = StringUtils.removeStart(password,
                            EncryptionSettings.ENCRYPTION_PREFIX);
                    String decryptedPassword = encryptor.decrypt(encryptedPassword);
                    databaseConfig.setDatabasePassword(decryptedPassword);
                } else if (StringUtils.isNotBlank(password)) {
                    // encrypt the password and write it back to the file
                    String encryptedPassword = EncryptionSettings.ENCRYPTION_PREFIX
                            + encryptor.encrypt(password);
                    mirthConfig.setProperty("database.password", encryptedPassword);

                    /*
                     * Save using a FileOutputStream so that the file will be saved to the
                     * proper location, even if running from the IDE.
                     */
                    File confDir = new File(ControllerFactory.getFactory().createConfigurationController()
                            .getConfigurationDir());
                    OutputStream os = new FileOutputStream(new File(confDir, "mirth.properties"));

                    try {
                        mirthConfig.save(os);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.sonicle.webtop.core.app.ServiceManager.java

private Map<String, ServiceManifest> discoverServices() throws IOException {
    ClassLoader cl = LangUtils.findClassLoader(getClass());

    // Scans classpath looking for service descriptor files
    Enumeration<URL> enumResources = null;
    try {/*from w  w w  .jav a  2s . c  om*/
        enumResources = cl.getResources(SERVICES_DESCRIPTOR_RESOURCE);
    } catch (IOException ex) {
        throw ex;
    }

    // Parses and splits descriptor files into a single manifest file for each service
    HashMap<String, ServiceManifest> manifests = new HashMap();
    while (enumResources.hasMoreElements()) {
        URL url = enumResources.nextElement();
        try {
            Collection<ServiceManifest> parsed = parseDescriptor(url);
            for (ServiceManifest manifest : parsed) {
                String key = manifest.getId();
                if (!manifests.containsKey(key)) {
                    manifests.put(manifest.getId(), manifest);

                } else if (manifest.getVersion().compareTo(manifests.get(key).getVersion()) > 0) {
                    logger.warn("[{}] Version {} replaced by {}", manifest.getId(),
                            manifests.get(key).getVersion(), manifest.getVersion());
                    manifests.put(manifest.getId(), manifest);
                }
            }
        } catch (ConfigurationException ex) {
            logger.error("Error while reading descriptor [{}]", url.toString(), ex);
        }
    }

    List<String> orderdKeys = manifests.keySet().stream().sorted((s1, s2) -> {
        if (StringUtils.startsWith(s1, CoreManifest.ID)) {
            return -1;
        } else {
            return s1.compareTo(s2);
        }
    }).collect(Collectors.toList());

    LinkedHashMap<String, ServiceManifest> map = new LinkedHashMap<>(orderdKeys.size());
    for (String key : orderdKeys) {
        map.put(key, manifests.get(key));
    }
    return map;
}

From source file:com.nridge.core.base.field.data.DataTable.java

/**
 * Returns one or more field rows that match the search criteria of the
 * parameters provided.  Each row of the table will be examined to determine
 * if a cell identified by name evaluates true when the operator and value
 * are applied to it.//ww  w  . ja  v  a 2  s  .  c o  m
 * <p>
 * <b>Note:</b> This method supports text based logical operators only.
 * You should use other <code>findValue()</code> methods for different
 * data types.
 * </p>
 *
 * @param aName Column name.
 * @param anOperator Logical operator.
 * @param aValue Comparison value.
 *
 * @return Array list of matching field rows or <i>null</i> if none evaluate true.
 */
public ArrayList<FieldRow> findValue(String aName, Field.Operator anOperator, String aValue) {
    String valueString;
    FieldRow fieldRow;
    Matcher regexMatcher = null;
    Pattern regexPattern = null;
    ArrayList<FieldRow> matchingRows = new ArrayList<FieldRow>();

    int rowCount = rowCount();
    int colOffset = offsetByName(aName);
    if ((aValue != null) && (colOffset != -1) && (rowCount > 0)) {
        for (int row = 0; row < rowCount; row++) {
            fieldRow = getRow(row);
            valueString = fieldRow.getValue(colOffset);

            switch (anOperator) {
            case NOT_EMPTY:
                if (StringUtils.isNotEmpty(valueString))
                    matchingRows.add(fieldRow);
                break;
            case EQUAL:
                if (StringUtils.equals(valueString, aValue))
                    matchingRows.add(fieldRow);
                break;
            case NOT_EQUAL:
                if (!StringUtils.equals(valueString, aValue))
                    matchingRows.add(fieldRow);
                break;
            case CONTAINS:
                if (StringUtils.contains(valueString, aValue))
                    matchingRows.add(fieldRow);
                break;
            case STARTS_WITH:
                if (StringUtils.startsWith(valueString, aValue))
                    matchingRows.add(fieldRow);
                break;
            case ENDS_WITH:
                if (StringUtils.endsWith(valueString, aValue))
                    matchingRows.add(fieldRow);
                break;
            case EMPTY:
                if (StringUtils.isEmpty(valueString))
                    matchingRows.add(fieldRow);
                break;
            case REGEX: // http://www.regular-expressions.info/java.html
                if (regexPattern == null)
                    regexPattern = Pattern.compile(aValue);
                if (regexMatcher == null)
                    regexMatcher = regexPattern.matcher(valueString);
                else
                    regexMatcher.reset(valueString);
                if (regexMatcher.find())
                    matchingRows.add(fieldRow);
                break;
            }
        }
    }

    return matchingRows;
}

From source file:ch.cyberduck.ui.cocoa.controller.MainController.java

/**
 * Extract the URL from the Apple event and handle it here.
 *///from   w w w.  jav a2s .c  om
@Action
public void handleGetURLEvent_withReplyEvent(NSAppleEventDescriptor event, NSAppleEventDescriptor reply) {
    log.debug("Received URL from Apple Event:" + event);
    final NSAppleEventDescriptor param = event.paramDescriptorForKeyword(keyAEResult);
    if (null == param) {
        log.error("No URL parameter");
        return;
    }
    final String url = param.stringValue();
    if (StringUtils.isEmpty(url)) {
        log.error("URL parameter is empty");
        return;
    }
    if (StringUtils.startsWith(url, "x-cyberduck-action:")) {
        final String action = StringUtils.removeStart(url, "x-cyberduck-action:");
        switch (action) {
        case "update":
            updater.check(false);
            break;
        default:
            if (StringUtils.startsWith(action, "oauth?token=")) {
                final OAuth2TokenListenerRegistry oauth = OAuth2TokenListenerRegistry.get();
                final String token = StringUtils.removeStart(action, "oauth?token=");
                oauth.notify(token);
                break;
            }
        }
    } else {
        final Host h = HostParser.parse(url);
        if (Path.Type.file == detector.detect(h.getDefaultPath())) {
            final Path file = new Path(h.getDefaultPath(), EnumSet.of(Path.Type.file));
            TransferControllerFactory.get()
                    .start(new DownloadTransfer(h, file,
                            LocalFactory.get(preferences.getProperty("queue.download.folder"), file.getName())),
                            new TransferOptions());
        } else {
            for (BrowserController browser : MainController.getBrowsers()) {
                if (browser.isMounted()) {
                    if (new HostUrlProvider().get(browser.getSession().getHost())
                            .equals(new HostUrlProvider().get(h))) {
                        // Handle browser window already connected to the same host. #4215
                        browser.window().makeKeyAndOrderFront(null);
                        return;
                    }
                }
            }
            final BrowserController browser = newDocument(false);
            browser.mount(h);
        }
    }
}

From source file:com.mirth.connect.model.util.ImportConverter3_0_0.java

private static void migrateJmsReceiverProperties(DonkeyElement properties) throws MigrationException {
    logger.debug("Migrating JmsReceiverProperties");
    Properties oldProperties = readPropertiesElement(properties);
    properties.setAttribute("class", "com.mirth.connect.connectors.jms.JmsReceiverProperties");
    properties.removeChildren();/* w  w  w .  ja v a2 s  .co m*/

    buildResponseConnectorProperties(properties.addChildElement("responseConnectorProperties"));

    properties.addChildElement("useJndi").setTextContent(readBooleanProperty(oldProperties, "useJndi", false));
    properties.addChildElement("jndiProviderUrl")
            .setTextContent(oldProperties.getProperty("jndiProviderUrl", ""));
    properties.addChildElement("jndiInitialContextFactory")
            .setTextContent(oldProperties.getProperty("jndiInitialFactory", ""));
    properties.addChildElement("jndiConnectionFactoryName")
            .setTextContent(oldProperties.getProperty("connectionFactoryJndiName", ""));
    properties.addChildElement("connectionFactoryClass")
            .setTextContent(oldProperties.getProperty("connectionFactoryClass", ""));
    properties.addChildElement("username").setTextContent(oldProperties.getProperty("username", ""));
    properties.addChildElement("password").setTextContent(oldProperties.getProperty("password", ""));

    String destinationName = oldProperties.getProperty("host", "");
    boolean topic = readBooleanValue(oldProperties, "durable", false);
    boolean durableTopic = topic;

    if (StringUtils.startsWith(destinationName, "topic://")
            || StringUtils.startsWith(destinationName, "//topic:")) {
        destinationName = destinationName.substring(8);
        topic = true;
    } else if (StringUtils.startsWith(destinationName, "//queue:")
            || StringUtils.startsWith(destinationName, "queue://")) {
        destinationName = destinationName.substring(8);
        topic = false;
        durableTopic = false;
    }

    properties.addChildElement("destinationName").setTextContent(destinationName);
    properties.addChildElement("reconnectIntervalMillis").setTextContent("10000");
    properties.addChildElement("clientId").setTextContent(oldProperties.getProperty("clientId", ""));
    properties.addChildElement("topic").setTextContent(Boolean.toString(topic));
    properties.addChildElement("durableTopic").setTextContent(Boolean.toString(durableTopic));
    properties.addChildElement("selector").setTextContent(oldProperties.getProperty("selector", ""));

    DonkeyElement connectionProperties = properties.addChildElement("connectionProperties");
    connectionProperties.setAttribute("class", "linked-hash-map");

    try {
        Properties oldConnectionProperties = readPropertiesElement(
                new DonkeyElement(oldProperties.getProperty("connectionFactoryProperties")));

        for (Object key : oldConnectionProperties.keySet()) {
            String value = oldConnectionProperties.getProperty((String) key);

            DonkeyElement entry = connectionProperties.addChildElement("entry");
            entry.addChildElement("string", (String) key);
            entry.addChildElement("string", value);
        }
    } catch (Exception e) {
        throw new MigrationException(e);
    }
}

From source file:com.mirth.connect.model.util.ImportConverter3_0_0.java

private static void migrateJmsDispatcherProperties(DonkeyElement properties) throws MigrationException {
    logger.debug("Migrating JmsDispatcherProperties");
    Properties oldProperties = readPropertiesElement(properties);
    properties.setAttribute("class", "com.mirth.connect.connectors.jms.JmsDispatcherProperties");
    properties.removeChildren();/*from   w w  w.ja v  a 2  s.  c  o m*/

    buildQueueConnectorProperties(properties.addChildElement("queueConnectorProperties"));

    properties.addChildElement("useJndi").setTextContent(readBooleanProperty(oldProperties, "useJndi", false));
    properties.addChildElement("jndiProviderUrl")
            .setTextContent(convertReferences(oldProperties.getProperty("jndiProviderUrl", "")));
    properties.addChildElement("jndiInitialContextFactory")
            .setTextContent(oldProperties.getProperty("jndiInitialFactory", ""));
    properties.addChildElement("jndiConnectionFactoryName")
            .setTextContent(oldProperties.getProperty("connectionFactoryJndiName", ""));
    properties.addChildElement("connectionFactoryClass")
            .setTextContent(oldProperties.getProperty("connectionFactoryClass", ""));
    properties.addChildElement("username")
            .setTextContent(convertReferences(oldProperties.getProperty("username", "")));
    properties.addChildElement("password")
            .setTextContent(convertReferences(oldProperties.getProperty("password", "")));

    String destinationName = convertReferences(oldProperties.getProperty("host", ""));
    boolean topic = false;

    if (StringUtils.startsWith(destinationName, "topic://")
            || StringUtils.startsWith(destinationName, "//topic:")) {
        destinationName = destinationName.substring(8);
        topic = true;
    } else if (StringUtils.startsWith(destinationName, "//queue:")
            || StringUtils.startsWith(destinationName, "queue://")) {
        destinationName = destinationName.substring(8);
        topic = false;
    }

    properties.addChildElement("destinationName").setTextContent(destinationName);
    properties.addChildElement("clientId").setTextContent("");
    properties.addChildElement("topic").setTextContent(Boolean.toString(topic));
    properties.addChildElement("template")
            .setTextContent(convertReferences(oldProperties.getProperty("template", "${message.encodedData}")));

    try {
        Properties oldConnectionProperties = readPropertiesElement(
                new DonkeyElement(oldProperties.getProperty("connectionFactoryProperties")));

        DonkeyElement connectionProperties = properties.addChildElement("connectionProperties");
        connectionProperties.setAttribute("class", "linked-hash-map");

        for (Object key : oldConnectionProperties.keySet()) {
            String value = convertReferences(oldConnectionProperties.getProperty((String) key));

            DonkeyElement entry = connectionProperties.addChildElement("entry");
            entry.addChildElement("string", (String) key);
            entry.addChildElement("string", value);
        }
    } catch (DonkeyElementException e) {
        throw new MigrationException(e);
    }
}

From source file:com.sonicle.webtop.core.CoreManager.java

/**
 * Expands a virtualRecipient address into a real set of recipients.
 * @param virtualRecipientAddress//ww  w . j a va  2 s.c om
 * @return
 * @throws WTException 
 */
public List<Recipient> expandVirtualProviderRecipient(String virtualRecipientAddress) throws WTException {
    ArrayList<Recipient> items = new ArrayList<>();
    VirtualAddress va = new VirtualAddress(virtualRecipientAddress);

    for (String soId : listRecipientProviderSourceIds()) {
        final RecipientsProviderBase provider = getProfileRecipientsProviders().get(soId);
        if (provider == null)
            continue;
        if (!StringUtils.isBlank(va.getDomain()) && !StringUtils.startsWith(soId, va.getDomain())) {
            continue;
        }

        List<Recipient> recipients = null;
        try {
            recipients = provider.expandToRecipients(va.getLocal());
        } catch (Throwable t) {
            logger.error("Error calling RecipientProvider [{}]", t, soId);
        }
        if (recipients == null)
            continue;
        for (Recipient recipient : recipients) {
            recipient.setSource(soId);
            items.add(recipient);
        }
    }
    return items;
}

From source file:com.mirth.connect.client.ui.Frame.java

public String readFileToString(File file) {
    try {// w  w w.j a  v a  2s  .  c o m
        String content = FileUtils.readFileToString(file, UIConstants.CHARSET);

        if (StringUtils.startsWith(content, EncryptionSettings.ENCRYPTION_PREFIX)) {
            return mirthClient.getEncryptor()
                    .decrypt(StringUtils.removeStart(content, EncryptionSettings.ENCRYPTION_PREFIX));
        } else {
            return content;
        }
    } catch (IOException e) {
        alertError(this, "Unable to read file.");
    }

    return null;
}

From source file:org.apache.commons.lang3.StringUtils.java

/**
 * <p>Check if a CharSequence starts with any of an array of specified strings.</p>
 *
 * <pre>//w  ww .  j av  a  2  s .c  o m
 * StringUtils.startsWithAny(null, null)      = false
 * StringUtils.startsWithAny(null, new String[] {"abc"})  = false
 * StringUtils.startsWithAny("abcxyz", null)     = false
 * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
 * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
 * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
 * </pre>
 *
 * @param string  the CharSequence to check, may be null
 * @param searchStrings the CharSequences to find, may be null or empty
 * @return {@code true} if the CharSequence starts with any of the the prefixes, case insensitive, or
 *  both {@code null}
 * @since 2.5
 * @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...)
 */
public static boolean startsWithAny(CharSequence string, CharSequence... searchStrings) {
    if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) {
        return false;
    }
    for (CharSequence searchString : searchStrings) {
        if (StringUtils.startsWith(string, searchString)) {
            return true;
        }
    }
    return false;
}