Example usage for org.springframework.util StringUtils isEmpty

List of usage examples for org.springframework.util StringUtils isEmpty

Introduction

In this page you can find the example usage for org.springframework.util StringUtils isEmpty.

Prototype

public static boolean isEmpty(@Nullable Object str) 

Source Link

Document

Check whether the given object (possibly a String ) is empty.

Usage

From source file:org.ihtsdo.otf.snomed.service.ConceptLookUpServiceImpl.java

@Override
@Cacheable(value = { "concept" })
public Concept getConcept(String conceptId) throws ConceptServiceException, EntityNotFoundException {

    LOGGER.debug("getting concept details for {} ", conceptId);

    if (StringUtils.isEmpty(conceptId)) {

        throw new EntityNotFoundException(String.format("Invalid concept id", conceptId));
    }/*from w ww .  j  av  a  2s  . c o m*/

    TitanGraph g = null;

    try {

        g = factory.getReadOnlyGraph();

        Iterable<Vertex> vs = g.getVertices(Properties.sctid.toString(), conceptId);

        for (Vertex v : vs) {

            Concept c = convertToConcept(v);
            RefsetGraphFactory.commit(g);

            return c;

        }

        RefsetGraphFactory.commit(g);

    } catch (Exception e) {

        LOGGER.error("Error duing concept details fetch", e);
        RefsetGraphFactory.rollback(g);

        throw new ConceptServiceException(e);

    } finally {

        RefsetGraphFactory.shutdown(g);
    }

    throw new EntityNotFoundException(String.format("Invalid concept id", conceptId));

}

From source file:com.formkiq.core.dao.QueueDaoImpl.java

@Override
public void save(final QueueMessage message) {

    Date now = this.dateservice.now();

    if (message.getInsertedDate() == null) {
        message.setInsertedDate(now);// w w  w .j av a2s  .  co  m
    }

    if (StringUtils.isEmpty(message.getQueuemessageid())) {
        message.setQueuemessageid(UUID.randomUUID());
        getEntityManager().persist(message);

    } else {

        getEntityManager().merge(message);
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.isservice.search.service.impl.SearchIndexServiceImpl.java

@Override
public SearchIndexResultSet query(QueryRequest query) throws IndexAndSearchException {
    ExecutorCompletionService<SearchIndexResultSet> completionService = new ExecutorCompletionService<>(
            taskExecutor);// w ww  . ja  v a 2s.c om
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "query", "[query:" + query + "]"));
    // 1. Does all the existed index cover this query
    // 2. get index meta and index shard
    // 3. trans query to Query that can used for searching
    // 4. dispatch search query
    // 5. do search
    // 6. merge result
    // 7. return

    if (query == null || StringUtils.isEmpty(query.getCubeId())) {
        LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "query",
                "[query:" + query + "]"));
        throw new IndexAndSearchException(
                TesseractExceptionUtils.getExceptionMessage(IndexAndSearchException.QUERYEXCEPTION_MESSAGE,
                        IndexAndSearchExceptionType.ILLEGALARGUMENT_EXCEPTION),
                IndexAndSearchExceptionType.ILLEGALARGUMENT_EXCEPTION);
    }
    IndexMeta idxMeta = this.idxMetaService.getIndexMetaByCubeId(query.getCubeId(),
            query.getDataSourceInfo().getDataSourceKey());

    SearchIndexResultSet result = null;
    long current = System.currentTimeMillis();
    if (idxMeta == null || idxMeta.getIdxState().equals(IndexState.INDEX_UNAVAILABLE)
            || idxMeta.getIdxState().equals(IndexState.INDEX_UNINIT) || !query.isUseIndex()
            || (query.getFrom() != null && query.getFrom().getFrom() != null
                    && !idxMeta.getDataDescInfo().getTableNameList().contains(query.getFrom().getFrom()))
            || !indexMetaContains(idxMeta, query)) {
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_PROCESS_NO_PARAM, "query",
                "use database"));
        // index does not exist or unavailable,use db query
        SqlQuery sqlQuery = QueryRequestUtil.transQueryRequest2SqlQuery(query);
        SqlDataSourceWrap dataSourceWrape = null;
        try {
            dataSourceWrape = (SqlDataSourceWrap) this.dataSourcePoolService
                    .getDataSourceByKey(query.getDataSourceInfo());
        } catch (DataSourceException e) {
            LOGGER.error(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_EXCEPTION, "query",
                    "[query:" + query + "]", e));
            throw new IndexAndSearchException(
                    TesseractExceptionUtils.getExceptionMessage(IndexAndSearchException.QUERYEXCEPTION_MESSAGE,
                            IndexAndSearchExceptionType.SQL_EXCEPTION),
                    e, IndexAndSearchExceptionType.SQL_EXCEPTION);
        }
        if (dataSourceWrape == null) {
            throw new IllegalArgumentException();
        }

        long limitStart = 0;
        long limitSize = 0;
        if (query.getLimit() != null) {
            limitStart = query.getLimit().getStart();
            if (query.getLimit().getSize() > 0) {
                limitSize = query.getLimit().getSize();
            }

        }
        SearchIndexResultSet currResult = this.dataQueryService.queryForListWithSQLQueryAndGroupBy(sqlQuery,
                dataSourceWrape, limitStart, limitSize, query);
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_PROCESS_NO_PARAM, "query",
                "db return " + currResult.size() + " records"));
        result = currResult;
    } else {
        LOGGER.info(
                String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_PROCESS_NO_PARAM, "query", "use index"));

        LOGGER.info("cost :" + (System.currentTimeMillis() - current) + " before prepare get record.");
        current = System.currentTimeMillis();

        List<SearchIndexResultSet> idxShardResultSetList = new ArrayList<SearchIndexResultSet>();
        for (IndexShard idxShard : idxMeta.getIdxShardList()) {

            if (idxShard.getIdxState().equals(IndexState.INDEX_UNINIT)) {
                continue;
            }

            completionService.submit(new Callable<SearchIndexResultSet>() {

                @Override
                public SearchIndexResultSet call() throws Exception {
                    try {
                        long current = System.currentTimeMillis();
                        Node searchNode = isNodeService.getFreeSearchNodeByIndexShard(idxShard,
                                idxMeta.getClusterName());
                        searchNode.searchRequestCountAdd();
                        isNodeService.saveOrUpdateNodeInfo(searchNode);
                        LOGGER.info("begin search in shard:{}", idxShard);
                        SearchIndexResultSet result = (SearchIndexResultSet) isClient
                                .search(query, idxShard, searchNode).getMessageBody();
                        searchNode.searchrequestCountSub();
                        isNodeService.saveOrUpdateNodeInfo(searchNode);
                        LOGGER.info("compelete search in shard:{},take:{} ms", idxShard,
                                System.currentTimeMillis() - current);
                        return result;
                    } catch (Exception e) {
                        throw new IndexAndSearchException(
                                TesseractExceptionUtils.getExceptionMessage(
                                        IndexAndSearchException.QUERYEXCEPTION_MESSAGE,
                                        IndexAndSearchExceptionType.NETWORK_EXCEPTION),
                                e, IndexAndSearchExceptionType.NETWORK_EXCEPTION);
                    }

                }
            });
        }
        for (int i = 0; i < idxMeta.getIdxShardList().size(); i++) {
            try {
                idxShardResultSetList.add(completionService.take().get());
            } catch (InterruptedException | ExecutionException e) {
                throw new IndexAndSearchException(
                        TesseractExceptionUtils.getExceptionMessage(
                                IndexAndSearchException.QUERYEXCEPTION_MESSAGE,
                                IndexAndSearchExceptionType.NETWORK_EXCEPTION),
                        e, IndexAndSearchExceptionType.NETWORK_EXCEPTION);
            }
        }
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_PROCESS_NO_PARAM, "query",
                "merging result from multiple index"));
        result = mergeResultSet(idxShardResultSetList, query);
        StringBuilder sb = new StringBuilder();
        sb.append("cost :").append(System.currentTimeMillis() - current)
                .append(" in get result record,result size:").append(result.size()).append(" shard size:")
                .append(idxShardResultSetList.size());

        LOGGER.info(sb.toString());
        current = System.currentTimeMillis();
    }

    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_PROCESS_NO_PARAM, "query",
            "merging final result"));

    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "query", "[query:" + query + "]"));
    return result;
}

From source file:com.sastix.cms.server.services.content.impl.CommonResourceServiceImpl.java

public String getRelativePath(final String uuri, final String tenantID, final byte[] binary,
        final String binaryURI) throws ContentValidationException, ResourceAccessError {
    //save resource in volume
    String relativePath;/* ww  w.ja  va 2 s  . c  o  m*/
    try {
        if (binary != null && !StringUtils.isEmpty(binaryURI)) {
            throw new ContentValidationException(
                    "Field errors: resourceBinary OR resourceExternalURI should be null");
        } else if (binary != null && binary.length > 0) {
            relativePath = hashedDirectoryService.storeFile(uuri, tenantID, binary);
        } else if (!StringUtils.isEmpty(binaryURI)) {
            relativePath = hashedDirectoryService.storeFile(uuri, tenantID, binaryURI);
        } else {
            throw new ContentValidationException(
                    "Field errors: resourceBinary OR resourceExternalURI may not be null");
        }
    } catch (Exception e) {
        if (e instanceof ContentValidationException) {
            throw (ContentValidationException) e;
        }
        throw new ResourceAccessError(e.toString());
    }
    return relativePath;
}

From source file:com.abuabdul.knodex.controller.KxLandingController.java

@RequestMapping("/remove/knodexSentenceToIndex")
@ResponseBody/* w  ww  . j  ava2 s. c om*/
public String removeIndexInformation(@ModelAttribute("knodexForm") KnodexForm knodex, String knodexId) {
    log.debug("Entering removeIndexInformation() in the KxLandingController");
    String parsedId = "";
    boolean deleted = false;
    if (!StringUtils.isEmpty(knodexId)) {
        log.debug("Parse the knodex Id in the KxLandingController " + knodexId);
        String[] idArray = knodexId.split("_");
        if (idArray != null && idArray.length != 0) {
            parsedId = idArray[idArray.length - 1];
            log.debug("Id of the record to be deleted - " + parsedId);
            deleted = kxDocumentService.removeASentence(parsedId);
        }

    }
    return String.valueOf(deleted);
}

From source file:burstcoin.observer.service.AssetService.java

private void startCheckAssetsTask() {
    timer.schedule(new TimerTask() {
        @Override/*from w  w  w . j a va  2  s  .c o  m*/
        public void run() {
            try {
                LOG.info("START import asset data from " + ObserverProperties.getWalletUrl());
                Map<String, Asset> assetLookup = createAssetLookup();
                Map<OrderType, Map<Asset, List<Order>>> orderLookup = createOrderLookup(assetLookup);
                Map<Asset, List<Trade>> tradeLookup = getTradeLookup(assetLookup);

                State state = getState();
                LOG.info("FINISH import asset data!");

                List<AssetBean> assetBeans = new ArrayList<>();
                List<AssetCandleStickBean> assetCandleStickBeans = new ArrayList<>();
                for (Asset asset : assetLookup.values()) {
                    List<List> candleStickData = new ArrayList<List>();
                    long volume7Days = 0L;
                    long volume30Days = 0L;
                    String lastPrice = "";
                    List<Trade> trades = tradeLookup.get(asset);
                    if (trades != null && !trades.isEmpty()) {
                        Iterator<Trade> iterator = trades.iterator();
                        boolean withinLast30Days = true;

                        while (withinLast30Days && iterator.hasNext()) {
                            Trade trade = iterator.next();
                            if (StringUtils.isEmpty(lastPrice)) {
                                lastPrice = convertPrice(trade.getPriceNQT(), trade.getDecimals());
                            }

                            Integer bidOrderBlock = Integer.valueOf(trade.getBidOrderHeight());
                            Integer askOrderBlock = Integer.valueOf(trade.getAskOrderHeight());
                            int block = bidOrderBlock >= askOrderBlock ? bidOrderBlock : askOrderBlock;
                            withinLast30Days = state.getNumberOfBlocks() - 360 * 30 < block;

                            if (withinLast30Days) {
                                long volume = Long.valueOf(trade.getPriceNQT())
                                        * Long.valueOf(trade.getQuantityQNT());
                                volume30Days += volume;

                                if (state.getNumberOfBlocks() - 360 * 7 < block) {
                                    volume7Days += volume;
                                }
                            }
                        }

                        Long currentBlockHeight = Long.valueOf(state.getNumberOfBlocks());

                        for (int i = 1; i <= 60 /*days*/; i++) {
                            List<Trade> tradesOfDay = new ArrayList<Trade>();
                            for (Trade trade : trades) {
                                if (trade.getHeight() > currentBlockHeight - (360 * (i + 1))
                                        && trade.getHeight() < currentBlockHeight - (360 * i)) {
                                    tradesOfDay.add(trade);
                                }
                            }

                            Double min = null;
                            Double max = null;
                            Double first = null;
                            Double last = null;

                            for (Trade trade : tradesOfDay) {
                                double price = Double
                                        .valueOf(convertPrice(trade.getPriceNQT(), trade.getDecimals()));
                                if (first == null) {
                                    first = price;
                                }
                                if (min == null || price < min) {
                                    min = price;
                                }
                                if (max == null || price > max) {
                                    max = price;
                                }
                                if (tradesOfDay.indexOf(trade) == tradesOfDay.size() - 1) {
                                    last = price;
                                }
                            }

                            if (min != null && max != null && first != null && last != null) {
                                List x = Arrays.asList("" + i, min, first, last, max);
                                candleStickData.add(x);
                            } else {
                                candleStickData.add(Arrays.asList("" + i, null, null, null, null));
                            }
                        }
                    }

                    Collections.reverse(candleStickData);

                    List<Order> sellOrders = orderLookup.get(OrderType.ASK).get(asset) != null
                            ? orderLookup.get(OrderType.ASK).get(asset)
                            : new ArrayList<>();
                    List<Order> buyOrders = orderLookup.get(OrderType.BID).get(asset) != null
                            ? orderLookup.get(OrderType.BID).get(asset)
                            : new ArrayList<>();

                    if (!(buyOrders.isEmpty() && sellOrders.isEmpty() && asset.getNumberOfTrades() < 2)) {
                        assetBeans.add(new AssetBean(asset.getAsset(), asset.getName(), asset.getDescription(),
                                asset.getAccountRS(), asset.getAccount(), asset.getQuantityQNT(),
                                asset.getDecimals(), asset.getNumberOfAccounts(), asset.getNumberOfTransfers(),
                                asset.getNumberOfTrades(), buyOrders.size(), sellOrders.size(),
                                formatAmountNQT(volume7Days, 8), formatAmountNQT(volume30Days, 8), lastPrice));
                        assetCandleStickBeans.add(new AssetCandleStickBean(asset.getAsset(), candleStickData));
                    }
                }
                Collections.sort(assetBeans, new Comparator<AssetBean>() {
                    @Override
                    public int compare(AssetBean o1, AssetBean o2) {
                        return Long.valueOf(o2.getVolume30Days()).compareTo(Long.valueOf(o1.getVolume30Days()));
                    }
                });
                Collections.sort(assetBeans, new Comparator<AssetBean>() {
                    @Override
                    public int compare(AssetBean o1, AssetBean o2) {
                        return Long.valueOf(o2.getVolume7Days()).compareTo(Long.valueOf(o1.getVolume7Days()));
                    }
                });

                // delete data of candleStick for all after index 24 todo remove as soon ui has show/hide charts per asset
                List<String> assetOrder = new ArrayList<String>();
                for (AssetBean assetBean : assetBeans) {
                    assetOrder.add(assetBean.getAsset());
                }
                assetCandleStickBeans.sort(new Comparator<AssetCandleStickBean>() {
                    @Override
                    public int compare(AssetCandleStickBean o1, AssetCandleStickBean o2) {
                        return ((Integer) assetOrder.indexOf(o1.getAsset()))
                                .compareTo(assetOrder.indexOf(o2.getAsset()));
                    }
                });

                publisher.publishEvent(new AssetUpdateEvent(assetBeans, assetCandleStickBeans));
            } catch (Exception e) {
                LOG.error("Failed update assets!", e);
            }
        }
    }, 200, ObserverProperties.getAssetRefreshInterval());
}

From source file:com.formkiq.core.util.Strings.java

/**
 * Extract Label / Value from String.// www  . ja v  a  2s.co m
 * @param s {@link String}
 * @return {@link Pair}
 */
public static Pair<String, String> extractLabelAndValue(final String s) {

    if (!StringUtils.isEmpty(s)) {

        Matcher m = EXTRACT_LABEL_VALUE.matcher(s);
        if (m.matches()) {
            return Pair.of(m.group(1), m.group(2));
        }

        return Pair.of(s, s);
    }

    return Pair.of("", "");
}

From source file:com.github.dactiv.fear.service.service.message.MessageService.java

/**
 * ???//from   w  w  w  .java  2  s  . c  o m
 *
 * @param nickname 
 * @param javaMailSender ??
 *
 * @return ??
 */
private String getSendForm(String nickname, JavaMailSender javaMailSender) {

    JavaMailSenderImpl impl = null;

    if (javaMailSender instanceof JavaMailSenderImpl) {
        impl = (JavaMailSenderImpl) javaMailSender;
    }

    if (impl == null) {
        throw new ServiceException(
                JavaMailSenderImpl.class + " ?? " + javaMailSender.getClass() + "");
    }

    String address;

    String propertiesNickname = impl.getJavaMailProperties().getProperty("mail.nickname", nickname);

    try {
        if (StringUtils.isEmpty(propertiesNickname)) {
            address = impl.getUsername();
        } else {
            address = MimeUtility.encodeText(propertiesNickname) + " <" + impl.getUsername() + ">";
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn("?[" + nickname + "],?" + impl.getUsername()
                + "", e);
        address = impl.getUsername();
    }

    return address;

}

From source file:com.baidu.rigel.biplatform.ma.report.utils.QueryUtils.java

/**
 * /*from  w  w  w.j  a v  a 2 s. c  om*/
 * ?
 * @param dsDefine 
 * 
 * @param queryAction
 *            
 * @return 
 * @throws QueryModelBuildException
 *             
 */
public static QuestionModel convert2QuestionModel(DataSourceDefine dsDefine, ReportDesignModel reportModel,
        QueryAction queryAction, String securityKey) throws QueryModelBuildException {
    if (queryAction == null) {
        throw new QueryModelBuildException("query action is null");
    }
    ConfigQuestionModel questionModel = new ConfigQuestionModel();
    String areaId = queryAction.getExtendAreaId();
    if (StringUtils.isEmpty(areaId)) {
        throw new QueryModelBuildException("area id is empty");
    }
    ExtendArea area = reportModel.getExtendById(areaId);
    if (area == null) {
        throw new QueryModelBuildException("can not get area with id : " + areaId);
    }
    Cube cube = getCubeWithExtendArea(reportModel, area);
    if (cube == null) {
        throw new QueryModelBuildException("can not get cube define in area : " + areaId);
    }
    // ?
    questionModel.setAxisMetas(buildAxisMeta(reportModel.getSchema(), area, queryAction));
    // ?
    questionModel.setQueryConditions(buildQueryConditions(reportModel, area, queryAction));
    questionModel.setCubeId(area.getCubeId());
    ((MiniCube) cube).setProductLine(dsDefine.getProductLine());
    // TODO ?cube ? ?
    Set<Item> tmp = Sets.newHashSet();
    tmp.addAll(queryAction.getSlices().keySet());
    tmp.addAll(queryAction.getRows().keySet());
    //        updateLogicCubeWithSlices(cube, tmp,
    //                reportModel.getSchema().getCubes().get(area.getCubeId()));
    questionModel.setCube(cube);
    questionModel.setDataSourceInfo(buidDataSourceInfo(dsDefine, securityKey));
    MeasureOrderDesc orderDesc = queryAction.getMeasureOrderDesc();
    if (orderDesc != null) {
        SortType sortType = SortType.valueOf(orderDesc.getOrderType());
        String uniqueName = "[Measure].[" + orderDesc.getName() + "]";
        SortRecord sortRecord = new SortRecord(sortType, uniqueName, orderDesc.getRecordSize());
        questionModel.setSortRecord(sortRecord);
    }
    // TODO ?????
    questionModel.getQueryConditionLimit().setWarningAtOverFlow(false);
    if (queryAction.isNeedOthers()) {
        // TODO ?? ?
        questionModel.getRequestParams().put("NEED_OTHERS", "1");
    }
    putSliceConditionIntoParams(queryAction, questionModel);
    questionModel.setFilterBlank(queryAction.isFilterBlank());
    return questionModel;
}

From source file:com.shigengyu.hyperion.core.WorkflowState.java

@Override
public String toString() {
    return !StringUtils.isEmpty(displayName) ? displayName : name;
}