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

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

Introduction

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

Prototype

public static int length(String str) 

Source Link

Document

Gets a String's length or 0 if the String is null.

Usage

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

public Page savePage(Page pageValue, int requireNotified, boolean forceSave)
        throws PageException, VersionConflictException, DuplicatedPageException, PageSaveTiemoutExcetpion {
    Page page = null;//from  w ww. ja  va2 s  .c  o m
    String spaceUname = pageValue.getSpace().getUnixName();
    String newPageTitle = pageValue.getTitle();
    Integer newPageUid = pageValue.getUid();

    log.info("Page saving for " + pageValue.getTitle() + " on space " + spaceUname);
    Space space;
    //page already exist, need clone then save a new record in database
    String oldTitle = null;
    boolean needRefreshCache = false;

    if (newPageUid != null) {
        //The page will create  old version to new record but update same UID as current 
        //it would get same result by pageDAO.getCurrentByUuid() but a little bit faster in performance.
        page = pageDAO.get(newPageUid);
    } else if (!StringUtils.isBlank(pageValue.getPageUuid())) {
        //if user choose a item from My Draft in Dashboard, this won't bring in a newPageUid 
        //There are 3 scenarios for this case. 
        //1. it is a existed page draft.Following method returns current page,
        //2. non-existed page draft. Following method returns null.
        //3. non-existed page but page has a copy in trash bin! The below method return null as well, but the uuid is already invalid
        // as it is used by trashed page - so need further check - if it has trashed page, reset pageUUID
        page = pageDAO.getCurrentByUuid(pageValue.getPageUuid());

        if (page == null) {
            Page removedPage = pageDAO.getByUuid(pageValue.getPageUuid());
            if (removedPage != null && removedPage.isRemoved()) {
                //case 3, treat it as new page
                pageValue.setPageUuid(null);
            }
        }
    }

    if (!forceSave && !checkVersion(pageValue, page)) {
        throw new VersionConflictException(page.getVersion());
    }

    //!!!Title duplicated problem: user try to create a new page or rename a page but same title already exist in space 
    Page sameTitlePage = pageDAO.getCurrentPageByTitle(spaceUname, newPageTitle);
    if (page != null) {
        if (sameTitlePage != null) {
            if (!sameTitlePage.getPageUuid().equals(page.getPageUuid()))
                throw new DuplicatedPageException();
        }

        //keep old page :NOTE: this piece code has duplicate with fixLinksToTitle() method
        History oldPage = (History) page.cloneToHistory();
        //put this page to history page:create a new record with cloned value except Uid
        //         history page does not save link, tag and attachment info. 
        //         The key is save content change!
        oldPage.setAttachments(null);
        oldPage.setParent(null);
        historyDAO.saveOrUpdate(oldPage);

        if (!StringUtils.equalsIgnoreCase(oldPage.getTitle(), newPageTitle)) {
            // oldTitle is not null, so that update PageLink on below
            oldTitle = oldPage.getTitle();
            needRefreshCache = true;
            //remove old page with old title from cache first, new page should add after page saved
            removePageCache(spaceUname, page, false);
        }
        //update current page with new value
        space = page.getSpace();

        copyValueFromView(page, pageValue);
        //         page.setUnixName(WikiUtil.getPageUnixname(newPageTitle));
        WikiUtil.setTouchedInfo(userReadingService, page);
        page.setVersion(page.getVersion() + 1);
    } else {
        //for new create page: same title page must not exist
        if (sameTitlePage != null) {
            throw new DuplicatedPageException("Page has duplicated title:" + newPageTitle);
        }

        needRefreshCache = true;
        //a new page first time save:
        page = new Page();
        copyValueFromView(page, pageValue);

        space = spaceDAO.getByUname(spaceUname);
        page.setSpace(space);

        //??? CascadeType.PERSIST seems does not work well. I must explicit call save(), but in CascadeType.ALL, it is not necessary.
        pageProgressDAO.saveOrUpdate(page.getPageProgress());

        page.setVersion(1);
        //if there is draft existed before page first create, keep draft uuid as page uuid!!! 
        if (StringUtils.isBlank(pageValue.getPageUuid()))
            page.setPageUuid(WikiUtil.createPageUuid(spaceUname, spaceUname, spaceUname, repositoryService));
        else
            page.setPageUuid(pageValue.getPageUuid());
        //         page.setUnixName(WikiUtil.getPageUnixname(newPageTitle));
        WikiUtil.setTouchedInfo(userReadingService, page);

        if (pageValue.getParent() != null && !StringUtils.isBlank(pageValue.getParent().getPageUuid())) {
            Page parentPage = pageDAO.getCurrentByUuid(pageValue.getParent().getPageUuid());
            if (parentPage != null) {
                //maybe parent page is deleted as well.
                page.setParent(parentPage);
                page.setLevel(parentPage.getLevel() + 1);
            } else {
                log.warn("page parent page does not exist. Page title is " + pageValue.getTitle()
                        + ". Parent page uuid is " + pageValue.getParent().getPageUuid());
            }
        } else
            //root page, such as home page
            page.setLevel(0);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //update page tags
    tagService.saveUpdatePageTag(page, pageValue.getTagString());

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // !!!! Important: this update attachments status must before  renderService.renderHTML(page)
    // otherwise, the drafts attachment won't render in {attach} or {gallery} macro....

    // Update page attachment status 
    //   remove this user's draft, does not use getDraft() then remove, because following error: 
    //      org.hibernate.HibernateException: Found shared references to a collection: com.edgenius.wiki.model.Page.tags
    try {
        User viewer = WikiUtil.getUser(userReadingService);
        mergeAttahment(getPageAttachment(spaceUname, page.getPageUuid(), true, true, viewer),
                pageValue.getAttachments(), spaceUname, viewer, PageType.NONE_DRAFT);
        upgradeAttachmentStatus(spaceUname, page.getPageUuid(), page.getModifier(), PageType.NONE_DRAFT);
    } catch (RepositoryException e) {
        //not critical exception, just log:
        log.error("Update attachment status during saving page:" + page.getPageUuid() + " in space "
                + spaceUname + ".Error: ", e);
    } catch (RepositoryTiemoutExcetpion e) {
        log.error("Merge attachment saving page:" + page.getPageUuid() + " in space " + spaceUname + ".Error: ",
                e);
    }

    List<RenderPiece> pieces = renderService.renderHTML(page);
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //update page links
    Set<PageLink> links = page.getLinks();
    if (links == null) {
        links = new HashSet<PageLink>();
        page.setLinks(links);
    }

    List<PageLink> newLinks = new ArrayList<PageLink>();
    for (RenderPiece object : pieces) {
        if (object instanceof LinkModel) {
            LinkModel ln = (LinkModel) object;
            //!!! Only linkToCreate and LinkToView support at moment(29/10/2008)
            if (ln.getType() == LinkModel.LINK_TO_CREATE_FLAG || ln.getType() == LinkModel.LINK_TO_VIEW_FLAG) {
                if (StringUtils.length(ln.getLink()) > SharedConstants.TITLE_MAX_LEN) {
                    log.warn("Found invalid link(too long), skip it on PageLink table:" + ln.getLink()
                            + " on page " + newPageTitle);
                } else {
                    PageLink link = PageLink.copyFrom(page, ln);
                    newLinks.add(link);
                }
            }
        }
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //update menu item for space
    //found other if current page has menuItem macro.

    MenuItem menuItem = null;
    //if this marked true, it will trigger the Shell update space request, so update Shell menu.
    page.setMenuUpdated(false);

    for (RenderPiece renderPiece : pieces) {
        if (renderPiece instanceof MacroModel
                && MenuItemMacro.NAME.equalsIgnoreCase(((MacroModel) renderPiece).macroName)) {
            //copy value to MenuItem object
            menuItem = new MenuItem();
            HashMap<String, String> values = ((MacroModel) renderPiece).values;
            if (values != null) {
                menuItem.setTitle(values.get(NameConstants.TITLE));
                menuItem.setOrder(NumberUtils.toInt(values.get(NameConstants.ORDER)));
                menuItem.setParent(values.get(NameConstants.PARENT_UUID));
            }
            menuItem.setPageTitle(page.getTitle());
            menuItem.setPageUuid(page.getPageUuid());
            //suppose only one menuItem in a page, if multiple, even also only use first of them.
            break;
        }
    }

    Set<MenuItem> menuItems = space.getSetting().getMenuItems();
    if (menuItem != null) {
        //update menu list in current space setting
        if (menuItems == null) {
            menuItems = new TreeSet<MenuItem>(new MenuItemComparator());
            space.getSetting().setMenuItems(menuItems);
        } else {
            //try to remove old value
            menuItems.remove(menuItem);
        }

        log.info("Menu item is add or update to page {}.", page.getPageUuid());
        menuItems.add(menuItem);
        settingService.saveOrUpdateSpaceSetting(space, space.getSetting());
        page.setMenuUpdated(true);
    } else if (menuItems != null) {
        //need check if menu item is deleted from page if it had. Try to remove it.
        if (menuItems.remove(new MenuItem(page.getPageUuid()))) {
            log.info("Menu item is removed from page {}.", page.getPageUuid());
            settingService.saveOrUpdateSpaceSetting(space, space.getSetting());
            page.setMenuUpdated(true);
        }
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //merge new links and existed links
    //delete non-existed
    for (Iterator<PageLink> iter = links.iterator(); iter.hasNext();) {
        PageLink ln = iter.next();
        ln.setAmount(0);
        for (Iterator<PageLink> newIter = newLinks.iterator(); newIter.hasNext();) {
            PageLink nlnk = newIter.next();
            if (ln.equals(nlnk)) {
                ln.setAmount(ln.getAmount() + 1);
                newIter.remove();
            }
        }
        if (ln.getAmount() == 0) {
            iter.remove();
        }
    }
    if (newLinks.size() > 0) {
        ArrayList<PageLink> linksList = new ArrayList<PageLink>(links);
        //there some new added links
        int idx;
        for (PageLink newLnk : newLinks) {
            if ((idx = linksList.indexOf(newLnk)) != -1) {
                PageLink ln = linksList.get(idx);
                ln.setAmount(ln.getAmount() + 1);
            } else {
                linksList.add(newLnk);
            }
        }
        links.clear();
        links.addAll(linksList);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //persistent
    page.setType(PageType.NONE_DRAFT);
    pageDAO.saveOrUpdate(page);

    //!!!NOTE: follow 3 lines code must after pageDAO.saveOrUpdate(),otherwise, if home page
    // is new page and contain link, method pageDAO.getCurrentByTitle() in LinkRenderHelper.exist() 
    //method will throw exception!!!(15/03/2007_my new car Honda Accord arrives in home:)
    if (pageValue.getNewPageType() == PageAttribute.NEW_HOMEPAGE) {
        space.setHomepage(page);
        spaceDAO.saveOrUpdate(space);
    }

    //update cache only when a new page created or page title updated
    if (needRefreshCache) {
        addPageCache(spaceUname, page);
    }
    refreshAncestors(spaceUname, page);

    //page title change so change all page which refer link to this page.
    //only title change,oldTitle is not null.
    if ((Global.AutoFixLinks & WikiConstants.AUTO_FIX_TITLE_CHANGE_LINK) > 0 && oldTitle != null) {
        String newTitle = page.getTitle();
        try {
            fixLinksToTitle(spaceUname, oldTitle, newTitle);
        } catch (Exception e) {
            log.error("Unable to fix page title change on other pages content.", e);
        }
    }

    //remove all draft whatever auto or manual
    removeDraftInternal(spaceUname, page.getPageUuid(), page.getModifier(), PageType.NONE_DRAFT, false);

    //MOVE to PageIndexInterceptor
    //      if(requireNotified)
    //         sendNodification(page);

    log.info("Page saved " + newPageTitle + " on space " + spaceUname + ". Page uid: " + newPageUid);

    PageEventListener[] listeners = eventContainer.getPageEventListeners(page.getPageUuid());
    if (listeners != null && listeners.length > 0) {
        log.info("Page saved event dispatching...");
        for (PageEventListener listener : listeners) {
            try {
                listener.pageSaving(page.getPageUuid());
            } catch (PageEventHanderException e) {
                log.error("Page saved event processed failed on " + listener.getClass().getName(), e);
            }
        }
    }
    return page;

}

From source file:hydrograph.ui.dataviewer.preferencepage.ViewDataPreferencesDialog.java

private boolean validateDelimiterAndQuoteCharactorProperty(String textBoxValue, String textBoxValue2,
        ControlDecoration singleCharactorDecorator, ControlDecoration duplicateDecorator) {
    if (StringUtils.length(ConvertHexValues.parseHex(textBoxValue)) == 1) {
        enableAndDisableOkButtonIfAnyDecoratorIsVisible();
        if (!(textBoxValue.equalsIgnoreCase(",") || textBoxValue.equalsIgnoreCase("\""))
                && !textBoxValue.equalsIgnoreCase(textBoxValue2)) {
            warningLabel.setText(Messages.WARNING_MESSAGE);
            warningLabel.setVisible(true);
            warningImageLabel.setVisible(true);
            hideDelimiterAndQuoteCharactorDecorator();
            if (StringUtils.length(ConvertHexValues.parseHex(textBoxValue2)) > 1) {
                getButton(0).setEnabled(false);
            } else {
                getButton(0).setEnabled(true);
                enableAndDisableOkButtonIfAnyDecoratorIsVisible();
            }//from ww  w  .ja  v  a 2 s  . co  m
            return false;
        } else {
            if (textBoxValue.equalsIgnoreCase(textBoxValue2)) {
                duplicateDecorator.show();
                getButton(0).setEnabled(false);
                return false;
            } else {
                showWarningMessage(textBoxValue, textBoxValue2);
                duplicateDecorator.hide();
                enableAndDisableOkButtonIfAnyDecoratorIsVisible();
                return true;
            }
        }
    } else {
        if (!textBoxValue.isEmpty()) {
            singleCharactorDecorator.show();
            getButton(0).setEnabled(false);
        }
        return false;
    }
}

From source file:io.seldon.api.state.ClientAlgorithmStore.java

@Override
public void configUpdated(String configKey, String configValue) {
    configValue = StringUtils.strip(configValue);
    logger.info("KEY WAS " + configKey);
    logger.info("Received new default strategy: " + configValue);

    if (StringUtils.length(configValue) == 0) {
        logger.warn("*WARNING* no default strategy is set!");
    } else {//from   w  ww.  j  av a2 s . c  o  m
        try {
            ObjectMapper mapper = new ObjectMapper();
            List<AlgorithmStrategy> strategies = new ArrayList<>();
            AlgorithmConfig config = mapper.readValue(configValue, AlgorithmConfig.class);

            for (Algorithm alg : config.algorithms) {
                strategies.add(toAlgorithmStrategy(alg));
            }
            AlgorithmResultsCombiner combiner = applicationContext.getBean(config.combiner,
                    AlgorithmResultsCombiner.class);
            Map<Integer, Double> actionWeightMap = toActionWeightMap(config.actionWeights);
            ClientStrategy strat = new SimpleClientStrategy(strategies, combiner, config.diversityLevel, "-",
                    actionWeightMap);
            defaultStrategy = strat;
            logger.info("Successfully changed default strategy.");
        } catch (IOException e) {
            logger.error("Problem changing default strategy ", e);
        }
    }
}

From source file:hydrograph.ui.dataviewer.preferencepage.ViewDataPreference.java

private Notification validateDelimiter() {
    Notification notification = new Notification();
    if (StringUtils.isNotBlank(delimiterEditor.getStringValue())
            && delimiterEditor.getStringValue().equalsIgnoreCase(quoteEditor.getStringValue())) {
        notification.addError(Messages.DELIMITER_VALUE_MATCH_ERROR);
    }/*from w  ww  . j av  a  2s  .  c  om*/
    if (StringUtils.length(ConvertHexValues.parseHex(delimiterEditor.getStringValue())) != 1) {
        notification.addError(Messages.DELIMITER_SINGLE_CHARACTOR_ERROR_MESSAGE);
    }
    return notification;
}

From source file:hydrograph.ui.dataviewer.preferencepage.ViewDataPreference.java

private Notification validateQuoteCharacter() {
    Notification notification = new Notification();
    if (StringUtils.isNotBlank(quoteEditor.getStringValue())
            && quoteEditor.getStringValue().equalsIgnoreCase(delimiterEditor.getStringValue())) {
        notification.addError(Messages.QUOTE_VALUE_MATCH_ERROR);
    }/*from  www. j  av a2  s.  c  o m*/
    if (StringUtils.length(ConvertHexValues.parseHex(quoteEditor.getStringValue())) != 1) {
        notification.addError(Messages.QUOTE_SINGLE_CHARACTOR_ERROR_MESSAGE);
    }
    return notification;
}

From source file:com.oneops.sensor.ws.SensorWsController.java

private void fixTS(CiOpenEvent event) {
    String timestampS = String.valueOf(event.getTimestamp());
    if (StringUtils.length(timestampS) < LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES) {
        String timeStamp = StringUtils.rightPad(timestampS, LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES, '0');
        logger.info("Corrected TS for  " + event.getName() + "oldTs: " + timestampS + " :correctedValue: "
                + timeStamp);/*from   w  w  w .j  av  a 2  s .c om*/
        event.setTimestamp(Long.valueOf(timeStamp));
    } else if (StringUtils.length(timestampS) > LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES) {
        String timeStamp = StringUtils.substring(timestampS, 0, LENGTH_OF_TIMESTAMP_FOR_TWO_CENTURIES);
        event.setTimestamp(Long.valueOf(timeStamp));
        logger.info("Corrected TS for" + event.getName() + " timestamp fixed with " + timeStamp);
    }
}

From source file:gtu._work.ui.RegexCatchReplacer_Ebao.java

private void callEbaoMsgId(String msgId, boolean exactSearch) {
    if (StringUtils.isBlank(msgId) || StringUtils.length(msgId) < 3) {
        return;//from ww w  . jav  a2 s .  c o  m
    }
    String dataLike = " like '%" + msgId + "%' ";
    if (exactSearch) {
        dataLike = " = '" + msgId + "' ";
    }
    String sql = "select * from t_string_resource where (str_id = '" + msgId + "' or str_data " + dataLike
            + ") and lang_id = 311 ";
    try {
        Connection conn = this.getDbDataSource().getConnection();
        List<Map<String, Object>> queryList = JdbcDBUtil.queryForList(sql, null, conn, false);
        DefaultTableModel model = (DefaultTableModel) ebaoTable.getModel();
        for (Map<String, Object> map : queryList) {
            model.addRow(new Object[] { map.get("STR_ID"), map.get("STR_DATA") });
        }
        try {
            conn.close();
        } catch (Exception ex) {
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.manydesigns.portofino.pageactions.crud.CrudAction4ItsProject.java

/**
 * <p>/*www.  j a  v a 2  s. c om*/
 * Returns an array of column sizes (in characters) for the search export.<br />
 * By default, sizes are computed comparing the relative sizes of each column, consisting of the header and the
 * values produced by the search.
 * </p>
 * <p>
 * Users can override this method to compute the sizes using a different algorithm, or hard-coding them for a
 * particular CRUD instance.
 * </p>
 */
protected double[] setupXmlSearchColumnSizes() {
    double[] headerSizes = new double[tableForm.getColumns().length];
    for (int i = 0; i < headerSizes.length; i++) {
        TableForm.Column col = tableForm.getColumns()[i];
        int length = StringUtils.length(col.getLabel());
        headerSizes[i] = length;
    }

    double[] columnSizes = new double[tableForm.getColumns().length];
    for (TableForm.Row row : tableForm.getRows()) {
        int i = 0;
        for (Field field : row) {
            int size = StringUtils.length(field.getStringValue());
            double relativeSize = ((double) size) / tableForm.getRows().length;
            columnSizes[i++] += relativeSize;
        }
    }

    double totalSize = 0;
    for (int i = 0; i < columnSizes.length; i++) {
        double effectiveSize = Math.max(columnSizes[i], headerSizes[i]);
        columnSizes[i] = effectiveSize;
        totalSize += effectiveSize;
    }
    while (totalSize > 75) {
        int maxIndex = 0;
        double max = 0;
        for (int i = 0; i < columnSizes.length; i++) {
            if (columnSizes[i] > max) {
                max = columnSizes[i];
                maxIndex = i;
            }
        }
        columnSizes[maxIndex] -= 1;
        totalSize -= 1;
    }
    while (totalSize < 70) {
        int minIndex = 0;
        double min = Double.MAX_VALUE;
        for (int i = 0; i < columnSizes.length; i++) {
            if (columnSizes[i] < min) {
                min = columnSizes[i];
                minIndex = i;
            }
        }
        columnSizes[minIndex] += 1;
        totalSize += 1;
    }
    return columnSizes;
}

From source file:com.iyonger.apm.web.service.PerfTestService.java

String getProperSizedStatusString(Map<String, SystemDataModel> agentStatusMap) {
    String json = gson.toJson(agentStatusMap);
    int statusLength = StringUtils.length(json);
    if (statusLength > 9950) { // max column size is 10,000
        LOGGER.info("Agent status string length: {}, too long to save into table.", statusLength);
        double ratio = 9900.0 / statusLength;
        int pickSize = (int) (agentStatusMap.size() * ratio);
        Map<String, SystemDataModel> pickAgentStateMap = Maps.newHashMap();

        int pickIndex = 0;
        for (Entry<String, SystemDataModel> each : agentStatusMap.entrySet()) {
            if (pickIndex < pickSize) {
                pickAgentStateMap.put(each.getKey(), each.getValue());
                pickIndex++;//  w  ww  . j  a va 2  s. c om
            }
        }
        json = gson.toJson(pickAgentStateMap);
        LOGGER.debug("Agent status string get {} outof {} agents, new size is {}.",
                new Object[] { pickSize, agentStatusMap.size(), json.length() });
    }
    return json;
}

From source file:ca.sqlpower.matchmaker.address.AddressPool.java

private String adjustSize(String source, Integer size) {
    if (size == null) {
        return source; // we couldn't obtain the column size, so do nothing.
    }/*from w ww .  j  a  v a  2  s  .  c om*/

    if (StringUtils.length(source) > size) {
        return StringUtils.substring(source, 0, size);
    }

    return source;
}