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

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

Introduction

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

Prototype

public static String capitalize(final String str) 

Source Link

Document

Capitalizes a String changing the first letter to title case as per Character#toTitleCase(char) .

Usage

From source file:ch.cyberduck.core.preferences.Preferences.java

/**
 * @param locale ISO Language identifier
 * @return Human readable language name in the target language
 *//* ww  w  .  j  ava 2s  .  co  m*/
public String getDisplayName(final String locale) {
    java.util.Locale l;
    if (StringUtils.contains(locale, "_")) {
        l = new java.util.Locale(locale.split("_")[0], locale.split("_")[1]);
    } else {
        l = new java.util.Locale(locale);
    }
    return StringUtils.capitalize(l.getDisplayName(l));
}

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

/**
 * Save all of the current channel information in the editor to the actual channel
 */// w w w . ja  va  2 s  . c o  m
public boolean saveChanges() {
    if (!parent.checkChannelName(summaryNameField.getText(), currentChannel.getId())) {
        return false;
    }

    if (metadataPruningOnRadio.isSelected() && metadataPruningDaysTextField.getText().equals("")) {
        parent.alertWarning(parent,
                "If metadata pruning is enabled, the age of metadata to prune cannot be blank.");
        return false;
    }

    if (contentPruningDaysRadio.isSelected() && contentPruningDaysTextField.getText().equals("")) {
        parent.alertWarning(parent,
                "If content pruning is enabled, the age of content to prune cannot be blank.");
        return false;
    }

    if (metadataPruningOnRadio.isSelected() && contentPruningDaysRadio.isSelected()) {
        Integer metadataPruningDays = Integer.parseInt(metadataPruningDaysTextField.getText());
        Integer contentPruningDays = Integer.parseInt(contentPruningDaysTextField.getText());

        if (contentPruningDays > metadataPruningDays) {
            parent.alertWarning(parent,
                    "The age of content to prune cannot be greater than the age of metadata to prune.");
            return false;
        }
    }

    // Store the current metadata column data in a map with the column name as the key and the type as the value.
    Map<String, MetaDataColumnType> currentColumns = new HashMap<String, MetaDataColumnType>();
    for (MetaDataColumn column : currentChannel.getProperties().getMetaDataColumns()) {
        currentColumns.put(column.getName(), column.getType());
    }

    Set<String> columnNames = new HashSet<String>();
    for (int i = 0; i < metaDataTable.getRowCount(); i++) {
        DefaultTableModel model = (DefaultTableModel) metaDataTable.getModel();

        // Do not allow metadata column names to be empty
        String columnName = (String) model.getValueAt(i, model.findColumn(METADATA_NAME_COLUMN_NAME));
        if (StringUtils.isEmpty(columnName)) {
            parent.alertWarning(parent,
                    "Empty column name detected in custom metadata table. Column names cannot be empty.");
            return false;
        } else {
            // Do not allow duplicate column names
            if (columnNames.contains(columnName)) {
                parent.alertWarning(parent,
                        "Duplicate column name detected in custom metadata table. Column names must be unique.");
                return false;
            }

            if (columnName.equalsIgnoreCase("MESSAGE_ID") || columnName.equalsIgnoreCase("METADATA_ID")) {
                parent.alertWarning(parent, columnName
                        + " is a reserved keyword and cannot be used as a column name in the custom metadata table.");
                return false;
            }

            // Add the column name to a set so it can be checked for duplicates
            columnNames.add(columnName);
        }

        MetaDataColumnType columnType = (MetaDataColumnType) model.getValueAt(i,
                model.findColumn(METADATA_TYPE_COLUMN_NAME));

        // Remove columns from the map only if they have NOT been modified in a way such that their data will be deleted on deploy
        if (currentColumns.containsKey(columnName) && currentColumns.get(columnName).equals(columnType)) {
            currentColumns.remove(columnName);
        }
    }

    // Notify the user if an existing column was modified in a way such that it will be deleted on deploy
    if (!currentColumns.isEmpty()) {
        if (!parent.alertOption(parent,
                "Renaming, deleting, or changing the type of existing custom metadata columns\nwill delete all existing data "
                        + "for that column. Are you sure you want to do this?")) {
            return false;
        }
    }

    boolean enabled = summaryEnabledCheckbox.isSelected();

    saveSourcePanel();

    if (parent.currentContentPage == transformerPane) {
        transformerPane.accept(false);
        transformerPane.modified = false; // TODO: Check this. Fix to prevent double save on confirmLeave
    }

    if (parent.currentContentPage == filterPane) {
        filterPane.accept(false);
        filterPane.modified = false; // TODO: Check this. Fix to prevent double save on confirmLeave
    }

    saveDestinationPanel();

    MessageStorageMode messageStorageMode = MessageStorageMode.fromInt(messageStorageSlider.getValue());
    String errorString = getQueueErrorString(messageStorageMode);

    if (errorString != null) {
        parent.alertWarning(parent, StringUtils.capitalize(errorString)
                + " queueing must be disabled first before using the selected message storage mode.");
        return false;
    }

    currentChannel.setName(summaryNameField.getText());
    currentChannel.setDescription(summaryDescriptionText.getText());

    updateScripts();
    setLastModified();

    currentChannel.getProperties().setClearGlobalChannelMap(clearGlobalChannelMapCheckBox.isSelected());
    currentChannel.getProperties().setEncryptData(encryptMessagesCheckBox.isSelected());
    currentChannel.getProperties().setInitialState((DeployedState) initialState.getSelectedItem());
    currentChannel.getProperties().setStoreAttachments(attachmentStoreCheckBox.isSelected());

    String validationMessage = checkAllForms(currentChannel);
    if (validationMessage != null) {
        enabled = false;

        // If there is an error on one of the forms, then run the
        // validation on the current form to display any errors.
        if (channelView.getSelectedComponent() == destination) {
            // If the destination is enabled...
            if (currentChannel.getDestinationConnectors().get(destinationTable.getSelectedModelIndex())
                    .isEnabled()) {
                destinationConnectorPanel.checkProperties(destinationConnectorPanel.getProperties(), true);
            }
        } else if (channelView.getSelectedComponent() == source) {
            sourceConnectorPanel.checkProperties(sourceConnectorPanel.getProperties(), true);
        }

        summaryEnabledCheckbox.setSelected(false);

        parent.alertCustomError(this.parent, validationMessage, CustomErrorDialog.ERROR_SAVING_CHANNEL);
    }

    // Set the channel to enabled or disabled after it has been validated
    currentChannel.setEnabled(enabled);

    saveChannelTags();
    saveMetaDataColumns();
    saveMessageStorage(messageStorageMode);
    saveMessagePruning();

    // Update resource names
    parent.updateResourceNames(currentChannel);

    for (ChannelTabPlugin channelTabPlugin : LoadedExtensions.getInstance().getChannelTabPlugins().values()) {
        channelTabPlugin.getChannelTabPanel().save(currentChannel);
    }

    boolean updated = false;

    try {
        // Will throw exception if the connection died or there was an exception
        // saving the channel, skipping the rest of this code.
        updated = parent.updateChannel(currentChannel,
                parent.channelPanel.getCachedChannelStatuses().containsKey(currentChannel.getId()));

        try {
            currentChannel = (Channel) SerializationUtils.clone(
                    parent.channelPanel.getCachedChannelStatuses().get(currentChannel.getId()).getChannel());

            if (parent.currentContentPage == transformerPane) {
                if (channelView.getSelectedIndex() == SOURCE_TAB_INDEX) {
                    transformerPane.reload(currentChannel.getSourceConnector());
                } else if (channelView.getSelectedIndex() == DESTINATIONS_TAB_INDEX) {
                    int destination = destinationTable.getSelectedModelIndex();
                    transformerPane.reload(currentChannel.getDestinationConnectors().get(destination));
                }
            }
            if (parent.currentContentPage == filterPane) {
                if (channelView.getSelectedIndex() == SOURCE_TAB_INDEX) {
                    filterPane.reload(currentChannel.getSourceConnector(),
                            currentChannel.getSourceConnector().getFilter());
                } else if (channelView.getSelectedIndex() == DESTINATIONS_TAB_INDEX) {
                    Connector destination = currentChannel.getDestinationConnectors()
                            .get(destinationTable.getSelectedModelIndex());
                    filterPane.reload(destination, destination.getFilter());
                }
            }
            updateRevision();
            updateLastModified();
        } catch (SerializationException e) {
            parent.alertThrowable(this.parent, e);
        }
    } catch (ClientException e) {
        parent.alertThrowable(this.parent, e);
    }

    sourceConnectorPanel.updateQueueWarning(currentChannel.getProperties().getMessageStorageMode());
    destinationConnectorPanel.updateQueueWarning(currentChannel.getProperties().getMessageStorageMode());

    if (updated && saveGroupId != null) {
        parent.channelPanel.addChannelToGroup(currentChannel.getId(), saveGroupId);
        saveGroupId = null;
    }

    return updated;
}

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

/**
 * Prints all time series of this collection in a formatted table.
 * <p>/*from   w ww  .j  ava 2s . c  om*/
 * Uses the print methods from {@link VersatileTimeSeries}, but
 * adds the index map functionality (see {@link #newIndexMap(
 * String, String, String...)}) and the run and experiment 
 * indices. Rather than just printing one time series, it 
 * prints all time series in a formatted table form, with
 * ticks, times, or dates and an optional row separator.
 * <p>
 * <b>Note:</b> Currently this method uses a single label 
 * (<code>baseName</code>) as the variable name and hence cannot
 * be used to print out a collection that contains time series
 * of different variables. For such a collection, you first need
 * to obtain subsets of time series belonging to the same variable
 * using {@link #getSubset(String)} before printing. You can chain
 * the operations.
 * <p>
 * <b>Example:</b> Operations that return a collection can be chained. 
 * If <code>tscResults</code> is for instance a collection of time 
 * series that include prices, you can print these out by invoking
 * <code>tscResults.getSubset("price").printDecoratedSeries("PRICE", 
 * FIRST_COLUMN_WIDTH)</code> 
 * @param baseName the label used to indicate the variable name
 * @param width the width of the columns that hold the time series values
 * @param ticks true, if ticks, times, or dates are to be shown in a header
 * separated by a row separator. 
 * @return the string containing the formatted time series table
 */
public String printDecoratedSeries(String baseName, int width, Boolean ticks) {
    List<VersatileTimeSeries> atsList = getSeries();
    String atsString = "";
    Boolean isHeaderPrinted = false;

    for (VersatileTimeSeries ats : atsList) { // loops through all time series in this collection
        String label = "";
        String key = (String) ats.getKey();
        //            ArrayList<String> indices = ats.extractVariableIndices(key);
        //            String varName = ats.extractVariableName(key);
        //            HashMap<String, String> map = indexMap.get(varName);
        String exp = ats.extractExperimentIndex(key);
        String run = ats.extractRunIndex(key);

        if (ticks && !isHeaderPrinted) { // print the header only if requested and only once for this table
            atsString = ats.printDecoratedTicks(width) + "\n";
            atsString += ats.printDecoratedRowSeparator(width) + "--------------------\n";
            isHeaderPrinted = true;
        }

        // Generate the variable name and dimension indices (which might be mapped)
        label += StringUtils.rightPad(baseName, width);
        label += mapIndices(ats) + " | ";

        // Generate the run and experiment labels
        if ((exp != null) && (run != null))
            label += "{";

        if (exp != null) {
            label += StringUtils.capitalize(exp);
            if (run != null)
                label += ", ";
        }

        if (run != null)
            label += StringUtils.capitalize(run);

        if ((exp != null) && (run != null))
            label += "}";

        atsString += label + " " + ats.printValues() + "   | " + label + "  " + "\n"; // assemble the output line 
    }

    return atsString; // output string; typically consists of several lines 
}

From source file:forge.game.card.Card.java

private static String getTextForKwCantBeBlockedByType(final String keyword) {
    boolean negative = true;
    final List<String> subs = Lists.newArrayList(TextUtil.split(keyword.split(" ", 2)[1], ','));
    final List<List<String>> subsAnd = Lists.newArrayList();
    final List<String> orClauses = new ArrayList<>();
    for (final String expession : subs) {
        final List<String> parts = Lists.newArrayList(expession.split("[.+]"));
        for (int p = 0; p < parts.size(); p++) {
            final String part = parts.get(p);
            if (part.equalsIgnoreCase("creature")) {
                parts.remove(p--);/*from   ww  w . j a  v a2s.  c o  m*/
                continue;
            }
            // based on suppossition that each expression has at least 1 predicate except 'creature'
            negative &= part.contains("non") || part.contains("without");
        }
        subsAnd.add(parts);
    }

    final boolean allNegative = negative;
    final String byClause = allNegative ? "except by " : "by ";

    final Function<Pair<Boolean, String>, String> withToString = new Function<Pair<Boolean, String>, String>() {
        @Override
        public String apply(Pair<Boolean, String> inp) {
            boolean useNon = inp.getKey() == allNegative;
            return (useNon ? "*NO* " : "") + inp.getRight();
        }
    };

    for (final List<String> andOperands : subsAnd) {
        final List<Pair<Boolean, String>> prependedAdjectives = Lists.newArrayList();
        final List<Pair<Boolean, String>> postponedAdjectives = Lists.newArrayList();
        String creatures = null;

        for (String part : andOperands) {
            boolean positive = true;
            if (part.startsWith("non")) {
                part = part.substring(3);
                positive = false;
            }
            if (part.startsWith("with")) {
                positive = !part.startsWith("without");
                postponedAdjectives.add(Pair.of(positive, part.substring(positive ? 4 : 7)));
            } else if (part.startsWith("powerLEX")) {// Kraken of the Straits
                postponedAdjectives.add(Pair.of(true, "power less than the number of islands you control"));
            } else if (part.startsWith("power")) {
                int kwLength = 5;
                String opName = Expressions.operatorName(part.substring(kwLength, kwLength + 2));
                String operand = part.substring(kwLength + 2);
                postponedAdjectives.add(Pair.of(true, "power" + opName + operand));
            } else if (CardType.isACreatureType(part)) {
                if (creatures != null && CardType.isACreatureType(creatures)) { // e.g. Kor Castigator
                    creatures = StringUtils.capitalize(Lang.getPlural(part)) + creatures;
                } else {
                    creatures = StringUtils.capitalize(Lang.getPlural(part))
                            + (creatures == null ? "" : " or " + creatures);
                }
            } else {
                prependedAdjectives.add(Pair.of(positive, part.toLowerCase()));
            }
        }

        StringBuilder sbShort = new StringBuilder();
        if (allNegative) {
            boolean isFirst = true;
            for (Pair<Boolean, String> pre : prependedAdjectives) {
                if (isFirst)
                    isFirst = false;
                else
                    sbShort.append(" and/or ");

                boolean useNon = pre.getKey() == allNegative;
                if (useNon)
                    sbShort.append("non-");
                sbShort.append(pre.getValue()).append(" ").append(creatures == null ? "creatures" : creatures);
            }
            if (prependedAdjectives.isEmpty())
                sbShort.append(creatures == null ? "creatures" : creatures);

            if (!postponedAdjectives.isEmpty()) {
                if (!prependedAdjectives.isEmpty()) {
                    sbShort.append(" and/or creatures");
                }

                sbShort.append(" with ");
                sbShort.append(
                        Lang.joinHomogenous(postponedAdjectives, withToString, allNegative ? "or" : "and"));
            }

        } else {
            for (Pair<Boolean, String> pre : prependedAdjectives) {
                boolean useNon = pre.getKey() == allNegative;
                if (useNon)
                    sbShort.append("non-");
                sbShort.append(pre.getValue()).append(" ");
            }
            sbShort.append(creatures == null ? "creatures" : creatures);

            if (!postponedAdjectives.isEmpty()) {
                sbShort.append(" with ");
                sbShort.append(
                        Lang.joinHomogenous(postponedAdjectives, withToString, allNegative ? "or" : "and"));
            }

        }
        orClauses.add(sbShort.toString());
    }
    return byClause + StringUtils.join(orClauses, " or ") + ".";
}

From source file:forge.ai.ComputerUtil.java

public static Object vote(Player ai, List<Object> options, SpellAbility sa, Multimap<Object, Player> votes) {
    if (!sa.hasParam("AILogic")) {
        return Aggregates.random(options);
    } else {//from  ww w. j a v  a2 s  . c o  m
        String logic = sa.getParam("AILogic");
        switch (logic) {
        case "Torture":
            return "Torture";
        case "GraceOrCondemnation":
            return ai.getCreaturesInPlay().size() > ai.getOpponent().getCreaturesInPlay().size() ? "Grace"
                    : "Condemnation";
        case "CarnageOrHomage":
            CardCollection cardsInPlay = CardLists
                    .getNotType(sa.getHostCard().getGame().getCardsIn(ZoneType.Battlefield), "Land");
            CardCollection humanlist = CardLists.filterControlledBy(cardsInPlay, ai.getOpponents());
            CardCollection computerlist = CardLists.filterControlledBy(cardsInPlay, ai);
            return (ComputerUtilCard.evaluatePermanentList(computerlist) + 3) < ComputerUtilCard
                    .evaluatePermanentList(humanlist) ? "Carnage" : "Homage";
        case "Judgment":
            if (votes.isEmpty()) {
                CardCollection list = new CardCollection();
                for (Object o : options) {
                    if (o instanceof Card) {
                        list.add((Card) o);
                    }
                }
                return ComputerUtilCard.getBestAI(list);
            } else {
                return Iterables.getFirst(votes.keySet(), null);
            }
        case "Protection":
            if (votes.isEmpty()) {
                List<String> restrictedToColors = new ArrayList<String>();
                for (Object o : options) {
                    if (o instanceof String) {
                        restrictedToColors.add((String) o);
                    }
                }
                CardCollection lists = CardLists.filterControlledBy(ai.getGame().getCardsInGame(),
                        ai.getOpponents());
                return StringUtils
                        .capitalize(ComputerUtilCard.getMostProminentColor(lists, restrictedToColors));
            } else {
                return Iterables.getFirst(votes.keySet(), null);
            }
        default:
            return Iterables.getFirst(options, null);
        }
    }
}

From source file:com.mirth.connect.donkey.server.data.jdbc.JdbcDao.java

@Override
public void addMetaDataColumn(String channelId, MetaDataColumn metaDataColumn) {
    logger.debug(channelId + ": adding custom meta data column (" + metaDataColumn.getName() + ")");
    Statement statement = null;/*from   ww w .  jav a  2  s  .  com*/

    try {
        Map<String, Object> values = new HashMap<String, Object>();
        values.put("localChannelId", getLocalChannelId(channelId));
        values.put("columnName", metaDataColumn.getName());

        String queryName = "addMetaDataColumn"
                + StringUtils.capitalize(StringUtils.lowerCase(metaDataColumn.getType().toString()));

        statement = connection.createStatement();
        statement.executeUpdate(querySource.getQuery(queryName, values));

        if (querySource.queryExists(queryName + "Index")) {
            statement.executeUpdate(querySource.getQuery(queryName + "Index", values));
        }
    } catch (SQLException e) {
        throw new DonkeyDaoException("Failed to add meta-data column", e);
    } finally {
        close(statement);
    }
}

From source file:forge.game.card.Card.java

/**
 * Replace all instances of one color word in this card's text by another.
 * @param originalWord the original color word.
 * @param newWord the new color word./*  w  ww. ja  v a 2s. c o m*/
 * @throws RuntimeException if either of the strings is not a valid Magic
 *  color.
 */
public final void addChangedTextColorWord(final String originalWord, final String newWord,
        final Long timestamp) {
    if (MagicColor.fromName(newWord) == 0) {
        throw new RuntimeException("Not a color: " + newWord);
    }
    changedTextColors.add(timestamp, StringUtils.capitalize(originalWord), StringUtils.capitalize(newWord));
    updateKeywordsChangedText(timestamp);
    updateChangedText();
}

From source file:com.xpn.xwiki.XWiki.java

public URL getServerURL(String database, XWikiContext context) throws MalformedURLException {
    String serverurl = null;/*from ww  w  .j av a 2  s  .  co m*/

    // In virtual wiki path mode the server is the standard one
    if ("1".equals(Param("xwiki.virtual.usepath", "0"))) {
        return null;
    }

    if (database != null) {
        String db = context.getDatabase();
        try {
            context.setDatabase(getDatabase());
            XWikiDocument doc = getDocument("XWiki.XWikiServer" + StringUtils.capitalize(database), context);
            BaseObject serverobject = doc.getXObject(VIRTUAL_WIKI_DEFINITION_CLASS_REFERENCE);
            if (serverobject != null) {
                String server = serverobject.getStringValue("server");
                if (server != null) {
                    String protocol = context.getWiki().Param("xwiki.url.protocol", null);
                    if (protocol == null) {
                        int iSecure = serverobject.getIntValue("secure", -1);
                        // Check the request object if the "secure" property is undefined.
                        boolean secure = iSecure == 1 || (iSecure < 0 && context.getRequest().isSecure());
                        protocol = secure ? "https" : "http";
                    }
                    long port = context.getURL().getPort();
                    if (port == 80 || port == 443) {
                        port = -1;
                    }
                    if (port != -1) {
                        serverurl = protocol + "://" + server + ":" + port + "/";
                    } else {
                        serverurl = protocol + "://" + server + "/";
                    }
                }
            }
        } catch (Exception ex) {
        } finally {
            context.setDatabase(db);
        }
    }

    if (serverurl != null) {
        return new URL(serverurl);
    } else {
        return null;
    }
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

public static String getInternalPropertyName(String propname, XWikiContext context) {
    XWikiMessageTool msg = context.getMessageTool();
    String cpropname = StringUtils.capitalize(propname);

    return (msg == null) ? cpropname : msg.get(cpropname);
}

From source file:com.xpn.xwiki.doc.XWikiDocument.java

public String getInternalProperty(String propname) {
    String methodName = "get" + StringUtils.capitalize(propname);
    try {//w w w.  j  a  v  a 2  s  .  co  m
        Method method = getClass().getDeclaredMethod(methodName, (Class[]) null);
        return (String) method.invoke(this, (Object[]) null);
    } catch (Exception e) {
        return null;
    }
}