Example usage for org.apache.commons.lang StringUtils defaultIfEmpty

List of usage examples for org.apache.commons.lang StringUtils defaultIfEmpty

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils defaultIfEmpty.

Prototype

public static String defaultIfEmpty(String str, String defaultStr) 

Source Link

Document

Returns either the passed in String, or if the String is empty or null, the value of defaultStr.

Usage

From source file:net.ymate.platform.plugin.util.PluginUtils.java

/**
 * @param cfgFile//from w w w . j  a va 2 s  .  c om
 * @param plugin
 * @return ????
 */
public static File getResourceFile(String cfgFile, IPlugin plugin) {
    if (plugin != null) {
        // ?
        String _path = StringUtils.defaultIfEmpty(plugin.getPluginMeta().getPath(),
                plugin.getPluginFactory().getPluginConfig().getPluginHomePath());
        if (StringUtils.isNotBlank(_path)) {
            File _result = new File(new File(_path, StringUtils
                    .defaultIfEmpty(plugin.getPluginMeta().getAlias(), plugin.getPluginMeta().getId())),
                    cfgFile);
            if (_result.exists() && _result.isAbsolute() && _result.canRead()) {
                return _result;
            }
        }
        // ??
        URL _targetFileURL = ResourceUtils.getResource(cfgFile, plugin.getClass());
        if (_targetFileURL != null) {
            return FileUtils.toFile(_targetFileURL);
        }
    }
    return null;
}

From source file:net.ymate.platform.validation.AbstractValidator.java

/**
 * @param context ?//from   ww w.j  a va2 s.c  om
 * @param message ?
 * @param replaceTexts ????
 * @return ??I18N???
 */
protected String doMessageResult(IValidateContext context, String message, String... replaceTexts) {
    String _returnValue = context.getMessage();
    if (StringUtils.isBlank(_returnValue)) {
        _returnValue = StringUtils.defaultIfEmpty(I18N.formatMessage(YMP.__LSTRING_FILE, null, null, message),
                message);
    }
    if (StringUtils.isNotBlank(_returnValue) && replaceTexts != null && replaceTexts.length > 0) {
        ExpressionUtils _exp = ExpressionUtils.bind(_returnValue);
        for (int _idx = 0; _idx < replaceTexts.length; _idx++) {
            _exp.set(_idx + "", replaceTexts[_idx]);
        }
        _returnValue = _exp.getResult();
    } else {
        _returnValue = I18N.formatMessage(YMP.__LSTRING_FILE, null, null, "ymp.validation.default_message");
    }
    return _returnValue;
}

From source file:net.ymate.platform.validation.impl.CompareValidator.java

@Override
protected String onValidate(IValidateContext context) {
    if (doParamsLengthCheck(context, 1)) {
        if (isString(context.getFieldValue().getClass())) {
            String _value = (String) context.getFieldValue();
            if (StringUtils.isNotBlank(_value)) {
                Map<String, String> _params = getParamMaps(context);
                String _cond = StringUtils.defaultIfEmpty(_params.get("cond"), "equals");
                String _field = _params.get("field");
                if (_field == null || context.getFieldValue(_field) == null) {
                    throw new IllegalArgumentException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                            "ymp.validation.validator_parameter_invalid"));
                }/*  w  w w.ja v  a 2s  .  c o  m*/
                if (_cond.equals("equals")) {
                    if (!_value.equals(context.getFieldValue(_field))) {
                        return doMessageResult(context, "ymp.validation.compare");
                    }
                } else {
                    throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                            "ymp.validation.unsupport_cond_op"));
                }
            }
        } else {
            throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                    "ymp.validation.unsupport_non_string_cond_op"));
        }
    } else {
        throw new IllegalArgumentException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                "ymp.validation.validator_parameter_invalid"));
    }
    return onValidateNull(context);
}

From source file:net.ymate.platform.validation.impl.NumericValidator.java

@Override
protected String onValidate(IValidateContext context) {
    if (isString(context.getFieldValue().getClass())) {
        String _value = (String) context.getFieldValue();
        if (doParamsLengthCheck(context, 0) && StringUtils.isNotBlank(_value)) {
            Map<String, String> _params = getParamMaps(context);
            String _type = StringUtils.defaultIfEmpty(_params.get("type"), "int");
            if (_type.equalsIgnoreCase("int")) {
                // ?
                if (!_value.matches("^-?\\d+$")) {
                    return doMessageResult(context, getResultMessageI18nStr(context, false, false, 0, 0));
                }//w  w  w.ja  v  a 2s. c o  m
            } else if (_type.equalsIgnoreCase("float")) {
                // ?
                if (!_value.matches("^(-?\\d+)(\\.\\d+)?$")) {
                    return doMessageResult(context, getResultMessageI18nStr(context, false, false, 0, 0));
                }
            } else {
                throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                        "ymp.validation.unsupport_parameter_type_op"));
            }
            // ???
            boolean _hasMin = _params.containsKey("min");
            boolean _hasMax = _params.containsKey("max");
            int _min = 0;
            int _max = 0;
            if (_hasMin) {
                _min = Integer.parseInt(_params.get("min"));
                if (_min <= 0) {
                    _hasMin = false;
                }
            }
            if (_hasMax) {
                _max = Integer.parseInt(_params.get("max"));
                if (_max <= 0 || (_hasMin && _max < _min)) {
                    _hasMax = false;
                }
            }
            if (_hasMin || _hasMax) {
                double _numValue = Double.parseDouble(_value);
                if (_hasMax) {
                    if (_numValue <= _max) {
                        if (_hasMin) {
                            if (_numValue >= _min) {
                                return VALIDATE_SUCCESS;
                            }
                        } else {
                            return VALIDATE_SUCCESS;
                        }
                    }
                } else if (_hasMin) {
                    if (_numValue >= _min) {
                        return VALIDATE_SUCCESS;
                    }
                }
                return doMessageResult(context, getResultMessageI18nStr(context, _hasMin, _hasMax, _min, _max),
                        _min + "", _max + "");
            }
        }
    } else {
        throw new ValidationException(I18N.formatMessage(YMP.__LSTRING_FILE, null, null,
                "ymp.validation.unsupport_non_string_cond_op"));
    }
    return onValidateNull(context);
}

From source file:net.ymate.platform.validation.Validates.java

/**
 * @param targetClass ?//  www  .  j  a  va2  s. c o m
 * @return ??
 */
public static PairObject<Validation, Map<String, ValidateRule[]>> loadValidateRule(Class<?> targetClass) {
    Map<String, ValidateRule[]> _returnValue = null;
    Validation _validation = targetClass.getAnnotation(Validation.class);
    if (_validation != null) {
        _returnValue = new HashMap<String, ValidateRule[]>();
        List<PairObject<Field, Validate>> _fieldAnnotations = ClassUtils.getFieldAnnotations(targetClass,
                Validate.class, false);
        for (PairObject<Field, Validate> _fieldAnno : _fieldAnnotations) {
            if (_fieldAnno.getValue().isModel() && _fieldAnno.getValue().value().length > 0) {
                Map<String, ValidateRule[]> _modelVMap = loadValidateRule(_fieldAnno.getKey().getType())
                        .getValue();
                if (_modelVMap != null) {
                    _returnValue.putAll(_modelVMap);
                }
            } else {
                _returnValue.put(
                        StringUtils.defaultIfEmpty(_fieldAnno.getValue().name(), _fieldAnno.getKey().getName()),
                        _fieldAnno.getValue().value());
            }
        }
    }
    return new PairObject<Validation, Map<String, ValidateRule[]>>(_validation, _returnValue);
}

From source file:net.ymate.platform.validation.Validates.java

/**
 * @param targetMethod ?/*w  ww. j  a v  a 2s  .  co  m*/
 * @param fieldNames ????
 * @return ??
 */
public static PairObject<Validation, Map<String, ValidateRule[]>> loadValidateRule(Method targetMethod,
        String[] fieldNames) {
    Map<String, ValidateRule[]> _returnValue = null;
    Validation _validation = targetMethod.getAnnotation(Validation.class);
    if (_validation != null) {
        _returnValue = new HashMap<String, ValidateRule[]>();
        Annotation[][] _paramAnnotations = targetMethod.getParameterAnnotations();
        for (int _idx = 0; _idx < targetMethod.getParameterTypes().length; _idx++) {
            Annotation[] _annotations = _paramAnnotations[_idx];
            for (Annotation _annotation : _annotations) {
                if (_annotation instanceof Validate) {
                    Validate _validate = (Validate) _annotation;
                    if (_validate.isModel()) {
                        Map<String, ValidateRule[]> _modelVMap = loadValidateRule(
                                targetMethod.getParameterTypes()[_idx]).getValue();
                        if (_modelVMap != null) {
                            _returnValue.putAll(_modelVMap);
                        }
                    } else {
                        _returnValue.put(StringUtils.defaultIfEmpty(_validate.name(), fieldNames[_idx]),
                                _validate.value());
                    }
                    break;
                }
            }
        }
    }
    return new PairObject<Validation, Map<String, ValidateRule[]>>(_validation, _returnValue);
}

From source file:net.ymate.platform.webmvc.view.impl.JsonView.java

/**
 * @param callback ??/* w  w  w  . j  a va 2  s . c o m*/
 * @return JSONP????callbackcallback???
 */
public JsonView withJsonCallback(String callback) {
    __jsonCallback = StringUtils.defaultIfEmpty(callback, null);
    return this;
}

From source file:nl.clockwork.mule.ebms.service.stub.enricher.XMLToEbMSAttachmentEnricher.java

@Override
public Object transform(final MuleMessage message, String outputEncoding) throws TransformerException {
    try {/*w  w  w.j  av  a  2 s. co m*/
        String fileName = message.getStringProperty("originalFilename", "message.xml");
        EbMSAttachment attachment = new EbMSAttachment(fileName,
                StringUtils.defaultIfEmpty(Utils.getMimeType(fileName), "application/octet-stream"),
                ((String) message.getPayload()).getBytes()); //application/xml
        message.setPayload(Arrays.asList(attachment));
        return message;
    } catch (IOException e) {
        throw new TransformerException(this, e);
    }
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandler.java

/**
 * Log a successful transfer//  ww w  . j  a v a 2s . com
 */
public void logTransfer(Transfer transfer) {
    final Logger logger = getTransactionLogger();
    final Level detailed = TransactionLevel.DETAILED.getLevel();
    final Level normal = TransactionLevel.NORMAL.getLevel();
    final boolean detailedLoggable = logger.isLoggable(detailed);
    final boolean normalLoggable = logger.isLoggable(normal);
    final boolean willLog = detailedLoggable || normalLoggable;
    // Generate log if, at least, normal level is enabled
    if (willLog) {
        transfer = fetchService.fetch(transfer, RelationshipHelper.nested(Transfer.Relationships.FROM,
                Account.Relationships.TYPE, AccountType.Relationships.CURRENCY), Transfer.Relationships.TO);
        Level level;
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final UnitsConverter unitsConverter = localSettings
                .getUnitsConverter(transfer.getFrom().getType().getCurrency().getPattern());
        String message;
        Object[] args;
        // Get the specific level arguments
        if (detailedLoggable) {
            final TransferType type = transfer.getType();
            level = detailed;
            message = "id: %s, date: %s, type: %s (%s), amount: %s, from: %s, to: %s, by: %s, tx#: %s, description: %s";
            final Element by = transfer.getBy();
            args = new Object[] { transfer.getId(),
                    localSettings.getDateTimeConverter().toString(transfer.getDate()), type.getId(),
                    type.getName(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName(),
                    by == null ? "<null>" : by.getUsername(),
                    StringUtils.defaultIfEmpty(transfer.getTransactionNumber(), "<null>"),
                    StringUtils.replace(transfer.getDescription(), "\n", "\\n") };
        } else {
            level = normal;
            message = "id: %s, amount: %s, from: %s, to: %s";
            args = new Object[] { transfer.getId(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName() };
        }
        try {
            logger.log(level, String.format(message, args));
        } catch (final Exception e) {
            System.out.println(
                    "Error generating log on " + settingsService.getLogSettings().getTransactionFile());
        }
    }
}

From source file:nl.strohalm.cyclos.utils.logging.LoggingHandlerImpl.java

/**
 * Log a successful transfer//  w  w  w .ja  v  a2s  .co  m
 */
@Override
public void logTransfer(final Transfer transfer) {
    final Logger logger = getTransactionLogger();
    final Level detailed = TransactionLevel.DETAILED.getLevel();
    final Level normal = TransactionLevel.NORMAL.getLevel();
    final boolean detailedLoggable = logger.isLoggable(detailed);
    final boolean normalLoggable = logger.isLoggable(normal);
    final boolean willLog = detailedLoggable || normalLoggable;
    // Generate log if, at least, normal level is enabled
    if (willLog) {
        // transfer = fetchService.fetch(transfer, RelationshipHelper.nested(Payment.Relationships.FROM, Account.Relationships.TYPE,
        // AccountType.Relationships.CURRENCY), Payment.Relationships.TO);
        Level level;
        final LocalSettings localSettings = settingsService.getLocalSettings();
        final UnitsConverter unitsConverter = localSettings
                .getUnitsConverter(transfer.getFrom().getType().getCurrency().getPattern());
        String message;
        Object[] args;
        // Get the specific level arguments
        String loggedUser = LoggedUser.hasUser() ? LoggedUser.user().getUsername() : "<no logged user>";
        if (detailedLoggable) {
            final TransferType type = transfer.getType();
            level = detailed;
            message = "logged user: %s, id: %s, date: %s, type: %s (%s), amount: %s, from: %s, to: %s, by: %s, tx#: %s, description: %s";
            final Element by = transfer.getBy();
            args = new Object[] { loggedUser, transfer.getId(),
                    localSettings.getDateTimeConverter().toString(transfer.getDate()), type.getId(),
                    type.getName(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName(),
                    by == null ? "<null>" : by.getUsername(),
                    StringUtils.defaultIfEmpty(transfer.getTransactionNumber(), "<null>"),
                    StringUtils.replace(transfer.getDescription(), "\n", "\\n") };
        } else {
            level = normal;
            message = "logged user: %s, id: %s, amount: %s, from: %s, to: %s";
            args = new Object[] { loggedUser, transfer.getId(), unitsConverter.toString(transfer.getAmount()),
                    transfer.getFrom().getOwnerName(), transfer.getTo().getOwnerName() };
        }
        try {
            logger.log(level, String.format(message, args));
        } catch (final Exception e) {
            System.out.println(
                    "Error generating log on " + settingsService.getLogSettings().getTransactionFile());
        }
    }
}