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.part.TableEditPart.java

private ColumnFigure[] createColumnFigure(Table tableModel, Column model) {
    ColumnFigure labelKey = new ColumnFigure(COLUMN_TYPE.KEY);
    ColumnFigure labelName = new ColumnFigure(COLUMN_TYPE.NAME);
    ColumnFigure labelComment = new ColumnFigure(COLUMN_TYPE.COMMENT);
    ColumnFigure labelType = new ColumnFigure(COLUMN_TYPE.TYPE);
    ColumnFigure labelNotNull = new ColumnFigure(COLUMN_TYPE.NULL);

    labelKey.setText(StringUtils.substring(model.getKey(), 0, 1));
    labelName.setText(model.getField());
    labelComment.setText(model.getComment());
    labelType.setText(model.getType());//from www .  j a  v a  2s  .co m
    labelNotNull.setText(StringUtils.substring(model.getNull(), 0, 1));

    return new ColumnFigure[] { labelKey, labelName, labelComment, labelType, labelNotNull };
}

From source file:com.processpuzzle.application.configuration.domain.ParametrizedConfigurationPropertyHandler.java

private void determineSelectorSegments() {
    int positionOfComparisonOperator = StringUtils.indexOfAny(parametrizedSelector, COMPARISON_OPERATORS);
    int positionOfConditionBegin = StringUtils.lastIndexOfAny(
            StringUtils.substring(parametrizedSelector, 0, positionOfComparisonOperator),
            ANY_SELECTOR_SEGMENT_DELIMITER);
    int positionOfConditionEnd = StringUtils.indexOfAny(
            StringUtils.substring(parametrizedSelector, positionOfComparisonOperator + 1),
            ANY_SELECTOR_SEGMENT_DELIMITER) + positionOfComparisonOperator + 1;

    conditionSegment = StringUtils.substring(parametrizedSelector, positionOfConditionBegin + 1,
            positionOfConditionEnd);//from   ww  w .j  a  v  a  2  s .co  m
    selectorBeforeCondition = StringUtils.substring(parametrizedSelector, 0, positionOfConditionBegin);
    selectorAfterCondition = StringUtils.substring(parametrizedSelector, positionOfConditionEnd + 1);
    conditionPropery = StringUtils.substring(conditionSegment, 0,
            positionOfComparisonOperator - positionOfConditionBegin - 1);
    if (conditionPropery.contains(PropertyContext.ATTRIBUTE_SIGNER))
        conditionPropery = PropertyContext.ATTRIBUTE_BEGIN + conditionPropery + PropertyContext.ATTRIBUTE_END;

    conditionValue = StringUtils.substring(conditionSegment,
            positionOfComparisonOperator - positionOfConditionBegin);
    if (conditionValue.startsWith("'") || conditionValue.startsWith("\""))
        ;
    conditionValue = StringUtils.substring(conditionValue, 1, conditionValue.length() - 1);
}

From source file:com.ning.killbill.zuora.zuora.ZuoraApi.java

public Either<ZuoraError, String> createPaymentProviderAccount(ZuoraConnection connection,
        com.ning.billing.account.api.Account inputAccount) {
    String defaultAccountName = StringUtils.substring("AccountName : " + inputAccount.getEmail(), 0, 50);

    String zuoraAccountId = null;
    Either<ZuoraError, Account> accountOrError = getByAccountName(connection, inputAccount.getExternalKey());

    if (accountOrError.isRight() && accountOrError.getRight().getId() != null) {
        zuoraAccountId = accountOrError.getRight().getId();
    } else {/*from w w w  .  j  av a 2s.c  o m*/

        logService.log(LogService.LOG_INFO,
                String.format("Creating zuora account %s", inputAccount.getExternalKey()));

        try {
            final com.zuora.api.object.ObjectFactory objectFactory = connection.getObjectFactory();
            final Account zuoraAccount = objectFactory.createAccount();

            zuoraAccount.setAccountNumber(inputAccount.getExternalKey());
            zuoraAccount.setAllowInvoiceEdit(false);
            zuoraAccount.setAutoPay(false);
            zuoraAccount.setBatch(DEFAULT_BATCH);
            zuoraAccount.setBillCycleDay(ZuoraDateUtils.dayOfMonth());
            zuoraAccount.setCurrency(inputAccount.getCurrency() == null ? String.valueOf(Currency.USD)
                    : String.valueOf(inputAccount.getCurrency()));
            zuoraAccount.setName(inputAccount.getName() == null ? defaultAccountName : inputAccount.getName());
            zuoraAccount.setPaymentTerm(DEFAULT_PAYMENT_TERMS);
            zuoraAccount.setStatus("Draft");
            zuoraAccount.setInvoiceDeliveryPrefsEmail(false);

            final Either<ZuoraError, String> accountIdOrError = connection.createWithId(zuoraAccount);

            if (accountIdOrError.isRight()) {
                zuoraAccountId = accountIdOrError.getRight();
            } else {
                return Either.left(new ZuoraError(accountIdOrError.getLeft().getType(),
                        accountIdOrError.getLeft().getMessage()));
            }
        } catch (Exception ex) {
            return Either.left(new ZuoraError(ZuoraError.ERROR_UNKNOWN, ex.getMessage()));
        }
    }

    updateAccountWithNewContact(connection, zuoraAccountId, inputAccount);

    return Either.right(zuoraAccountId);
}

From source file:com.edgenius.wiki.service.impl.SitemapServiceImpl.java

public boolean removePage(String pageUuid) throws IOException {
    boolean removed = false;
    String sitemapIndex = metadata.getSitemapIndex(pageUuid);
    if (sitemapIndex == null) {
        log.warn("Page {} does not exist in sitemap", pageUuid);
        return removed;
    }//from w w w .  j a v  a 2 s .c o m

    String sitemapZip = SITEMAP_NAME_PREFIX + sitemapIndex + ".xml.gz";
    File sizemapZipFile = new File(mapResourcesRoot.getFile(), sitemapZip);
    if (!sizemapZipFile.exists()) {
        throw new IOException("Remove pageUuid " + pageUuid + " from sitemap failed becuase sitemap not found");
    }

    PipedInputStream bis = new PipedInputStream();
    PipedOutputStream bos = new PipedOutputStream(bis);
    InputStream zipfile = new FileInputStream(sizemapZipFile);
    GZIPInputStream gzipstream = new GZIPInputStream(zipfile);
    byte[] bytes = new byte[1024 * 1000];
    int len = 0;
    while ((len = gzipstream.read(bytes)) > 0) {
        bos.write(bytes, 0, len);
    }

    IOUtils.closeQuietly(zipfile);
    IOUtils.closeQuietly(gzipstream);

    String pageUrl = metadata.getPageUrl(pageUuid);
    String body = IOUtils.toString(bis);
    int loc = body.indexOf("<loc>" + pageUrl + "</loc>");
    if (loc != -1) {
        int start = StringUtils.lastIndexOf(body, "<url>", loc);
        int end = StringUtils.indexOf(body, "</url>", loc);
        if (start != -1 && end != -1) {
            //remove this URL
            body = StringUtils.substring(body, start, end + 6);
            zipToFile(sizemapZipFile, body.getBytes());
            removed = true;
        }
    }

    metadata.removePageMap(pageUuid);

    return removed;
}

From source file:com.inktomi.wxmetar.MetarParser.java

static boolean parseVisibility(String token, String nextToken, final Metar metar) {
    boolean rval = Boolean.FALSE;

    Matcher numberMatcher = NUMBER.matcher(token);
    Matcher fractionMatcher = FRACTION.matcher(nextToken);

    // Check for that fraction
    if (!StringUtils.endsWith(token, "SM") && numberMatcher.matches() && StringUtils.endsWith(nextToken, "SM")
            && fractionMatcher.matches()) {

        // add them together
        float visMiles = Float.parseFloat(token); // this should be something like 1 or 2

        // Assemble the fraction
        float visFraction = Float.parseFloat(fractionMatcher.group(1))
                / Float.parseFloat(fractionMatcher.group(2));

        metar.visibility = visMiles + visFraction;

        rval = Boolean.TRUE;//from   w  w  w  . j  a  v a 2s  . c o  m
    }

    // Get the SM out of the way
    if (StringUtils.endsWith(token, "SM")) {
        metar.visibility = Float.parseFloat(StringUtils.substring(token, 0, token.length() - 2));
    }

    return rval;
}

From source file:com.abiquo.abiserver.pojo.infrastructure.PhysicalMachine.java

@Override
public PhysicalmachineHB toPojoHB() {
    PhysicalmachineHB physicalMachineHB = new PhysicalmachineHB();

    physicalMachineHB.setDataCenter(getDataCenter().toPojoHB());

    physicalMachineHB.setIdPhysicalMachine(getId());
    physicalMachineHB.setName(StringUtils.substring(getName(), 0, 255)); // a fully qualified
    // domain name (FQDN)
    // is 255 octets -
    // where any one label
    // can be 63 octets
    // long at most (RFC
    // 2181)//from www  . ja  v a2 s  . c  o  m
    physicalMachineHB.setDescription(getDescription());
    physicalMachineHB.setCpu(getCpu());
    physicalMachineHB.setCpuUsed(getCpuUsed());
    physicalMachineHB.setRam(getRam());
    physicalMachineHB.setRamUsed(getRamUsed());
    Rack rack = (Rack) getAssignedTo();
    physicalMachineHB.setRack(rack.toPojoHB());
    physicalMachineHB.setIdState(getIdState());
    physicalMachineHB.setVswitchName(vswitchName);
    physicalMachineHB.setInitiatorIQN(initiatorIQN);
    physicalMachineHB.setIpmiIp(ipmiIp);
    physicalMachineHB.setIpmiPort(ipmiPort);
    physicalMachineHB.setIpmiUser(ipmiUser);
    physicalMachineHB.setIpmiPassword(ipmiPassword);
    Set<DatastoreHB> datastoresHB = new HashSet<DatastoreHB>();
    if (datastores != null) {
        for (Datastore datastore : datastores) {
            datastoresHB.add(datastore.toPojoHB());
        }
    }
    physicalMachineHB.setDatastoresHB(datastoresHB);
    if (idEnterprise != null) {
        physicalMachineHB.setIdEnterprise(idEnterprise.intValue() != 0 ? idEnterprise : null);
    }

    if (hypervisor != null) {
        physicalMachineHB.setHypervisor(hypervisor.toPojoHB(physicalMachineHB));
    }

    return physicalMachineHB;
}

From source file:com.google.gdt.eclipse.designer.uibinder.model.widgets.GridInfo.java

/**
 * Decorates text of {@link Cell} with short excerpt of its content.
 *///from  w w  w .j a  v  a 2s.c  o  m
private void decorateCellText() {
    addBroadcastListener(new ObjectInfoPresentationDecorateText() {
        public void invoke(ObjectInfo object, String[] text) throws Exception {
            if (object instanceof HtmlCell && isParentOf(object)) {
                DocumentElement element = ((HtmlCell) object).getElement();
                int beginIndex = element.getOpenTagOffset() + element.getOpenTagLength();
                int endIndex = element.getCloseTagOffset();
                String contentText = getContext().getContent().substring(beginIndex, endIndex);
                contentText = contentText.trim();
                contentText = StringUtils.substring(contentText, 0, 15);
                text[0] += " " + contentText;
            }
        }
    });
}

From source file:com.openbravo.pos.admin.RolesViewTree.java

private void createTree() {

    //Create the jtree            
    root = new DefaultMutableTreeNode();
    uTree = new CheckboxTree(root);
    root.setUserObject("All Permissions");
    uTree.getCheckingModel().setCheckingMode(TreeCheckingModel.CheckingMode.PROPAGATE_PRESERVING_CHECK);
    uTree.clearSelection();//from  ww w  . j  ava 2s  .c  o m

    DefaultCheckboxTreeCellRenderer renderer = (DefaultCheckboxTreeCellRenderer) uTree.getCellRenderer();
    renderer.setLeafIcon(null);
    renderer.setClosedIcon(null);
    renderer.setOpenIcon(null);

    // set up listeners
    MouseListener ml = new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            int selRow = uTree.getRowForLocation(e.getX(), e.getY());
            TreePath selPath = uTree.getPathForLocation(e.getX(), e.getY());

            if (selPath != null) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
                // If using Right to left Language change the way the check tree works    
                if (!uTree.getComponentOrientation().isLeftToRight()) {
                    if (uTree.isPathChecked(new TreePath(node.getPath()))) {
                        uTree.removeCheckingPath(new TreePath(node.getPath()));
                    } else {
                        uTree.addCheckingPath(new TreePath(node.getPath()));
                    }
                }
                jPermissionDesc.setText(descriptionMap.get(node));
            }
        }
    };
    uTree.addMouseListener(ml);

    // when this listener is fired changes state to dirty 
    uTree.addTreeCheckingListener(new TreeCheckingListener() {
        public void valueChanged(TreeCheckingEvent e) {
            passedDirty.setDirty(true);
        }
    });

    try {
        // Get list of all the permisions in the database
        // and the list of sections
        dbPermissions = (List) m_dlAdmin.getAlldbPermissions();
        branches = m_dlAdmin.getSectionsList();
    } catch (BasicException ex) {
        Logger.getLogger(RolesViewTree.class.getName()).log(Level.SEVERE, null, ex);
    }

    // Create the main branches in the tree
    for (Object branch : branches) {
        section = ((StringUtils.substring(branch.toString(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(StringUtils.right(branch.toString(), branch.toString().length() - 2))
                : branch.toString();
        root.add(new DefaultMutableTreeNode(section));
    }

    classMap = new HashMap();
    descriptionMap = new HashMap();
    nodePaths = new HashMap();
    // Replace displayname, Section and Description 
    // from the database with the correct details from the permissions locale        
    for (DBPermissionsInfo Perm : dbPermissions) {
        Perm.setDisplayName(((StringUtils.substring(Perm.getDisplayName(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(
                        StringUtils.right(Perm.getDisplayName(), Perm.getDisplayName().length() - 2))
                : Perm.getDisplayName());
        Perm.setSection(((StringUtils.substring(Perm.getSection(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(StringUtils.right(Perm.getSection(), Perm.getSection().length() - 2))
                : Perm.getSection());
        Perm.setDescription(((StringUtils.substring(Perm.getDescription(), 0, 2)).equals("##"))
                ? AppLocal.getIntString(
                        StringUtils.right(Perm.getDescription(), Perm.getDescription().length() - 2))
                : Perm.getDescription());
    }
    //put the list into order by display name
    sort();
    // Create the leaf nodes & fill in hashmap's
    for (DBPermissionsInfo Perm : dbPermissions) {
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(Perm.getDisplayName(), false);
        if (searchNode(Perm.getSection(), root) != null) {
            searchNode(Perm.getSection(), root).add(newNode);
            classMap.put("[All Permissions, " + Perm.getSection() + ", " + newNode + "]", Perm.getClassName());
            descriptionMap.put(newNode, Perm.getDescription());
            nodePaths.put(Perm.getClassName(), newNode);
        }
    }
    root = sortTree(root);
    jScrollPane1.setViewportView(uTree);
    uTree.expandAll();
}

From source file:com.abssh.util.PropertyFilter.java

/**
 * @param filterName//  w w w . j av a2  s. co m
 *            ,???. eg. LIKES_NAME_OR_LOGIN_NAME
 * @param value
 *            .
 */
@SuppressWarnings("unchecked")
public PropertyFilter(final String filterName, final Object value, boolean flag) {

    String matchTypeStr = StringUtils.substringBefore(filterName, "_");
    String matchTypeCode = StringUtils.substring(matchTypeStr, 0, matchTypeStr.length() - 1);
    String propertyTypeCode = StringUtils.substring(matchTypeStr, matchTypeStr.length() - 1,
            matchTypeStr.length());
    try {
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyType = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    propertyNames = propertyNameStr.split(PropertyFilter.OR_SEPARATOR);

    Assert.isTrue(propertyNames.length > 0,
            "filter??" + filterName + ",??.");
    // entity property.
    if (value != null && (value.getClass().isArray() || Collection.class.isInstance(value))) {
        // IN ?
        Object[] vObjects = null;
        if (value.getClass().isArray()) {
            vObjects = (Object[]) value;
        } else if (Collection.class.isInstance(value)) {
            vObjects = ((Collection) value).toArray();
        } else {
            vObjects = value.toString().split(",");
        }
        this.propertyValue = new Object[vObjects.length];
        for (int i = 0; i < vObjects.length; i++) {
            propertyValue[i] = ReflectionUtils.convertValue(vObjects[i], propertyType);
        }
    } else {
        Object tObject = ReflectionUtils.convertValue(value, propertyType);
        if (tObject != null && matchType == MatchType.LE && propertyType.getName().equals("java.util.Date")) {
            // LED ??tObject2010-08-13 00:00:00
            // ?2010-08-13 23:59:59
            Date leDate = (Date) tObject;
            Calendar c = GregorianCalendar.getInstance();
            c.setTime(leDate);
            c.set(Calendar.HOUR_OF_DAY, 23);
            c.set(Calendar.MINUTE, 59);
            c.set(Calendar.SECOND, 59);
            tObject = c.getTime();
        } else if (tObject != null && matchType == MatchType.LEN
                && propertyType.getName().equals("java.util.Date")) {
        } else if (tObject != null && matchType == MatchType.LIKE) {
            tObject = ((String) tObject).replace("%", "\\%").replace("_", "\\_");
        }
        this.propertyValue = new Object[] { tObject };
    }
}

From source file:gnete.card.web.merch.MerchAction.java

@Override
public String execute() throws Exception {
    this.statusList = MerchState.getWithOutCheck();
    this.yesOrNoFlagList = YesOrNoFlag.getAll();

    Map<String, Object> params = new HashMap<String, Object>();

    boolean isUserOfLimitedTransQuery = isUserOfLimitedTransQuery();
    if (isUserOfLimitedTransQuery) {
        params.put("isUserOfLimitedTransQuery", isUserOfLimitedTransQuery);
        params.put("limitedExcludeManageBranchCodes",
                UserOfLimitedTransQueryUtil.getExcludeManageBranchCodes());
    }//from  www  . ja v  a2  s .c  o  m

    if (merchInfo != null) {
        String type = merchInfo.getMerchType();
        if (CommonHelper.isNotEmpty(type)) {
            type = StringUtils.substring(type, 0, StringUtils.indexOf(type, "|"));
        }
        params.put("merchId", merchInfo.getMerchId());
        params.put("merchName", MatchMode.ANYWHERE.toMatchString(merchInfo.getMerchName()));
        params.put("cardBranchCode", cardBranchCode);// ??-
        params.put("manageBranch", merchInfo.getManageBranch());
        params.put("status", merchInfo.getStatus());
        params.put("merchType", type);
        params.put("singleProduct", merchInfo.getSingleProduct());
        DatePair datePair = new DatePair(this.startDate, this.endDate);
        datePair.setTruncatedTimeDate(params);
    }
    if (CommonHelper.isNotEmpty(checkStartDate)) {
        Date otherSDate = DateUtil.formatDate(checkStartDate, "yyyyMMdd");
        params.put("checkStartDate", otherSDate);
    }
    if (CommonHelper.isNotEmpty(checkEndDate)) {
        Date otherEDate = DateUtil.formatDate(checkEndDate, "yyyyMMdd");
        params.put("checkEndDate", otherEDate);
    }

    showCardBranch = false; // ????

    if (isCenterOrCenterDeptRoleLogined()) {// ??
        showCardBranch = true;
        showCenter = true;
    } else if (isFenzhiRoleLogined()) {// 
        params.put("manageBranch", this.getLoginBranchCode());
        showCardBranch = true;
    } else if (isAgentRoleLogined()) {// ???
        params.put("agentBranchCode", getLoginBranchCode());

    } else if (isCardRoleLogined() || isCardDeptRoleLogined()) {// ??
        this.cardBranchCode = this.getLoginBranchCode();
        params.put("cardBranchCode", cardBranchCode);
        this.setCardBranchName(NameTag.getBranchName(cardBranchCode));
    } else if (isMerchantRoleLogined()) {// 
        params.put("merchId", this.getSessionUser().getMerchantNo());
    } else {
        throw new BizException("???");
    }
    this.page = this.merchInfoDAO.find(params, this.getPageNumber(), this.getPageSize());

    return LIST;
}