Example usage for org.springframework.util StringUtils hasLength

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

Introduction

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

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:com.excilys.ebi.bank.util.Asserts.java

public static void doesNotContain(String textToSearch, String substring, String messagePattern,
        Object... args) {/*from ww  w. j  a  va2  s.  co  m*/
    if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring)
            && textToSearch.indexOf(substring) != -1) {
        throw new IllegalArgumentException(MessageFormatter.arrayFormat(messagePattern, args).getMessage());
    }
}

From source file:com.artivisi.security.service.impl.SpringSecurityServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public List<User> findUsersByUsername(String username) {
    if (!StringUtils.hasLength(username))
        return new ArrayList<User>();

    return sessionFactory.getCurrentSession()
            .createQuery("from User o where lower(o.username) like :username order by o.username")
            .setString("username", "%" + username.toLowerCase() + "%").list();
}

From source file:es.osoco.grails.plugins.otp.access.AnnotationMultipleVoterFilterInvocationDefinition.java

protected String findGrailsUrl(final UrlMappingInfo mapping) {

    String uri = mapping.getURI();
    if (StringUtils.hasLength(uri)) {
        return uri;
    }//from ww  w . j  av a 2  s .com

    String actionName = mapping.getActionName();
    if (!StringUtils.hasLength(actionName)) {
        actionName = "";
    }

    String controllerName = mapping.getControllerName();

    if (isController(controllerName, actionName)) {
        if (!StringUtils.hasLength(actionName) || "null".equals(actionName)) {
            actionName = "index";
        }
        return ("/" + controllerName + "/" + actionName).trim();
    }

    return null;
}

From source file:uk.ac.gda.dls.client.views.MonitorCompositeFactory.java

MonitorComposite(Composite parent, int style, Scannable scannable, String label, final String units,
        Integer decimalPlaces, Integer labelWidth, Integer contentWidth) {
    super(parent, style);
    this.scannable = scannable;
    this.decimalPlaces = decimalPlaces;
    this.labelWidth = labelWidth;
    this.contentWidth = contentWidth;

    if (StringUtils.hasLength(units))
        suffix = " " + units;

    formats = scannable.getOutputFormat();
    GridLayoutFactory.fillDefaults().numColumns(2).applyTo(this);
    GridDataFactory.fillDefaults().applyTo(this);

    Label lbl = new Label(this, SWT.RIGHT | SWT.WRAP);
    lbl.setText(StringUtils.hasLength(label) ? label : scannable.getName());
    GridData labelGridData = new GridData(GridData.HORIZONTAL_ALIGN_END);

    if (labelWidth != null)
        labelGridData.widthHint = labelWidth.intValue();
    lbl.setLayoutData(labelGridData);//w w w  .j a  va 2s  . c o m

    text = new Text(this, SWT.READ_ONLY | SWT.BORDER | SWT.CENTER);
    text.setEditable(false);

    GridData textGridData = new GridData(GridData.FILL_HORIZONTAL);
    textGridData.horizontalAlignment = GridData.HORIZONTAL_ALIGN_BEGINNING;
    if (contentWidth != null)
        textGridData.widthHint = contentWidth.intValue();
    text.setLayoutData(textGridData);

    setTextRunnable = new Runnable() {
        @Override
        public void run() {
            int currentLength = text.getText().length();
            String valPlusUnits = val + suffix;
            text.setText(valPlusUnits);
            int diff = valPlusUnits.length() - currentLength;
            if (diff > 0 || diff < -3)
                EclipseWidgetUtils.forceLayoutOfTopParent(MonitorComposite.this);
        }
    };

    observer = new IObserver() {

        @Override
        public void update(Object source, Object arg) {
            if (arg instanceof ScannablePositionChangeEvent) {
                final ScannablePositionChangeEvent event = (ScannablePositionChangeEvent) arg;
                setVal(event.newPosition.toString());
            } else if (arg instanceof String) {
                setVal((String) arg);
            } else {
                ScannableGetPositionWrapper wrapper = new ScannableGetPositionWrapper(arg, formats);
                setVal(wrapper.getStringFormattedValues()[0]);
            }
        }
    };

    try {
        ScannableGetPositionWrapper wrapper = new ScannableGetPositionWrapper(scannable.getPosition(), formats);
        val = wrapper.getStringFormattedValues()[0];
    } catch (DeviceException e1) {
        val = "Error";
        logger.error("Error getting position for " + scannable.getName(), e1);
    }
    setVal(val);

    scannable.addIObserver(observer);
}

From source file:org.springbyexample.jdbc.core.SqlScriptProcessor.java

/**
 * Initializes SQL scripts./*from www.  j ava  2  s  .  c om*/
 * @throws IOException
 */
public void process() throws IOException {
    if (lSqlScripts != null) {
        for (String sqlScript : lSqlScripts) {
            String sql = null;

            Resource resource = resourceLoader.getResource(sqlScript);

            if (!resource.exists()) {
                sql = sqlScript;
            } else {
                BufferedReader br = null;

                try {
                    if (charset == null) {
                        br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                    } else {
                        br = new BufferedReader(new InputStreamReader(resource.getInputStream(), charset));
                    }

                    StringBuilder sb = new StringBuilder();
                    String line = null;

                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                        sb.append("\n");
                    }

                    sql = sb.toString();
                } finally {
                    try {
                        br.close();
                    } catch (Exception e) {
                    }
                }
            }

            if (StringUtils.hasLength(sql)) {
                logger.debug("Initializing db with given sql");
                // execute sql
                template.execute(sql);
            }
        }
    }
}

From source file:com.github.springtestdbunit.DbUnitTestExecutionListener.java

@Override
public void prepareTestInstance(TestContext testContext) throws Exception {

    if (logger.isDebugEnabled()) {
        logger.debug("Preparing test instance " + testContext.getTestClass() + " for DBUnit");
    }/*from  ww w  .  j  a  v  a 2s.c o m*/

    String databaseConnectionBeanName = null;
    Class<? extends DataSetLoader> dataSetLoaderClass = FlatXmlDataSetLoader.class;
    Class<? extends DatabaseOperationLookup> databaseOperationLookupClass = DefaultDatabaseOperationLookup.class;

    DbUnitConfiguration configuration = testContext.getTestClass().getAnnotation(DbUnitConfiguration.class);
    if (configuration != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Using @DbUnitConfiguration configuration");
        }
        databaseConnectionBeanName = configuration.databaseConnection();
        dataSetLoaderClass = configuration.dataSetLoader();
        databaseOperationLookupClass = configuration.databaseOperationLookup();
    }

    if (!StringUtils.hasLength(databaseConnectionBeanName)) {
        databaseConnectionBeanName = getDatabaseConnectionUsingCommonBeanNames(testContext);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("DBUnit tests will run using databaseConnection \"" + databaseConnectionBeanName
                + "\", datasets will be loaded using " + dataSetLoaderClass);
    }
    prepareDatabaseConnection(testContext, databaseConnectionBeanName);
    prepareDataSetLoader(testContext, dataSetLoaderClass);
    prepareDatabaseOperationLookup(testContext, databaseOperationLookupClass);
}

From source file:org.zilverline.web.SearchDefaultsController.java

/**
 * Method updates an existing SearchService.
 * //from   w w w  .j a  va2 s .c  om
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.validation.BindException)
 */
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws ServletException {
    // get keys and values for BoostFactors
    Map reqMap = request.getParameterMap();
    Iterator iter = reqMap.entrySet().iterator();
    String[] values = new String[reqMap.size()];
    String[] fields = new String[reqMap.size()];
    String prefix = "field_";
    // find corresponding field, value pairs, they have matching numbers as
    // parameter names (field_#,#) (# is a number)
    while (iter.hasNext()) {
        Map.Entry element = (Map.Entry) iter.next();
        String key = (String) element.getKey();
        String value = ((String[]) element.getValue())[0];
        log.debug("Parsing request for: " + key + ", " + value);
        try {
            if (key.startsWith(prefix)) {
                // this is a field named field_#
                String indexStr = key.substring(prefix.length());
                int index = Integer.parseInt(indexStr);
                log.debug("Adding " + value + " to fields[" + index + "]");
                fields[index] = value;
            } else {
                // this could be a value named #
                int index = Integer.parseInt(key);
                log.debug("Adding " + value + " to values[" + index + "]");
                values[index] = value;
            }
        } catch (NumberFormatException e) {
            // not an extractor related requestParameter
            log.debug("Skipping " + key + ", " + value);
        }
    }
    // add the key value pairs to Map, if field and value contains value
    Map props = new Properties();
    for (int i = 0; i < fields.length; i++) {
        if (StringUtils.hasLength(fields[i]) && StringUtils.hasLength(values[i])) {
            log.debug("Adding " + fields[i] + "=" + values[i] + " to map");
            props.put(fields[i], values[i]);
            // validate the value
            try {
                float f = Float.parseFloat(values[i]);
            } catch (NumberFormatException e) {
                log.debug("value must be a float: " + values[i]);
                errors.rejectValue("factors", "error.notapositivenumber", null, "must be a float.");
                // TODO this is not great, and it does not show error.
                // OnBindAndValidate?
                return new ModelAndView(getSuccessView());
            }

        } else {
            log.debug("Skipping (remove) " + fields[i] + "=" + values[i] + " from map");
        }
    }
    if (service.getFactors() != null) {
        service.getFactors().setFactors(props);
    } else {
        // TODO: this is funny,and should not occur, prevent this from happening somewhere else
        log.warn("SearchService should have Boostfactors, creating new");
        service.setFactors(new BoostFactor());
        service.getFactors().setFactors(props);
    }

    try {
        service.store();
    } catch (SearchException e) {
        throw new ServletException("Error storing new Search Defaults", e);
    }
    return new ModelAndView(getSuccessView());
}

From source file:org.vaadin.spring.security.shared.AbstractVaadinAuthenticationTargetUrlRequestHandler.java

/**
 * Builds the target URL according to the logic defined in the main class Javadoc.
 *///from  w w w. ja v a 2s  .c om
protected String determineTargetUrl(HttpServletRequest request, HttpServletResponse response) {
    if (isAlwaysUseDefaultTargetUrl()) {
        return defaultTargetUrl;
    }

    // Check for the parameter and use that if available
    String targetUrl = null;

    if (targetUrlParameter != null) {
        targetUrl = request.getParameter(targetUrlParameter);

        if (StringUtils.hasText(targetUrl)) {
            logger.debug("Found targetUrlParameter in request: " + targetUrl);

            return targetUrl;
        }
    }

    if (useReferer && !StringUtils.hasLength(targetUrl)) {
        targetUrl = request.getHeader("Referer");
        logger.debug("Using Referer header: " + targetUrl);
    }

    if (!StringUtils.hasText(targetUrl)) {
        targetUrl = defaultTargetUrl;
        logger.debug("Using default Url: " + targetUrl);
    }

    return targetUrl;
}

From source file:org.codehaus.groovy.grails.plugins.spring.ws.ReloadablePayloadRootQNameEndpointMapping.java

/**
 * Lookup an endpoint for the given message. The extraction of the endpoint key is delegated to the concrete
 * subclass.//from   w w w.  j  a  va  2s . co  m
 *
 * @return the looked up endpoint, or <code>null</code>
 */
protected final Object getEndpointInternal(MessageContext messageContext) throws Exception {
    String key = getLookupKeyForMessage(messageContext);
    if (!StringUtils.hasLength(key)) {
        return null;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Looking up endpoint for [" + key + "]");
    }
    return lookupEndpoint(key);
}