Example usage for org.springframework.util StringUtils hasText

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

Introduction

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

Prototype

public static boolean hasText(@Nullable String str) 

Source Link

Document

Check whether the given String contains actual text.

Usage

From source file:org.cleverbus.api.exception.IntegrationException.java

@Override
public String getMessage() {
    String superMsg = super.getMessage();
    if (StringUtils.hasText(superMsg)) {
        return superMsg;
    }/*from   w  w w  .j  a v  a 2 s . co  m*/

    return getError().getErrDesc();
}

From source file:com.springsource.greenhouse.connect.FacebookConnectInterceptor.java

public void preConnect(ConnectionFactory<Facebook> provider, MultiValueMap<String, String> params,
        WebRequest request) {//  ww  w.  j  a  v a2 s .  co m
    if (StringUtils.hasText(request.getParameter(POST_TO_WALL_PARAMETER))) {
        request.setAttribute(POST_TO_WALL_ATTRIBUTE, Boolean.TRUE, WebRequest.SCOPE_SESSION);
    }
    if (StringUtils.hasText(request.getParameter(USE_FACEBOOK_IMAGE_PARAMETER))) {
        request.setAttribute(USE_FACEBOOK_IMAGE_ATTRIBUTE, Boolean.TRUE, WebRequest.SCOPE_SESSION);
    }
}

From source file:biz.c24.io.spring.batch.config.ItemReaderParser.java

@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder bean) {

    // Optional//from  www  .j a v a2s  .  co  m
    String scope = element.getAttribute("scope");
    if (StringUtils.hasText(scope)) {
        bean.setScope(scope);
    } else {
        // Default to step scope
        bean.setScope("step");
    }

    int numSourceDefns = 0;

    // Optional
    String sourceRef = element.getAttribute("source-ref");
    if (StringUtils.hasText(sourceRef)) {
        bean.addPropertyReference("source", sourceRef);
        numSourceDefns++;
    }

    // Mandatory
    String modelRef = element.getAttribute("model-ref");
    bean.addPropertyReference("model", modelRef);

    // Optional
    String elementStartPattern = element.getAttribute("elementStartPattern");
    if (StringUtils.hasText(elementStartPattern)) {
        bean.addPropertyValue("elementStartPattern", elementStartPattern);
    }

    // Optional
    String elementStopPattern = element.getAttribute("elementStopPattern");
    if (StringUtils.hasText(elementStopPattern)) {
        bean.addPropertyValue("elementStopPattern", elementStopPattern);
    }

    // Optional
    String validate = element.getAttribute("validate");
    if (StringUtils.hasText(validate)) {
        bean.addPropertyValue("validate", validate); //don't evaluate as a boolean until Bean creation time to allow for SpEL
    }

    // Optional
    String failfast = element.getAttribute("failfast");
    if (StringUtils.hasText(failfast)) {
        boolean val = Boolean.parseBoolean(failfast);
        bean.addPropertyValue("failfast", val);
    }

    // Optional
    String sourceFactoryRef = element.getAttribute("source-factory-ref");
    if (StringUtils.hasText(sourceFactoryRef)) {
        bean.addPropertyReference("sourceFactory", sourceFactoryRef);
    }

    // Optional
    String parseListenerRef = element.getAttribute("parse-listener-ref");
    if (StringUtils.hasText(parseListenerRef)) {
        bean.addPropertyReference("parseListener", parseListenerRef);
    }

    Element fileSourceElement = DomUtils.getChildElementByTagName(element, "file-source");
    if (fileSourceElement != null) {
        BeanDefinition beanDefinition = parserContext.getDelegate().parseCustomElement(fileSourceElement,
                bean.getBeanDefinition());
        beanDefinition.setBeanClassName(FileSource.class.getName());
        bean.addPropertyValue("source", beanDefinition);
        numSourceDefns++;
    }

    Element zipFileSourceElement = DomUtils.getChildElementByTagName(element, "zip-file-source");
    if (zipFileSourceElement != null) {
        BeanDefinition beanDefinition = parserContext.getDelegate().parseCustomElement(zipFileSourceElement,
                bean.getBeanDefinition());
        beanDefinition.setBeanClassName(ZipFileSource.class.getName());
        bean.addPropertyValue("source", beanDefinition);
        numSourceDefns++;
    }

    if (numSourceDefns > 1) {
        parserContext.getReaderContext()
                .error("Only one of source-ref, file-source and zip-file-source can be used", element);
    } else if (numSourceDefns == 0) {
        parserContext.getReaderContext()
                .error("One of source-ref, file-source and zip-file-source must be specified", element);
    }

}

From source file:com.consol.citrus.simulator.servlet.SimulatorStatusServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (StringUtils.hasText(req.getQueryString()) && req.getQueryString().contains("clear=true")) {
        testResults.clear();/*w  ww.  ja  v  a2  s. c om*/
    }

    Map<String, Object> model = new HashMap<String, Object>();
    model.put("running", runningTests);
    model.put("results", reverseOrder(testResults));
    model.put("contextPath", req.getContextPath());

    Context context = Context.newContext(model);
    statusTemplate.apply(context, resp.getWriter());
}

From source file:se.alingsas.alfresco.repo.utils.byggreda.ReadMetadataDocument.java

/**
 * Takes an input stream which should point to a metadata document for
 * byggreda. Validates and parses the data and returns a set of
 * ByggRedaDocument//from  www  .  j a va2 s. c o m
 * 
 * @param inputStream
 * @return
 */
public static Set<ByggRedaDocument> read(final InputStream inputStream, List<String> globalMessages) {
    if (inputStream == null) {
        return null;
    }
    Set<ByggRedaDocument> result = new HashSet<ByggRedaDocument>();
    LineIterator lineIterator = null;
    String line = "";
    int lineNumber = 1;
    try {
        lineIterator = IOUtils.lineIterator(inputStream, "ISO-8859-1");
        // Skip first line which is a header line
        if (lineIterator.hasNext()) {

            line = lineIterator.nextLine();
            if (!line.startsWith("\"Film\";\"") && !line.startsWith("Film;")) {
                globalMessages.add(
                        "#1: Sidhuvud ej funnet p frsta raden i styrfilen. Frsta raden var: " + line);
                LOG.error("No header found on the first line in the document. First line was: " + line
                        + ". Aborting...");
                return result;
            } else {
                LOG.debug("Line #" + lineNumber + ": Skipping header");
            }
        }
        while (lineIterator.hasNext()) {
            lineNumber++;
            line = lineIterator.nextLine();
            // if it's an empty line or a comment, skip
            if (!StringUtils.hasText(line) || line.startsWith("#")) {
                globalMessages.add("#" + lineNumber + ": Tom rad, eller bortkommenterad rad funnel, skippas");
                LOG.info("Line #" + lineNumber + ": Skipping comment or empty line");
                continue;
            }
            // Validation and error handling
            ByggRedaDocument document = parseAndValidate(line);
            document.setLineNumber(lineNumber);
            if (!document.isReadSuccessfully()) {
                // An error occured, we need to log this
                LOG.error("Line #" + document.getLineNumber() + ": " + document.getStatusMsg());
            } else {
                // Document successfully read
                LOG.debug("Line #" + document.getLineNumber() + ": "
                        + "Successfully read record. , Record number: " + document.getRecordDisplay());
            }
            result.add(document);
        }
    } catch (final Exception ex) {
        globalMessages.add("#" + lineNumber + ": Fel vid inlsning av rad " + lineNumber
                + " frn styrfil. Radens innehll: " + line + " Systemmeddelande: " + ex.getMessage());
        LOG.error("Error on line '" + lineNumber + "'. Line contents: " + line, ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        LineIterator.closeQuietly(lineIterator);
    }
    return result;
}

From source file:it.cosenonjaviste.alfresco.annotations.processors.runtime.ChildOfConfigurer.java

@Override
protected void processBeanDefinition(ConfigurableListableBeanFactory beanFactory, BeanDefinition bd,
        String beanClassName, String definitionName) throws FatalBeanException {
    try {// w ww  . ja va2  s  . com
        final ChildOf childOf = AnnotationUtils.findAnnotation(Class.forName(beanClassName), ChildOf.class);
        if (childOf != null) {
            final String parentName = childOf.value();
            if (StringUtils.hasText(parentName)) {
                bd.setParentName(parentName);
            } else {
                throw new FatalBeanException(
                        String.format("%s is @ChildOf annotated, but no value set.", beanClassName));
            }
        }
    } catch (ClassNotFoundException e) {
        logger.warn(String.format(
                "ClassNotFoundException while searching for ChildOf annotation on bean name '%s' of type '%s'. This error is expected on Alfresco Community 4.2.c. for some classes in package 'org.alfresco.repo'",
                definitionName, beanClassName));
    }
}

From source file:org.wallride.repository.TagRepositoryImpl.java

@Override
public Page<Tag> search(TagSearchRequest request, Pageable pageable) {
    FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);
    QueryBuilder qb = fullTextEntityManager.getSearchFactory().buildQueryBuilder().forEntity(Tag.class).get();

    @SuppressWarnings("rawtypes")
    BooleanJunction<BooleanJunction> junction = qb.bool();
    junction.must(qb.all().createQuery());

    if (StringUtils.hasText(request.getKeyword())) {
        Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("synonyms");
        String[] fields = new String[] { "name" };
        MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
        parser.setDefaultOperator(QueryParser.Operator.AND);
        Query query = null;//from  w  ww . j  a va2 s.  co m
        try {
            query = parser.parse(request.getKeyword());
        } catch (ParseException e1) {
            try {
                query = parser.parse(QueryParser.escape(request.getKeyword()));
            } catch (ParseException e2) {
                throw new RuntimeException(e2);
            }
        }
        junction.must(query);
    }

    if (StringUtils.hasText(request.getLanguage())) {
        junction.must(qb.keyword().onField("language").matching(request.getLanguage()).createQuery());
    }

    Query searchQuery = junction.createQuery();

    Session session = (Session) entityManager.getDelegate();
    Criteria criteria = session.createCriteria(Tag.class);

    Sort sort = new Sort(new SortField("sortName", SortField.Type.STRING));

    FullTextQuery persistenceQuery = fullTextEntityManager.createFullTextQuery(searchQuery, Tag.class)
            .setCriteriaQuery(criteria).setSort(sort);
    persistenceQuery.setFirstResult(pageable.getOffset());
    persistenceQuery.setMaxResults(pageable.getPageSize());

    int resultSize = persistenceQuery.getResultSize();

    @SuppressWarnings("unchecked")
    List<Tag> results = persistenceQuery.getResultList();
    return new PageImpl<>(results, pageable, resultSize);
}

From source file:com.frank.search.solr.core.TermsQueryParser.java

protected void appendTermsOptionsToSolrQuery(TermsOptions options, SolrQuery solrQuery) {
    solrQuery.setTerms(true);//  w  w  w .j  av  a 2  s . c  o m
    if (options.getLimit() >= 0) {
        solrQuery.setTermsLimit(options.getLimit());
    }
    if (options.getMaxCount() >= -1) {
        solrQuery.setTermsMaxCount(options.getMaxCount());
    }
    if (options.getMinCount() >= 0) {
        solrQuery.setTermsMinCount(options.getMinCount());
    }
    if (StringUtils.hasText(options.getPrefix())) {
        solrQuery.setTermsPrefix(options.getPrefix());
    }
    if (StringUtils.hasText(options.getRegex())) {
        solrQuery.setTermsRegex(options.getRegex());
    }
    if (options.getRegexFlag() != null) {
        solrQuery.setTermsRegexFlag(options.getRegexFlag().toString().toLowerCase());
    }
    if (options.getSort() != null) {
        solrQuery.setTermsSortString(options.getSort().toString().toLowerCase());
    }
    if (options.getUpperBoundTerm() != null) {
        solrQuery.setTermsUpper(options.getUpperBoundTerm().getTerm());
        solrQuery.setTermsUpperInclusive(options.getUpperBoundTerm().isInclude());
    }
    if (options.getLowerBoundTerm() != null) {
        solrQuery.setTermsUpper(options.getLowerBoundTerm().getTerm());
        solrQuery.setTermsUpperInclusive(options.getLowerBoundTerm().isInclude());
    }
    if (!options.isRaw()) {
        solrQuery.setTermsRaw(options.isRaw());
    }

}

From source file:org.copperengine.spring.audit.AuditTrailQueryEngine.java

@Override
public List<AuditTrailInfo> getAuditTrails(String transactionId, String conversationId, String correlationId,
        Integer level, int maxResult) {

    SqlPagingQueryProviderFactoryBean factory = new SqlPagingQueryProviderFactoryBean();

    String sortClause = "SEQ_ID";
    String whereClause = "where 1=1 ";
    List<Object> args = new ArrayList<Object>();

    if (level != null) {
        whereClause += " and LOGLEVEL <= ? ";
        sortClause = "LOGLEVEL";
        args.add(level);/*  ww w  .j a  v a 2 s  .c  om*/
    }
    if (StringUtils.hasText(correlationId)) {
        whereClause += " and CORRELATION_ID = ? ";
        sortClause = "CORRELATION_ID";
        args.add(correlationId);
    }

    if (StringUtils.hasText(conversationId)) {
        whereClause += " and CONVERSATION_ID = ? ";
        sortClause = "CONVERSATION_ID";
        args.add(conversationId);
    }

    if (StringUtils.hasText(transactionId)) {
        whereClause += " and TRANSACTION_ID = ? ";
        sortClause = "TRANSACTION_ID";
        args.add(transactionId);
    }

    String selectClause = "select " + "SEQ_ID," + "TRANSACTION_ID," + "CONVERSATION_ID," + "CORRELATION_ID,"
            + "OCCURRENCE," + "LOGLEVEL," + "CONTEXT," + "INSTANCE_ID," + "MESSAGE_TYPE";

    factory.setDataSource(getDataSource());
    factory.setFromClause("from COP_AUDIT_TRAIL_EVENT ");

    factory.setSelectClause(selectClause);

    factory.setWhereClause(whereClause);
    factory.setSortKey(sortClause);

    PagingQueryProvider queryProvider = null;
    try {
        queryProvider = (PagingQueryProvider) factory.getObject();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return null;
    }

    String query = queryProvider.generateFirstPageQuery(maxResult);

    // this.getJdbcTemplate().setQueryTimeout(1000);

    long start = System.currentTimeMillis();
    RowMapper<AuditTrailInfo> rowMapper = new RowMapper<AuditTrailInfo>() {

        public AuditTrailInfo mapRow(ResultSet rs, int arg1) throws SQLException {

            return new AuditTrailInfo(rs.getLong("SEQ_ID"), rs.getString("TRANSACTION_ID"),
                    rs.getString("CONVERSATION_ID"), rs.getString("CORRELATION_ID"),
                    rs.getTimestamp("OCCURRENCE").getTime(), rs.getInt("LOGLEVEL"), rs.getString("CONTEXT"),
                    rs.getString("INSTANCE_ID"), rs.getString("MESSAGE_TYPE"));
        }

    };
    List<AuditTrailInfo> res = this.getJdbcTemplate().query(query, rowMapper, args.toArray());

    long end = System.currentTimeMillis();

    logger.info("query took: " + (end - start) + " ms : " + query);

    return res;
}

From source file:org.openregistry.core.service.identifier.TestIdentifierAssigner.java

public void addIdentifierTo(final SorPerson sorPerson, final Person person) {
    final Identifier primaryNetid = findPrimaryIdentifier(person, this.getIdentifierType());
    if (primaryNetid == null) { // don't set if already there
        final Name name = person.getOfficialName();

        final StringBuilder builder = new StringBuilder();

        if (StringUtils.hasText(name.getGiven())) {
            builder.append(name.getGiven().substring(0, 1));
        }/*from   w w  w .  j  a  v  a  2  s.  co  m*/

        if (StringUtils.hasText(name.getMiddle())) {
            builder.append(name.getMiddle().substring(0, 1));
        }

        if (StringUtils.hasText(name.getFamily())) {
            builder.append(name.getFamily().substring(0, 1));
        }

        builder.append(constructNewValue());

        final Identifier identifier = person
                .addIdentifier(referenceRepository.findIdentifierType(getIdentifierType()), builder.toString());
        identifier.setDeleted(false);
        identifier.setPrimary(true);
    }
}