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

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

Introduction

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

Prototype

public static boolean endsWith(String str, String suffix) 

Source Link

Document

Check if a String ends with a specified suffix.

Usage

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.composite.MSSQLLoginComposite.java

@Override
public boolean makeUserDBDao(boolean isTest) {
    if (!isValidateInput(isTest))
        return false;

    String dbUrl = "";
    String strHost = StringUtils.trimToEmpty(textHost.getText());
    String strPort = StringUtils.trimToEmpty(textPort.getText());
    String strDB = StringUtils.trimToEmpty(textDatabase.getText());

    if (StringUtils.contains(strHost, "\\")) {

        String strIp = StringUtils.substringBefore(strHost, "\\");
        String strInstance = StringUtils.substringAfter(strHost, "\\");

        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance="
                + strInstance;/* w ww  .j  ava  2s.com*/
    } else if (StringUtils.contains(strHost, "/")) {

        String strIp = StringUtils.substringBefore(strHost, "/");
        String strInstance = StringUtils.substringAfter(strHost, "/");

        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strIp, strPort, strDB) + ";instance="
                + strInstance;

    } else {
        dbUrl = String.format(getSelectDB().getDB_URL_INFO(), strHost, strPort, strDB);
    }
    if (!"".equals(textJDBCOptions.getText())) {
        if (StringUtils.endsWith(dbUrl, ";")) {
            dbUrl += textJDBCOptions.getText();
        } else {
            dbUrl += ";" + textJDBCOptions.getText();
        }
    }

    if (logger.isDebugEnabled())
        logger.debug("[db url]" + dbUrl);

    userDB = new UserDBDAO();
    userDB.setDbms_type(getSelectDB().getDBToString());
    userDB.setUrl(dbUrl);
    userDB.setUrl_user_parameter(textJDBCOptions.getText());
    userDB.setDb(StringUtils.trimToEmpty(textDatabase.getText()));
    userDB.setGroup_name(StringUtils.trimToEmpty(preDBInfo.getComboGroup().getText()));
    userDB.setDisplay_name(StringUtils.trimToEmpty(preDBInfo.getTextDisplayName().getText()));

    String dbOpType = PublicTadpoleDefine.DBOperationType
            .getNameToType(preDBInfo.getComboOperationType().getText()).name();
    userDB.setOperation_type(dbOpType);
    if (dbOpType.equals(PublicTadpoleDefine.DBOperationType.PRODUCTION.name())
            || dbOpType.equals(PublicTadpoleDefine.DBOperationType.BACKUP.name())) {
        userDB.setIs_lock(PublicTadpoleDefine.YES_NO.YES.name());
    }

    userDB.setHost(StringUtils.trimToEmpty(textHost.getText()));
    userDB.setPort(StringUtils.trimToEmpty(textPort.getText()));
    userDB.setUsers(StringUtils.trimToEmpty(textUser.getText()));
    userDB.setPasswd(StringUtils.trimToEmpty(textPassword.getText()));

    // ? ?? ? .
    userDB.setRole_id(PublicTadpoleDefine.USER_ROLE_TYPE.ADMIN.toString());

    // others connection  .
    setOtherConnectionInfo();

    return true;
}

From source file:com.adobe.acs.tools.test_page_generator.impl.TestPageGeneratorServlet.java

private Object eval(final ScriptEngine scriptEngine, final Object value) {

    if (scriptEngine == null) {
        log.warn("ScriptEngine is null; cannot evaluate");
        return value;
    } else if (value instanceof String[]) {
        final List<String> scripts = new ArrayList<String>();
        final String[] values = (String[]) value;

        for (final String val : values) {
            scripts.add(String.valueOf(this.eval(scriptEngine, val)));
        }/*  w  w  w.j a  v a  2s . c o  m*/

        return scripts.toArray(new String[scripts.size()]);
    } else if (!(value instanceof String)) {
        return value;
    }

    final String stringValue = StringUtils.stripToEmpty((String) value);

    String script;
    if (StringUtils.startsWith(stringValue, "{{") && StringUtils.endsWith(stringValue, "}}")) {

        script = StringUtils.removeStart(stringValue, "{{");
        script = StringUtils.removeEnd(script, "}}");
        script = StringUtils.stripToEmpty(script);

        try {
            return scriptEngine.eval(script);
        } catch (ScriptException e) {
            log.error("Could not evaluation the test page property ecma [ {} ]", script);
        }
    }

    return value;
}

From source file:com.adobe.acs.tools.csv_asset_importer.impl.CsvAssetImporterServlet.java

/**
 * Gets an existing Asset to update or creates a new Asset.
 *
 * @param resourceResolver the resource resolver
 * @param params           the CSV Asset Importer params
 * @param columns          the Columns of the CSV
 * @param row              a row in the CSV
 * @return the Asset//from   w  w  w.j av a2s .  co  m
 * @throws FileNotFoundException
 * @throws RepositoryException
 * @throws CsvAssetImportException
 */
private Asset getOrCreateAsset(final ResourceResolver resourceResolver, final Parameters params,
        final Map<String, Column> columns, final String[] row)
        throws FileNotFoundException, RepositoryException, CsvAssetImportException {
    final AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);

    String uniqueId = null;
    if (StringUtils.isNotBlank(params.getUniqueProperty())) {
        uniqueId = row[columns.get(params.getUniqueProperty()).getIndex()];
    }

    String srcPath = null;
    // SrcPath is optional; If blank then process as an update properties strategy
    if (StringUtils.isNotBlank(params.getFileLocation())
            && !StringUtils.equals("/dev/null", params.getFileLocation())
            && StringUtils.isNotBlank(params.getRelSrcPathProperty())
            && StringUtils.isNotBlank(row[columns.get(params.getRelSrcPathProperty()).getIndex()])) {
        srcPath = params.getFileLocation() + "/" + row[columns.get(params.getRelSrcPathProperty()).getIndex()];

        log.debug("Row points to a file to import [ {} ]", srcPath);
    }

    final String mimeType = this.getMimeType(params, columns, row);
    final String absTargetPath = row[columns.get(params.getAbsTargetPathProperty()).getIndex()];

    if (StringUtils.endsWith(absTargetPath, "/")) {
        throw new CsvAssetImportException(
                "Absolute path [ " + absTargetPath + " ] is to a folder, not a file. Skipping");
    }

    // Resolve the absolute target path Asset
    Asset asset = null;

    // If a uniqueProperty is specified, ensure the value matches
    if (StringUtils.isNotBlank(params.getUniqueProperty()) && StringUtils.isNotBlank(uniqueId)) {
        // Check for existing Assets
        asset = this.findExistingAsset(resourceResolver,
                row[columns.get(params.getAbsTargetPathProperty()).getIndex()], params.getUniqueProperty(),
                uniqueId);
    } else {
        final Resource assetResource = resourceResolver.getResource(absTargetPath);
        if (assetResource != null) {
            asset = DamUtil.resolveToAsset(assetResource);
        }
    }

    FileInputStream fileInputStream = null;
    if (srcPath != null) {
        fileInputStream = new FileInputStream(srcPath);
    }
    // Determine if a Asset Creation or Update is needed

    if (asset == null) {
        if (fileInputStream == null) {
            log.warn("Existing asset could not be found for [ {} ] and no src file can found to import",
                    absTargetPath);
        } else {
            log.info("Existing asset could not be found for [ {} ], creating from [ {} ]", absTargetPath,
                    srcPath);
            asset = this.createAsset(assetManager, absTargetPath, fileInputStream, mimeType);
        }
    } else {
        // Asset exists
        if (Parameters.ImportStrategy.DELTA.equals(params.getImportStrategy())) {
            if (!StringUtils.equals(asset.getPath(), absTargetPath)) {

                // If is metadata only then moving the existing asset
                final Session session = resourceResolver.adaptTo(Session.class);

                if (!session.nodeExists(absTargetPath)) {
                    JcrUtils.getOrCreateByPath(StringUtils.substringBeforeLast(absTargetPath, "/"),
                            "sling:OrderedFolder", session);
                }

                session.move(asset.getPath(), absTargetPath);
                log.info("Moved asset from [ {} ~> {} ]", asset.getPath(), absTargetPath);
                asset = DamUtil.resolveToAsset(resourceResolver.getResource(absTargetPath));
            }

            // Partial Import, check if the original rendition should be updated
            if (params.isUpdateBinary()) {
                if (fileInputStream != null) {
                    asset = this.updateAssetOriginal(asset, fileInputStream, mimeType);
                } else {
                    log.info(
                            "Delta import strategy with 'Update Binary' specified but no src was specified. Skipping updating of binary for [ {} ].",
                            absTargetPath);
                }
            }
        } else if (Parameters.ImportStrategy.FULL.equals(params.getImportStrategy())) {
            // Remove existing asset so it can be recreated
            if (fileInputStream != null) {
                asset.adaptTo(Resource.class).adaptTo(Node.class).remove();
                log.info("Removed existing asset so it can be re-created");
                asset = this.createAsset(assetManager, absTargetPath, fileInputStream, mimeType);
            } else {
                log.info(
                        "Full import strategy specified but no src was specified. Skipping re-creation of binary for [ {} ].",
                        absTargetPath);
            }
        }
    }

    return asset;
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.DataGridLoader.java

@Nullable
protected Integer loadWidth(Element element, String propertyName) {
    String width = loadThemeString(element.attributeValue(propertyName));
    if (!StringUtils.isBlank(width)) {
        if (StringUtils.endsWith(width, "px")) {
            width = StringUtils.substring(width, 0, width.length() - 2);
        }/*from   w w w  . ja  v  a  2 s  .c  o  m*/
        try {
            // Only integer allowed in XML
            return Integer.parseInt(width);
        } catch (NumberFormatException e) {
            throw new GuiDevelopmentException("Property '" + propertyName + "' must contain only numeric value",
                    context.getCurrentFrameId(), propertyName, element.attributeValue("width"));
        }
    }
    return null;
}

From source file:com.adobe.acs.commons.replication.status.impl.JcrPackageReplicationStatusEventHandler.java

/**
 * Checks if any path in the array of paths looks like a Jcr Package path.
 *
 * Provides a very fast, String-based, in-memory check to weed out most false positives and avoid
 * resolving the path to a Jcr Package and ensure it is valid.
 *
 * @param paths the array of paths//from  ww w  .ja v a2s.co m
 * @return true if at least one path looks like a Jcr Package path
 */
private boolean containsJcrPackagePath(final String[] paths) {
    for (final String path : paths) {
        if (StringUtils.startsWith(path, "/etc/packages/") && StringUtils.endsWith(path, ".zip")) {
            // At least 1 entry looks like a package
            return true;
        }
    }

    // Nothing looks like a package...
    return false;
}

From source file:com.iyonger.apm.web.model.AgentManager.java

private Set<AgentIdentity> checkAgentAvailable(User user, Set<AgentIdentity> allFreeAgents,
        Set<AgentIdentity> useAgents) {
    Set<AgentIdentity> agentIdentities = new HashSet<AgentIdentity>();

    for (AgentIdentity each : allFreeAgents) {
        String region = ((AgentControllerIdentityImplementation) each).getRegion();
        if (StringUtils.endsWith(region, "owned_" + user.getUserId())
                || !StringUtils.contains(region, "owned_")) {
            if (useAgents.contains(each)) {
                agentIdentities.add(each);
            }/*from  w  w  w . ja  v a 2  s  . co m*/
        }
    }
    return agentIdentities;
}

From source file:com.iyonger.apm.web.model.AgentManager.java

/**
 * Select agent. This method return agent set which is belong to the given user first and then share agent set.
 *
 * @param user          user/*from   w w w.j a  v a2s.  c  om*/
 * @param allFreeAgents agents
 * @param agentCount    number of agent
 * @return selected agent.
 */
public Set<AgentIdentity> selectAgent(User user, Set<AgentIdentity> allFreeAgents, int agentCount) {
    Set<AgentIdentity> userAgent = new HashSet<AgentIdentity>();
    for (AgentIdentity each : allFreeAgents) {
        String region = ((AgentControllerIdentityImplementation) each).getRegion();
        if (StringUtils.endsWith(region, "owned_" + user.getUserId())) {
            userAgent.add(each);
            if (userAgent.size() == agentCount) {
                return userAgent;
            }
        }
    }

    for (AgentIdentity each : allFreeAgents) {
        String region = ((AgentControllerIdentityImplementation) each).getRegion();
        if (!StringUtils.contains(region, "owned_")) {
            userAgent.add(each);
            if (userAgent.size() == agentCount) {
                return userAgent;
            }
        }
    }
    return userAgent;
}

From source file:com.haulmont.cuba.gui.xml.layout.loaders.AbstractTableLoader.java

protected Table.Column loadColumn(Element element, Datasource ds) {
    String id = element.attributeValue("id");

    MetaPropertyPath metaPropertyPath = AppBeans.get(MetadataTools.NAME, MetadataTools.class)
            .resolveMetaPropertyPath(ds.getMetaClass(), id);

    Table.Column column = new Table.Column(metaPropertyPath != null ? metaPropertyPath : id);

    String editable = element.attributeValue("editable");
    if (StringUtils.isNotEmpty(editable)) {
        column.setEditable(Boolean.parseBoolean(editable));
    }/* w ww  . jav  a  2 s .c  o m*/

    String collapsed = element.attributeValue("collapsed");
    if (StringUtils.isNotEmpty(collapsed)) {
        column.setCollapsed(Boolean.parseBoolean(collapsed));
    }

    String groupAllowed = element.attributeValue("groupAllowed");
    if (StringUtils.isNotEmpty(groupAllowed)) {
        column.setGroupAllowed(Boolean.parseBoolean(groupAllowed));
    }

    String sortable = element.attributeValue("sortable");
    if (StringUtils.isNotEmpty(sortable)) {
        column.setSortable(Boolean.parseBoolean(sortable));
    }

    loadCaption(column, element);
    loadDescription(column, element);

    if (column.getCaption() == null) {
        String columnCaption;
        if (column.getId() instanceof MetaPropertyPath) {
            MetaPropertyPath mpp = (MetaPropertyPath) column.getId();
            MetaProperty metaProperty = mpp.getMetaProperty();
            String propertyName = metaProperty.getName();

            if (DynamicAttributesUtils.isDynamicAttribute(metaProperty)) {
                CategoryAttribute categoryAttribute = DynamicAttributesUtils.getCategoryAttribute(metaProperty);

                columnCaption = LocaleHelper.isLocalizedValueDefined(categoryAttribute.getLocaleNames())
                        ? categoryAttribute.getLocaleName()
                        : StringUtils.capitalize(categoryAttribute.getName());
            } else {
                MetaClass propertyMetaClass = metadataTools.getPropertyEnclosingMetaClass(mpp);
                columnCaption = messageTools.getPropertyCaption(propertyMetaClass, propertyName);
            }
        } else {
            Class<?> declaringClass = ds.getMetaClass().getJavaClass();
            String className = declaringClass.getName();
            int i = className.lastIndexOf('.');
            if (i > -1)
                className = className.substring(i + 1);
            columnCaption = messages.getMessage(declaringClass, className + "." + id);
        }
        column.setCaption(columnCaption);
    }

    column.setXmlDescriptor(element);
    if (metaPropertyPath != null)
        column.setType(metaPropertyPath.getRangeJavaClass());

    String width = loadThemeString(element.attributeValue("width"));
    if (!StringUtils.isBlank(width)) {
        if (StringUtils.endsWith(width, "px")) {
            width = StringUtils.substring(width, 0, width.length() - 2);
        }
        try {
            column.setWidth(Integer.parseInt(width));
        } catch (NumberFormatException e) {
            throw new GuiDevelopmentException("Property 'width' must contain only numeric value",
                    context.getCurrentFrameId(), "width", element.attributeValue("width"));
        }
    }
    String align = element.attributeValue("align");
    if (StringUtils.isNotBlank(align)) {
        column.setAlignment(Table.ColumnAlignment.valueOf(align));
    }

    column.setFormatter(loadFormatter(element));

    loadAggregation(column, element);
    loadCalculatable(column, element);
    loadMaxTextLength(column, element);

    return column;
}

From source file:eionet.web.action.VocabularyFoldersActionBean.java

/**
 * Validates changing site prefix./*  w  w  w  . ja  va 2 s  .c o  m*/
 *
 * @throws ServiceException
 *             if an error occurs
 */
@ValidationMethod(on = { "changeSitePrefix" })
public void validateChangeSitePrefix() throws ServiceException {
    if (StringUtils.isBlank(newSitePrefix)) {
        addGlobalValidationError("New Site Prefix is missing");
    } else if (!Util.isValidUri(newSitePrefix)) {
        addGlobalValidationError("New Site prefix is not a valid URI. \n The allowed schemes are: "
                + "http, https, ftp, mailto, tel and urn.");
    } else if (!StringUtils.endsWith(newSitePrefix, "/")) {
        newSitePrefix += "/";
    }

    if (StringUtils.isBlank(oldSitePrefix)) {
        addGlobalValidationError("Old Site Prefix is missing");
    } else if (!Util.isValidUri(oldSitePrefix)) {
        addGlobalValidationError("Old Site prefix is not a valid URI. \n The allowed schemes are: "
                + "http, https, ftp, mailto, tel and urn.");
    } else if (!StringUtils.endsWith(oldSitePrefix, "/")) {
        oldSitePrefix += "/";
    }

    if (StringUtils.equals(oldSitePrefix, newSitePrefix)) {
        addGlobalValidationError("Old and New Site Prefixes are the same.");
    }
}

From source file:com.hangum.tadpole.rdb.core.dialog.job.CreateJobDialog.java

private String getScript() {
    StringBuffer result = new StringBuffer();
    result.append(this.textScript.getText().trim());

    if (!StringUtils.endsWith(result.toString(), ";")) {
        result.append(";");
    }/*from   w  w  w .j av  a2 s  .c  o m*/

    return result.toString().replace("'", "''");
}