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:com.hangum.tadpole.rdb.erd.core.utils.TadpoleModelUtils.java

/**
 * logindb?   ?  .// w w w .j  av a 2s . com
 * 
 * @param monitor
 * @param userDB
 * @return
 */
public DB getDBAllTable(final IProgressMonitor monitor, final UserDBDAO userDB) throws Exception {

    DB db = factory.createDB();
    db.setDbType(userDB.getDbms_type());
    db.setId(userDB.getUsers());
    db.setUrl(userDB.getUrl());

    // ??.
    List<TableDAO> tables = getAllTables(userDB);
    //   ? ?.
    Map<String, Table> mapDBTables = new HashMap<String, Table>();

    // 
    int count = 0;
    Rectangle prevRectangle = null;

    int nextTableX = START_TABLE_WIDTH;
    int nextTableY = START_TABLE_HIGHT;

    for (int i = 0; i < tables.size(); i++) {
        monitor.subTask(String.format("Working %s/%s", i, tables.size()));

        final TableDAO tableDao = tables.get(i);
        Table tableModel = factory.createTable();
        tableModel.setDb(db);
        tableModel.setName(tableDao.getName());

        if (userDB.getDBDefine() == DBDefine.SQLite_DEFAULT) {
            tableModel.setComment("");
        } else {
            String tableComment = tableDao.getComment();
            if (tableComment == null)
                tableComment = "";
            tableComment = StringUtils.substring(tableComment, 0, 10);
            tableModel.setComment(tableComment);
        }

        mapDBTables.put(tableModel.getName(), tableModel);

        //   .
        if (prevRectangle == null) {
            prevRectangle = new Rectangle(START_TABLE_WIDTH, START_TABLE_HIGHT, END_TABLE_WIDTH,
                    END_TABLE_HIGHT);
        } else {
            // ??  ?. 
            prevRectangle = new Rectangle(nextTableX, nextTableY, END_TABLE_WIDTH, END_TABLE_HIGHT);
        }
        //            logger.debug("###########################################################################################################################");
        //            logger.debug("###########################################################################################################################");
        //            logger.debug("###########################################################################################################################");
        //            logger.debug(prevRectangle.toString());
        //            logger.debug("###########################################################################################################################");
        //            logger.debug("###########################################################################################################################");
        tableModel.setConstraints(prevRectangle);

        // column add
        List<TableColumnDAO> columnList = TDBDataHandler.getColumns(userDB, tableDao);
        for (TableColumnDAO columnDAO : columnList) {

            Column column = factory.createColumn();
            column.setDefault(columnDAO.getDefault());
            column.setExtra(columnDAO.getExtra());
            column.setField(columnDAO.getField());
            column.setNull(columnDAO.getNull());
            column.setKey(columnDAO.getKey());
            column.setType(columnDAO.getType());

            String strComment = columnDAO.getComment();
            if (strComment == null)
                strComment = "";
            strComment = StringUtils.substring(strComment, 0, 10);
            column.setComment(strComment);

            column.setTable(tableModel);
            tableModel.getColumns().add(column);
        }

        // ? hehght .
        // row count * ? * ? ?
        int columnsHeight = tableModel.getColumns().size() * 18 + 30;

        //   
        count++;

        // ? ? ?  ?. 
        if (count == ROW_COUNT) {
            count = 0;

            nextTableX = prevRectangle.getTopRight().x + GAP_WIDTH;
            nextTableY = START_TABLE_WIDTH;
        } else {
            nextTableY = prevRectangle.getBottomLeft().y + columnsHeight + GAP_HIGHT;
        }

    } // end table list

    //  .
    RelationUtil.calRelation(userDB, mapDBTables, db);

    return db;
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.visutils.UtilityFunctions.java

/**
 * Currently the approach for slugifying filenames is naive. In future if there is need, 
 * we can write more sophisticated method.
 * @param textToBeSlugified/*from ww  w .j av a 2s . c  o  m*/
 * @return
 */
public static String slugify(String textToBeSlugified) {
    String textBlockSeparator = "-";
    return StringUtils.removeEnd(StringUtils.substring(
            textToBeSlugified.toLowerCase().trim().replaceAll("[^a-zA-Z0-9-]+", textBlockSeparator), 0,
            VisConstants.MAX_NAME_TEXT_LENGTH), textBlockSeparator);
}

From source file:com.cognifide.cq.cqsm.foundation.actions.deny.Deny.java

private ActionResult process(final Context context, boolean simulate) {
    ActionResult actionResult = new ActionResult();
    try {//from   ww w . j  av a  2s.  com
        Authorizable authorizable = context.getCurrentAuthorizable();
        actionResult.setAuthorizable(authorizable.getID());
        context.getSession().getNode(path);
        final PermissionActionHelper permissionActionHelper = new PermissionActionHelper(
                context.getValueFactory(), path, glob, permissions);
        LOGGER.info(String.format("Denying permissions %s for authorizable with id = %s for path = %s %s",
                permissions.toString(), context.getCurrentAuthorizable().getID(), path,
                StringUtils.isEmpty(glob) ? "" : ("glob = " + glob)));
        if (simulate) {
            permissionActionHelper.checkPermissions(context.getAccessControlManager());
        } else {
            permissionActionHelper.applyPermissions(context.getAccessControlManager(),
                    authorizable.getPrincipal(), false);
        }
        actionResult.logMessage("Added deny privilege for " + authorizable.getID() + " on " + path);
        if (permissions.contains("MODIFY")) {
            List<String> globModifyPermission = new ArrayList<>();
            globModifyPermission.add("MODIFY_PAGE");
            String preparedGlob = "";
            if (!StringUtils.isBlank(glob)) {
                preparedGlob = glob;
                if (StringUtils.endsWith(glob, "*")) {
                    preparedGlob = StringUtils.substring(glob, 0, StringUtils.lastIndexOf(glob, '*'));
                }
            }
            new Deny(path, preparedGlob + "*/jcr:content*", ignoreUnexistingPaths, globModifyPermission)
                    .process(context, simulate);
        }
    } catch (final PathNotFoundException e) {
        if (ignoreUnexistingPaths) {
            actionResult.logWarning("Path " + path + " not found");
        } else {
            actionResult.logError("Path " + path + " not found");
        }
    } catch (final RepositoryException | PermissionException | ActionExecutionException e) {
        actionResult.logError(MessagingUtils.createMessage(e));
    }
    return actionResult;
}

From source file:mitm.common.properties.PropertiesResolver.java

/**
 * Resolves special property value types (for example a property that starts with file:// is converted the 
 * the actual file content).//w  w  w.  j  a v  a 2s . c  o m
 * 
 * Currently only file: binding is supported
 */
public void resolve(Properties properties) throws PropertiesResolverException {
    Enumeration<?> propertyNamesEnum = properties.propertyNames();

    while (propertyNamesEnum.hasMoreElements()) {
        Object obj = propertyNamesEnum.nextElement();

        if (!(obj instanceof String)) {
            continue;
        }

        String key = (String) obj;

        String value = properties.getProperty(key);

        if (value == null) {
            continue;
        }

        int index = value.indexOf(SCHEMA_SEPARATOR);

        if (index == -1) {
            continue;
        }

        String binding = StringUtils.substring(value, 0, index).trim();
        String toResolve = StringUtils.substring(value, index + SCHEMA_SEPARATOR.length());

        if (FILE_SCHEMA.equalsIgnoreCase(binding)) {
            File file = new File(baseDir, toResolve);

            try {
                String resolved = FileUtils.readFileToString(file, CharacterEncoding.UTF_8);

                properties.setProperty(key, resolved);
            } catch (IOException e) {
                String canonicalPath = toResolve;

                try {
                    canonicalPath = file.getCanonicalPath();
                } catch (IOException ioe) {
                    logger.error("Error getting canonical path.", ioe);
                }

                throw new PropertiesResolverException("Could not resolve file " + canonicalPath, e);
            }
        } else if (LITERAL_SCHEMA.equalsIgnoreCase(binding)) {
            /*
             * with literal binding the value after the binding should be taken
             * literal.
             */
            properties.setProperty(key, toResolve);
        } else {
            throw new PropertiesResolverException("Unknown binding " + binding);
        }
    }
}

From source file:nc.noumea.mairie.organigramme.viewmodel.CreateEntiteViewModel.java

/**
 * Cre une entit en fonction de ce qui a t indiqu dans la popup de
 * cration. L'ajoute  l'arbre DTO reprsent par l'{@link EntiteDto}
 * "entiteDtoRoot" et l'ajoute aussi  l'arborescence {@link Ul}/{@link Li}
 * qui est utilise pour rafrachir l'arbre en retour de cette mthode
 *///from w ww .java 2 s.  c o m
@Command
@NotifyChange("entity")
public void save() {

    ProfilAgentDto profilAgentDto = authentificationService.getCurrentUser();

    // #16902 : Ajouter le champ labelCourt limit  60 caractres dans les
    // proprits d'une entit
    if (StringUtils.isNotBlank(this.entity.getLabel())) {
        this.entity.setLabelCourt(StringUtils.substring(this.entity.getLabel(), 0, 60));
    }

    if (!profilAgentDto.isEdition() || showErrorPopup(this.entity)) {
        return;
    }

    EntiteDto entiteDtoParent = this.entity.getEntiteParent();
    EntiteDto newEntiteDto = createAndInitNewEntiteDto(entiteDtoParent, profilAgentDto.getIdAgent());

    // On fait appel au WS ADS de cration d'une entit
    ReturnMessageDto returnMessageDto = adsWSConsumer.saveOrUpdateEntite(newEntiteDto);
    if (!returnMessageService.gererReturnMessage(returnMessageDto, false)) {
        return;
    }

    // On recharge le dto directement depuis ADS pour tre sur d'avoir la
    // version bien  jour
    newEntiteDto = adsWSConsumer.getEntite(returnMessageDto.getId());

    // On ajoute l'entit  l'arbre dj existant pour que le ct client
    // puisse reconstruire l'arbre complet
    final Map<String, Object> mapEntite = new HashMap<String, Object>();
    mapEntite.put("entiteDtoParent", entiteDtoParent);
    mapEntite.put("newEntiteDto", newEntiteDto);
    mapEntite.put("ouvreOnglet", true);
    BindUtils.postGlobalCommand(null, null, "refreshToutOngletEntite", new HashMap<String, Object>());
    BindUtils.postGlobalCommand(null, null, "refreshArbreSuiteAjout", mapEntite);

    getPopup().detach();
}

From source file:de.interactive_instruments.ShapeChange.Target.SQL.OracleStrategy.java

@Override
public String normalizeName(String name) {
    String upperCaseName = name.toUpperCase(Locale.ENGLISH);
    String normalizedName = StringUtils.substring(upperCaseName, 0, 30);
    if (upperCaseName.length() != normalizedName.length()) {
        result.addWarning(this, 1, upperCaseName, normalizedName);
    }//from w  ww  .ja  va2s. co m
    return normalizedName;
}

From source file:com.hangum.tadpole.engine.sql.util.executer.ProcedureExecuterManager.java

/**
 * Is executed procedure?//  ww  w.jav  a2s .c om
 * 
 * @param procedureDAO
 * @param useDB
 * @return
 */
public boolean isExecuted(ProcedureFunctionDAO procedureDAO, UserDBDAO selectUseDB) {
    if (!isSupport()) {
        MessageDialog.openWarning(null, Messages.get().Warning, Messages.get().ProcedureExecuterManager_0);
        return false;
    }
    if (!procedureDAO.isValid()) {
        MessageDialog.openWarning(null, Messages.get().Warning, Messages.get().ProcedureExecuterManager_4);
        return false;
    }

    if (userDB.getDBDefine() == DBDefine.MYSQL_DEFAULT) {
        double dbVersion = 0.0;
        try {
            SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
            DBInfoDAO dbInfo = (DBInfoDAO) sqlClient.queryForObject("findDBInfo"); //$NON-NLS-1$
            dbVersion = Double.parseDouble(StringUtils.substring(dbInfo.getProductversion(), 0, 3));

            if (dbVersion < 5.5) {
                MessageDialog.openInformation(null, Messages.get().Information,
                        Messages.get().ProcedureExecuterManager_6);
                return false;
            }
        } catch (Exception e) {
            logger.error("find DB info", e); //$NON-NLS-1$

            return false;
        }

    }

    try {
        ProcedureExecutor procedureExecutor = getExecuter();
        procedureExecutor.getInParameters();
    } catch (Exception e) {
        MessageDialog.openError(null, Messages.get().Error, e.getMessage());
        return false;
    }

    return true;
}

From source file:com.hangum.tadpole.mongodb.erd.core.part.TableEditPart.java

/**
 * create column figure/*  www .j a  v  a  2 s  . c o  m*/
 * 
 * @param tableFigure
 * @param model
 */
private void addColumnFigure(TableFigure tableFigure, Column model) {
    ColumnFigure labelKey = new ColumnFigure(COLUMN_TYPE.KEY);
    labelKey.setText(StringUtils.substring(model.getKey(), 0, 1));

    ColumnFigure labelName = new ColumnFigure(COLUMN_TYPE.NAME);
    labelName.setText(model.getField());

    ColumnFigure labelType = new ColumnFigure(COLUMN_TYPE.TYPE);
    labelType.setText(model.getType());

    tableFigure.add(labelKey);
    tableFigure.add(labelName);
    tableFigure.add(labelType);
}

From source file:com.adobe.acs.commons.contentfinder.querybuilder.impl.ContentFinderHitBuilder.java

/**
 * Derives and adds Asset related information to the map representing the hit.
 *
 * @param hit//from   w  w w  .  ja  v a 2  s  .  c om
 * @param map
 * @return
 * @throws javax.jcr.RepositoryException
 */
private static Map<String, Object> addAssetData(final Asset asset, final Hit hit, Map<String, Object> map)
        throws RepositoryException {

    String title = asset.getName();

    if (StringUtils.isNotBlank(asset.getMetadataValue(DamConstants.DC_TITLE))) {
        title = asset.getMetadataValue(DamConstants.DC_TITLE);
    }

    // Excerpt
    String excerpt = hit.getExcerpt();
    if (StringUtils.isBlank(hit.getExcerpt())) {
        excerpt = StringUtils.stripToEmpty(asset.getMetadataValue(DamConstants.DC_DESCRIPTION));
        if (excerpt.length() > MAX_EXCERPT_LENGTH) {
            excerpt = StringUtils.substring(excerpt, 0, (MAX_EXCERPT_LENGTH - ELLIPSE_LENGTH)) + "...";
        }
    }

    map.put(CF_PATH, asset.getPath());
    map.put(CF_NAME, asset.getName());
    map.put(CF_TITLE, title);
    map.put(CF_EXCERPT, excerpt);
    map.put(CF_MIMETYPE, asset.getMimeType());
    map.put(CF_SIZE, getSize(asset));
    map.put(CF_CACHE_KILLER, getCacheKiller(asset));
    map.put(CF_TYPE, "Asset");
    map.put(CF_LAST_MODIFIED, getLastModified(asset));

    return map;
}

From source file:hydrograph.ui.expression.editor.datastructure.MethodDetails.java

private String createFormattedJavaDoc(IMethod iMethod) throws JavaModelException {
    String source = iMethod.getSource();
    if (iMethod.getJavadocRange() != null) {
        javaDoc = StringUtils.substring(source, 0, iMethod.getJavadocRange().getLength());
        javaDoc = StringUtils.replaceEachRepeatedly(javaDoc, new String[] { "/*", "*/", "*" },
                new String[] { Constants.EMPTY_STRING, Constants.EMPTY_STRING, Constants.EMPTY_STRING });
    }/*  w w w  . j a  va2 s . c om*/
    return javaDoc;
}