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:org.eurekastreams.server.service.security.persistentlogin.PersistentLoginService.java

/**
 * Override parents version so we can generate our own custom token value
 * and store persistent login information in our repository.
 * @param request The request object.//  w w  w.  ja  v  a 2  s  .  c  o m
 * @param response The response object.
 * @param successfulAuthentication The Authentication object for authenticated user.
 */
public void onLoginSuccess(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication successfulAuthentication) {

    String username = retrieveUserName(successfulAuthentication);

    // If unable to find a username, just abort as
    // TokenBasedRememberMeServices is
    // unable to construct a valid token in this case.
    if (!StringUtils.hasLength(username)) {
        logger.error("Authentication contains empty username. Unable to create persistent login info.");
        return;
    }

    int tokenLifetime = calculateLoginLifetime(request, successfulAuthentication);
    long expiryTime = System.currentTimeMillis() + EXPIRE_TIME * tokenLifetime;

    String signatureValue = makeTokenSignature(expiryTime, username, UUID.randomUUID().toString());

    // store it to repository, this is "non-essential" functionality so
    // swallow any
    // exceptions and log it. If for any reason this doesn't work, abort
    // without
    // exception and don't set cookie
    try {
        PersistentLogin login = new PersistentLogin(username, signatureValue, expiryTime);
        loginRepository.createOrUpdatePersistentLogin(login);
    } catch (Exception e) {
        logger.error("Unable to insert PersistentLogin information to DB for user: " + username + "', expiry: '"
                + new Date(expiryTime) + "'");
        return;
    }

    setCookie(new String[] { username, Long.toString(expiryTime), signatureValue }, tokenLifetime, request,
            response);

    if (logger.isDebugEnabled()) {
        logger.debug(
                "Added remember-me cookie for user '" + username + "', expiry: '" + new Date(expiryTime) + "'");
    }
}

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

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

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

    //      Label lbl = new Label(this, SWT.NONE | SWT.CENTER);
    //      Label lbl = new Label(this, SWT.RIGHT |SWT.WRAP | SWT.BORDER);
    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);/*from   w  w  w  .  jav  a 2 s.c om*/

    int textStyle = SWT.SINGLE | SWT.BORDER | SWT.CENTER;
    text = new Text(this, textStyle);
    text.setEditable(true);
    text.setText("     ");

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

    Label lbUnit = new Label(this, SWT.LEFT);
    lbUnit.setText(StringUtils.hasLength(units) ? units : " ");

    //      text.addVerifyListener(new AmountVerifyKeyListener());

    text.addListener(SWT.DefaultSelection, new Listener() {
        @Override
        public void handleEvent(Event e) {
            System.out.println(e.widget + " - Default selection made");
            valueChanged((Text) e.widget);
        }
    });

    setTextRunnable = new Runnable() {
        @Override
        public void run() {
            int currentLength = text.getText().length();
            String valString = val;
            text.setText(valString);
            int diff = valString.length() - currentLength;
            if (diff > 0 || diff < -3)
                EclipseWidgetUtils.forceLayoutOfTopParent(ScannableComposite.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.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

protected void preparePostProcessor(Element element, ParserContext parserContext) {
    String id = element.getAttribute("id");
    String name = getName(element);
    BeanDefinitionBuilder postProcessor = BeanDefinitionBuilder
            .genericBeanDefinition(ConfigurationBeanPostProcessor.class);
    postProcessor.addConstructorArgValue(name);
    postProcessor.addConstructorArgReference(id);
    Element annotationConfigElement = selectSingleChildElement(element, "annotation-config", true);
    if (annotationConfigElement != null) {
        String marker = annotationConfigElement.getAttribute("marker");
        if (StringUtils.hasLength(marker)) {
            Class<?> theClass = ClassUtils.resolveClassName(marker,
                    Thread.currentThread().getContextClassLoader());
            if (!theClass.isAnnotation()) {
                throw new ConfigurationException(String.format("The class '%s' is not an annotation", marker));
            }//from   w w w.  j av  a 2 s  . co  m
            postProcessor.addPropertyValue("markerAnnotation", theClass);
        }
    }
    parserContext.registerBeanComponent(
            new BeanComponentDefinition(postProcessor.getBeanDefinition(), id + "-postProcessor"));
}

From source file:com.xdtech.core.orm.utils.AssertUtils.java

public static void doesNotContain(String textToSearch, String substring, RuntimeException throwIfAssertFail) {
    if (StringUtils.hasLength(textToSearch) && StringUtils.hasLength(substring)
            && textToSearch.indexOf(substring) != -1) {
        throw throwIfAssertFail;
    }//from  ww w  .  j av a 2  s  .  co m
}

From source file:com.taobao.diamond.server.service.DBPersistService.java

public Page<ConfigInfo> findConfigInfoLike(final int pageNo, final int pageSize, final String dataId,
        final String group) {
    this.jt.setQueryTimeout(QUERY_TIMEOUT);

    PaginationHelper<ConfigInfo> helper = new PaginationHelper<ConfigInfo>();
    String sqlCountRows = "select count(ID) from config_info where ";
    String sqlFetchRows = "select ID,data_id,group_id,content,md5 from config_info where ";
    boolean wasFirst = true;
    if (StringUtils.hasLength(dataId)) {
        sqlCountRows += "data_id like ? ";
        sqlFetchRows += "data_id like ? ";
        wasFirst = false;/*from  w w  w  .  j  ava 2  s .  co m*/
    }
    if (StringUtils.hasLength(group)) {
        if (wasFirst) {
            sqlCountRows += "group_id like ? ";
            sqlFetchRows += "group_id like ? ";
        } else {
            sqlCountRows += "and group_id like ? ";
            sqlFetchRows += "and group_id like ? ";
        }
    }
    Object[] args = null;
    if (StringUtils.hasLength(dataId) && StringUtils.hasLength(group)) {
        args = new Object[2];
        args[0] = generateLikeArgument(dataId);
        args[1] = generateLikeArgument(group);
    } else if (StringUtils.hasLength(dataId)) {
        args = new Object[] { generateLikeArgument(dataId) };
    } else if (StringUtils.hasLength(group)) {
        args = new Object[] { generateLikeArgument(group) };
    }

    return helper.fetchPage(this.jt, sqlCountRows, sqlFetchRows, args, pageNo, pageSize,
            CONFIG_INFO_ROW_MAPPER);
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Convert a name in camelCase to an underscored name in lower case.
 * Any upper case letters are converted to lower case with a preceding underscore.
 * @param name the original name//  w w w.  j a va2 s  .  co m
 * @return the converted name
 * @since 4.2
 * @see #lowerCaseName
 */
protected String underscoreName(String name) {
    if (!StringUtils.hasLength(name)) {
        return "";
    }
    StringBuilder result = new StringBuilder();
    result.append(lowerCaseName(name.substring(0, 1)));
    for (int i = 1; i < name.length(); i++) {
        String s = name.substring(i, i + 1);
        String slc = lowerCaseName(s);
        if (!s.equals(slc)) {
            result.append("_").append(slc);
        } else {
            result.append(s);
        }
    }
    return result.toString();
}

From source file:grails.plugin.springsecurity.web.access.intercept.AnnotationFilterInvocationDefinition.java

protected String createControllerUri(String controllerName, String actionName) {
    if (!StringUtils.hasLength(actionName) || "null".equals(actionName)) {
        actionName = "index";
    }/*from   w  w  w  . j a  v  a  2 s.  c  o m*/
    return (SLASH + controllerName + SLASH + actionName).trim();
}

From source file:com.iana.dver.controller.DverAdminController.java

@RequestMapping(value = "/admin/rejected/filter", produces = "application/json", method = RequestMethod.GET)
public @ResponseBody String filterRejectedDversByScacOrDot(
        @RequestParam(value = "sEcho", required = false, defaultValue = "1") String sEcho,
        @RequestParam(value = "sSearch", required = false) String sSearch,
        @RequestParam(value = "sColumns", required = false) String sColumns,
        @RequestParam(value = "iDisplayStart", required = false, defaultValue = "0") String iDisplayStart,
        @RequestParam(value = "iDisplayLength", required = false, defaultValue = "10") String iDisplayLength,
        @RequestParam(value = "iColumns", required = false, defaultValue = "8") String iColumns,
        @RequestParam(value = "iepDotFilter", required = false, defaultValue = "") String iepDotFilter,
        @RequestParam(value = "mcDotFilter", required = false, defaultValue = "") String mcDotFilter,
        @RequestParam(value = "reportNoFilter", required = false, defaultValue = "") String reportNoFilter) {

    try {//  w w  w .j a va  2s  .c  o m

        Map<String, String> filtermap = new HashMap<String, String>();

        if (StringUtils.hasLength(iepDotFilter)) {
            filtermap.put("iepDotFilter", iepDotFilter + "%");
        }
        if (StringUtils.hasLength(mcDotFilter)) {
            filtermap.put("mcDotFilter", mcDotFilter + "%");
        }
        if (StringUtils.hasLength(reportNoFilter)) {
            filtermap.put("reportNoFilter", reportNoFilter + "%");
        }

        List<DverDetailsVO> rejectedDvers = this.dverDetailsService.getFilteredRejectedDvers(filtermap,
                Integer.parseInt(iDisplayStart), Integer.parseInt(iDisplayLength));

        if (CollectionUtils.isEmpty(rejectedDvers)) {
            rejectedDvers = new ArrayList<DverDetailsVO>();
        }

        int iTotalRecords = rejectedDvers.size();
        int iTotalDisplayRecords = this.dverDetailsService.countFilteredRejectedDvers(filtermap);

        JsonObject jsonResponse = new JsonObject();
        jsonResponse.addProperty("sEcho", sEcho);
        jsonResponse.addProperty("iTotalRecords", iTotalRecords);
        jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
        Gson gson = new Gson();
        jsonResponse.add("aaData", gson.toJsonTree(rejectedDvers));
        return jsonResponse.toString();

    } catch (Exception ex) {
        DVERUtil.sendExceptionEmails("filterRejectedDversByScacOrDot method of DverAdminController \n " + ex);
        logger.error("Error in filterRejectedDversByScacOrDot....." + ex);
        return "error";
    }
}

From source file:com.taobao.diamond.server.service.ConfigService.java

private void checkParameter(String dataId, String group, String content) {
    if (!StringUtils.hasLength(dataId) || StringUtils.containsWhitespace(dataId))
        throw new ConfigServiceException("dataId");

    if (!StringUtils.hasLength(group) || StringUtils.containsWhitespace(group))
        throw new ConfigServiceException("group");

    if (!StringUtils.hasLength(content))
        throw new ConfigServiceException("content");
}

From source file:org.kmnet.com.fw.web.pagination.PaginationInfo.java

/**
 * Remove the delimiter of query string that exists at the head.
 * <p>//from   w ww.  java  2 s. c  o  m
 * Target delimiter is '?' or '&'.
 * </p>
 * @param queryString query string
 * @return query string that removed delimiter at the head.
 * @since 1.0.1
 */
private String removeHeadDelimiterOfQueryString(String queryString) {
    if (!StringUtils.hasLength(queryString)) {
        return queryString;
    }
    if (queryString.startsWith("?") || queryString.startsWith("&")) {
        return queryString.substring(1);
    } else {
        return queryString;
    }
}