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.kurento.rabbitmq.RabbitTemplate.java

protected Message doSendAndReceiveWithFixed(final String exchange, final String routingKey,
        final Message message) {
    return this.execute(new ChannelCallback<Message>() {

        @Override//w ww  . j  ava 2s .  co  m
        public Message doInRabbit(Channel channel) throws Exception {
            final PendingReply pendingReply = new PendingReply();

            byte[] messageTagBytes = message.getMessageProperties().getCorrelationId();

            String messageTag;
            if (messageTagBytes != null) {
                messageTag = new String(messageTagBytes);
            } else {
                messageTag = UUID.randomUUID().toString();
            }

            RabbitTemplate.this.replyHolder.put(messageTag, pendingReply);
            // Save any existing replyTo and correlation data
            String savedReplyTo = message.getMessageProperties().getReplyTo();
            pendingReply.setSavedReplyTo(savedReplyTo);
            if (StringUtils.hasLength(savedReplyTo) && logger.isDebugEnabled()) {
                logger.debug("Replacing replyTo header:" + savedReplyTo
                        + " in favor of template's configured reply-queue:"
                        + RabbitTemplate.this.replyQueue.getName());
            }
            message.getMessageProperties().setReplyTo(RabbitTemplate.this.replyQueue.getName());
            String savedCorrelation = null;
            if (RabbitTemplate.this.correlationKey == null) { // using
                // standard
                // correlationId
                // property
                byte[] correlationId = message.getMessageProperties().getCorrelationId();
                if (correlationId != null) {
                    savedCorrelation = new String(correlationId, RabbitTemplate.this.encoding);
                }
            } else {
                savedCorrelation = (String) message.getMessageProperties().getHeaders()
                        .get(RabbitTemplate.this.correlationKey);
            }
            pendingReply.setSavedCorrelation(savedCorrelation);
            if (RabbitTemplate.this.correlationKey == null) { // using
                // standard
                // correlationId
                // property
                message.getMessageProperties()
                        .setCorrelationId(messageTag.getBytes(RabbitTemplate.this.encoding));
            } else {
                message.getMessageProperties().setHeader(RabbitTemplate.this.correlationKey, messageTag);
            }

            if (logger.isDebugEnabled()) {
                logger.debug("Sending message with tag " + messageTag);
            }
            doSend(channel, exchange, routingKey, message, null);
            LinkedBlockingQueue<Message> replyHandoff = pendingReply.getQueue();
            Message reply = (replyTimeout < 0) ? replyHandoff.take()
                    : replyHandoff.poll(replyTimeout, TimeUnit.MILLISECONDS);
            RabbitTemplate.this.replyHolder.remove(messageTag);
            return reply;
        }
    });
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Called while saving a SyncRecord to allow for manipulating what is stored. The impl of this
 * method transforms the {@link PersonAttribute#getValue()} and {@link Obs#getVoidReason()}
 * methods to not reference primary keys. (Instead the uuid is referenced and then dereferenced
 * before being saved). If no transformation is to take place, the data is returned as given.
 *
 * @param item the serialized sync item associated with this record
 * @param entity the OpenmrsObject containing the property
 * @param property the property name//from w  ww . j  a  va  2 s  . co  m
 * @param data the current value for the
 * @return the transformed (or unchanged) data to save in the SyncRecord
 */
public String transformItemForSyncRecord(Item item, OpenmrsObject entity, String property, String data) {
    // data will not be null here, so NPE checks are not needed

    if (entity instanceof PersonAttribute && "value".equals(property)) {
        PersonAttribute attr = (PersonAttribute) entity;
        // use PersonAttributeType.format to get the uuid
        if (attr.getAttributeType() == null)
            throw new SyncException("Unable to find person attr type on attr with uuid: " + entity.getUuid());
        String className = attr.getAttributeType().getFormat();
        try {
            Class c = Context.loadClass(className);
            item.setAttribute("type", className);

            // An empty string represents an empty value. Return it as the UUID does not exist.
            if ((data.trim()).isEmpty())
                return data;

            // only convert to uuid if this is an OpenMrs object
            // otherwise, we are just storing a simple String or Integer
            // value
            if (OpenmrsObject.class.isAssignableFrom(c)) {
                String valueObjectUuid = fetchUuid(c, Integer.valueOf(data));
                return valueObjectUuid;
            }
        } catch (Throwable t) {
            log.warn("Unable to get class of type: " + className + " for sync'ing attribute.value column", t);
        }
    } else if (entity instanceof PersonAttributeType && "foreignKey".equals(property)) {
        if (StringUtils.hasLength(data)) {
            PersonAttributeType attrType = (PersonAttributeType) entity;
            String className = attrType.getFormat();
            try {
                Class c = Context.loadClass(className);
                String foreignKeyObjectUuid = fetchUuid(c, Integer.valueOf(data));

                // set the class name on this to be the uuid-ized type
                // instead of java.lang.Integer.
                // the SyncUtil.valForField method will handle changing this
                // back to an integer
                item.setAttribute("type", className);
                return foreignKeyObjectUuid;
            } catch (Throwable t) {
                log.warn("Unable to get class of type: " + className + " for sync'ing foreignKey column", t);
            }
        }
    } else if (entity instanceof Obs && "voidReason".equals(property)) {
        if (data.contains("(new obsId: ")) {
            // rip out the obs id and replace it with a uuid
            String voidReason = String.copyValueOf(data.toCharArray()); // copy
            // the
            // string
            // so
            // that
            // we're
            // operating
            // on
            // a
            // new
            // object
            int start = voidReason.lastIndexOf(" ") + 1;
            int end = voidReason.length() - 1;
            String obsId = voidReason.substring(start, end);
            try {
                String newObsUuid = fetchUuid(Obs.class, Integer.valueOf(obsId));
                return data.substring(0, data.lastIndexOf(" ")) + " " + newObsUuid + ")";
            } catch (Exception e) {
                log.trace("unable to get uuid from obs pk: " + obsId, e);
            }
        }
    } else if (entity instanceof Cohort && "memberIds".equals(property)) {
        // convert integer patient ids to uuids
        try {
            item.setAttribute("type", "java.util.Set<org.openmrs.Patient>");
            StringBuilder sb = new StringBuilder();

            data = data.replaceFirst("\\[", "").replaceFirst("\\]", "");

            sb.append("[");
            String[] fieldVals = data.split(",");
            for (int x = 0; x < fieldVals.length; x++) {
                if (x >= 1)
                    sb.append(", ");

                String eachFieldVal = fieldVals[x].trim(); // take out whitespace
                String uuid = fetchUuid(Patient.class, Integer.valueOf(eachFieldVal));
                sb.append(uuid);

            }

            sb.append("]");

            return sb.toString();

        } catch (Throwable t) {
            log.warn("Unable to get Patient for sync'ing cohort.memberIds property", t);
        }

    }

    return data;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

static String trimToNull(String str) {
    String trimmedStr = StringUtils.trimWhitespace(str);
    if (StringUtils.hasLength(trimmedStr)) {
        return trimmedStr;
    }/*from w w  w  .jav  a 2 s . c o  m*/
    return null;
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java

@Test
public void testMapAccessWithTypeConversion() {
    IndexedTestBean bean = new IndexedTestBean();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(bean);
    bw.registerCustomEditor(TestBean.class, new PropertyEditorSupport() {
        @Override/*from   w w  w .  ja v  a 2 s  .co m*/
        public void setAsText(String text) throws IllegalArgumentException {
            if (!StringUtils.hasLength(text)) {
                throw new IllegalArgumentException();
            }
            setValue(new TestBean(text));
        }
    });

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("map[key1]", "rod");
    pvs.add("map[key2]", "rob");
    bw.setPropertyValues(pvs);
    assertEquals("rod", ((TestBean) bean.getMap().get("key1")).getName());
    assertEquals("rob", ((TestBean) bean.getMap().get("key2")).getName());

    pvs = new MutablePropertyValues();
    pvs.add("map[key1]", "rod");
    pvs.add("map[key2]", "");
    try {
        bw.setPropertyValues(pvs);
        fail("Should have thrown TypeMismatchException");
    } catch (PropertyBatchUpdateException ex) {
        PropertyAccessException pae = ex.getPropertyAccessException("map[key2]");
        assertTrue(pae instanceof TypeMismatchException);
    }
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java

@Test
public void testMapAccessWithUnmodifiableMap() {
    IndexedTestBean bean = new IndexedTestBean();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(bean);
    bw.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() {
        @Override/*  w w w.ja va 2  s.com*/
        public void setAsText(String text) throws IllegalArgumentException {
            if (!StringUtils.hasLength(text)) {
                throw new IllegalArgumentException();
            }
            setValue(new TestBean(text));
        }
    });

    Map<Integer, String> inputMap = new HashMap<Integer, String>();
    inputMap.put(new Integer(1), "rod");
    inputMap.put(new Integer(2), "rob");
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("map", Collections.unmodifiableMap(inputMap));
    bw.setPropertyValues(pvs);
    assertEquals("rod", ((TestBean) bean.getMap().get(new Integer(1))).getName());
    assertEquals("rob", ((TestBean) bean.getMap().get(new Integer(2))).getName());
}

From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java

@Test
public void testMapAccessWithCustomUnmodifiableMap() {
    IndexedTestBean bean = new IndexedTestBean();
    BeanWrapper bw = new JuffrouSpringBeanWrapper(bean);
    bw.registerCustomEditor(TestBean.class, "map", new PropertyEditorSupport() {
        @Override//from   w w w .j  ava 2 s .  com
        public void setAsText(String text) throws IllegalArgumentException {
            if (!StringUtils.hasLength(text)) {
                throw new IllegalArgumentException();
            }
            setValue(new TestBean(text));
        }
    });

    Map<Object, Object> inputMap = new HashMap<Object, Object>();
    inputMap.put(new Integer(1), "rod");
    inputMap.put(new Integer(2), "rob");
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("map", new ReadOnlyMap(inputMap));
    bw.setPropertyValues(pvs);
    assertEquals("rod", ((TestBean) bean.getMap().get(new Integer(1))).getName());
    assertEquals("rob", ((TestBean) bean.getMap().get(new Integer(2))).getName());
}

From source file:com.lm.lic.manager.util.GenUtil.java

/**
 * @param str//from  w  ww.  jav a 2  s .  c o m
 * @return
 */
public static final String replaceWithEmptyIfNull(String str) {
    str = StringUtils.hasLength(str) ? str : EMPTY;
    return str;
}

From source file:com.vmware.appfactory.common.base.AbstractController.java

/**
 * Apply Etag caching to the request. In the request header,
 * if the 'If-None-Match' field is either empty or does not match
 * with the new token; it then set current date in the 'Last-Modified'
 * field. Otherwise, it sends 304 code back in the response.
 *
 * @param request - a HttpServletRequest.
 * @param response - a HttpServletResponse.
 * @param newToken - a new token to be set in the response's Etag header.
 * @return it always returns previous token from the request's
 * 'If-None-Match' header./*w w w  . j a va 2 s  .  c om*/
 * @throws IOException if any error raised while setting
 * Etag caching related Http headers.
 */
protected String applyETagCache(HttpServletRequest request, HttpServletResponse response, String newToken,
        boolean setExpires) throws IOException {
    if (!StringUtils.hasLength(newToken)) {
        throw new IllegalArgumentException("Invalid newToken - " + newToken);
    }

    // Get the current date/time
    final Calendar cal = Calendar.getInstance();
    cal.set(Calendar.MILLISECOND, 0);
    final Date lastModified = cal.getTime();

    response.setHeader("Pragma", "cache");
    response.setHeader("Cache-Control", "public, must-revalidate");

    // Set the Expires and Cache-Control: max-age headers to 1 year in the future
    if (setExpires) {
        // Get the date/time 1 year from now
        cal.add(Calendar.YEAR, 1);
        final Date expires = cal.getTime();

        response.addHeader("Cache-Control", "max-age=3153600");
        response.setDateHeader("Expires", expires.getTime());
    }

    // Always store new token in the ETag header.
    response.setHeader("ETag", newToken);
    String previousToken = request.getHeader("If-None-Match");

    if (newToken.equals(previousToken)) {
        response.sendError(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("Last-Modified", request.getHeader("If-Modified-Since"));
    } else {
        response.setDateHeader("Last-Modified", lastModified.getTime());
    }
    return previousToken;
}

From source file:com.vmware.appfactory.datastore.DsDatastoreCifs.java

/**
 * Get a URL path to the root of the datastore.
 * TODO: This is somewhat bogus. Try not to use it.
 *
 * @return/*from   w  w w  .j a v a 2s.c  om*/
 */
@Deprecated
public String getBaseUrl(String scheme, boolean embedAuth) {
    /* We need at least a server or a path */
    if (!StringUtils.hasLength(getServer()) && !StringUtils.hasLength(getServerPath())) {
        return null;
    }

    /* Start with URL scheme */
    StringBuilder sb = new StringBuilder(scheme + "://");

    /* Optional domain */
    if (StringUtils.hasLength(getDomain())) {
        sb.append(getDomain()).append(";");
    }

    /* Insert 'user:pass@' if needed */
    if (embedAuth && requiresAuth()) {
        try {
            String pass = URLEncoder.encode(getPassword(), "UTF-8");

            sb.append(getUsername());
            sb.append(":");
            if (StringUtils.hasLength(pass)) {
                sb.append(pass);
            }
            sb.append("@");
        } catch (UnsupportedEncodingException ex) {
            /* Should not happen, but just in case */
            _log.error("Failed to embed auth into datastore URL", ex);
        }
    }

    /* Server and port */
    sb.append(getServer());
    if (getPort() > 0) {
        sb.append(":").append(getPort());
    }

    /* Share path */
    String share = StringUtils.hasLength(getShare()) ? getShare().replace("\\", DsUtil.FILE_SEPARATOR) : "";
    sb.append(buildPath("", share));

    return sb.toString();
}