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

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

Introduction

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

Prototype

public static String defaultIfBlank(String str, String defaultStr) 

Source Link

Document

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

Usage

From source file:com.cloudbees.plugins.credentials.CredentialsProvider.java

/**
 * A helper method for Groovy Scripting to address use cases such as JENKINS-39317 where all credential stores
 * need to be resaved. As this is a potentially very expensive operation the method has been marked
 * {@link DoNotUse} in order to ensure that no plugin attempts to call this method. If invoking this method
 * from an {@code init.d} Groovy script, ensure that the call is guarded by a marker file such that
 *
 * @throws IOException if things go wrong.
 *///from  w  w  w  . ja  v a2 s  . c  o m
@Restricted(DoNotUse.class) // Do not use from plugins
public static void saveAll() throws IOException {
    LOGGER.entering(CredentialsProvider.class.getName(), "saveAll");
    try {
        final Jenkins jenkins = Jenkins.getActiveInstance();
        jenkins.checkPermission(Jenkins.ADMINISTER);
        LOGGER.log(Level.INFO, "Forced save credentials stores: Requested by {0}",
                StringUtils.defaultIfBlank(Jenkins.getAuthentication().getName(), "anonymous"));
        Timer.get().execute(new Runnable() {
            @Override
            public void run() {
                SecurityContext ctx = ACL.impersonate(ACL.SYSTEM);
                try {
                    if (jenkins.getInitLevel().compareTo(InitMilestone.JOB_LOADED) < 0) {
                        LOGGER.log(Level.INFO,
                                "Forced save credentials stores: Initialization has not completed");
                        while (jenkins.getInitLevel().compareTo(InitMilestone.JOB_LOADED) < 0) {
                            LOGGER.log(Level.INFO, "Forced save credentials stores: Sleeping for 1 second");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                LOGGER.log(Level.WARNING,
                                        "Forced save credentials stores: Aborting due to interrupt", e);
                                return;
                            }
                        }
                        LOGGER.log(Level.INFO, "Forced save credentials stores: Initialization has completed");
                    }
                    LOGGER.log(Level.INFO, "Forced save credentials stores: Processing Jenkins");
                    for (CredentialsStore s : lookupStores(jenkins)) {
                        try {
                            s.save();
                        } catch (IOException e) {
                            LOGGER.log(Level.WARNING, "Forced save credentials stores: Could not save " + s, e);
                        }
                    }
                    LOGGER.log(Level.INFO, "Forced save credentials stores: Processing Items...");
                    int count = 0;
                    for (Item item : jenkins.getAllItems(Item.class)) {
                        count++;
                        if (count % 100 == 0) {
                            LOGGER.log(Level.INFO,
                                    "Forced save credentials stores: Processing Items ({0} processed)", count);
                        }
                        for (CredentialsStore s : lookupStores(item)) {
                            if (item == s.getContext()) {
                                // only save if the store is associated with this context item as otherwise will
                                // have been saved already / later
                                try {
                                    s.save();
                                } catch (IOException e) {
                                    LOGGER.log(Level.WARNING,
                                            "Forced save credentials stores: Could not save " + s, e);
                                }
                            }
                        }
                    }
                    LOGGER.log(Level.INFO, "Forced save credentials stores: Processing Users...");
                    count = 0;
                    for (User user : User.getAll()) {
                        count++;
                        if (count % 100 == 0) {
                            LOGGER.log(Level.INFO,
                                    "Forced save credentials stores: Processing Users ({0} processed)", count);
                        }
                        // HACK ALERT we just want to access the user's stores so we do just enough impersonation
                        // to ensure that User.current() == user
                        // while we could use User.impersonate() that would force a query against the backing
                        // SecurityRealm to revalidate
                        ACL.impersonate(new UsernamePasswordAuthenticationToken(user.getId(), "",
                                new GrantedAuthority[] { SecurityRealm.AUTHENTICATED_AUTHORITY }));
                        for (CredentialsStore s : lookupStores(user)) {
                            if (user == s.getContext()) {
                                // only save if the store is associated with this context item as otherwise will
                                // have been saved already / later
                                try {
                                    s.save();
                                } catch (IOException e) {
                                    LOGGER.log(Level.WARNING,
                                            "Forced save credentials stores: Could not save " + s, e);
                                }
                            }
                        }
                    }
                } finally {
                    LOGGER.log(Level.INFO, "Forced save credentials stores: Completed");
                    SecurityContextHolder.setContext(ctx);
                }
            }
        });
    } finally {
        LOGGER.exiting(CredentialsProvider.class.getName(), "saveAll");
    }
}

From source file:ips1ap101.lib.core.web.app.GestorPaginaActualizacion.java

public String getNombreClaseRecursoMaestroPagina(String nombrePorOmision) {
    String nombreClaseRecurso = getPaginaActualizacion().getContextoPeticion().getNombreClaseRecursoMaestro();
    if (StringUtils.isNotBlank(nombreClaseRecurso)) {
        getPaginaActualizacion().getContextoSesion().setClaseRecursoMaestroPagina(nombreClaseRecurso);
        return nombreClaseRecurso;
    }// w ww  . j  a va  2 s. co m
    nombreClaseRecurso = getPaginaActualizacion().getContextoSesion().getClaseRecursoMaestroPagina();
    return StringUtils.defaultIfBlank(nombreClaseRecurso, StringUtils.trimToEmpty(nombrePorOmision));
}

From source file:ips1ap101.lib.core.web.app.GestorPaginaActualizacion.java

public String getEtiquetaOpcionSeleccionadaListaFuncionAccion() {
    if (designing) {
        return null;
    }/*from  w w w.  ja  v a2 s  . c  om*/
    String label = isAccionMultiFuncion()
            ? STP.getToken(getEtiquetaOpcionSeleccionada(
                    getPaginaActualizacionConAccionMultiple().getListaFuncionAccion1()))
            : null; /* BundleWebui.getString("botonProcesar.text") */
    /**/
    return StringUtils.defaultIfBlank(label, getI18n().getEtiquetaSeleccioneUnaOpcionListaFuncionAccion());
}

From source file:ips1ap101.lib.core.web.app.GestorPaginaActualizacion.java

public String getEtiquetaOpcionSeleccionadaListaFuncionEdicion() {
    if (designing) {
        return null;
    }/*from  w ww.  j av  a2 s.c om*/
    String label = isEdicionMultiFuncion()
            ? STP.getToken(getEtiquetaOpcionSeleccionada(
                    getPaginaActualizacionConEdicionMultiple().getListaFuncionEdicion1()))
            : BundleWebui.getString("botonEditar.text");
    /**/
    return StringUtils.defaultIfBlank(label, getI18n().getEtiquetaSeleccioneUnaOpcionListaFuncionEdicion());
}

From source file:net.ymate.framework.commons.ParamUtils.java

private static void __doAppendParamValue(String _key, Object _v, StringBuilder _paramSB, boolean encode,
        String charset) {/* ww w.jav  a  2 s  . c  om*/
    if (_paramSB.length() > 0) {
        _paramSB.append("&");
    }
    String _valueStr = _v.toString();
    if (encode) {
        try {
            _paramSB.append(_key).append("=")
                    .append(URLEncoder.encode(_valueStr, StringUtils.defaultIfBlank(charset, "UTF-8")));
        } catch (UnsupportedEncodingException e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        }
    } else {
        _paramSB.append(_key).append("=").append(_valueStr);
    }
}

From source file:net.ymate.framework.commons.ParamUtils.java

public static String appendQueryParamValue(String url, Map<String, String> params, boolean encode,
        String charset) {// w  w w.j a va  2  s  . c  o m
    if (params != null && !params.isEmpty()) {
        StringBuilder _paramSB = new StringBuilder(url);
        if (!url.contains("?")) {
            _paramSB.append("?");
        } else {
            _paramSB.append("&");
        }
        for (Map.Entry<String, String> _param : params.entrySet()) {
            if (encode) {
                try {
                    _paramSB.append(_param.getKey()).append("=").append(
                            URLEncoder.encode(_param.getValue(), StringUtils.defaultIfBlank(charset, "UTF-8")))
                            .append("&");
                } catch (UnsupportedEncodingException e) {
                    _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                }
            } else {
                _paramSB.append(_param.getKey()).append("=").append(_param.getValue()).append("&");
            }
        }
        if (_paramSB.length() > 0 && _paramSB.charAt(_paramSB.length() - 1) == '&') {
            _paramSB.setLength(_paramSB.length() - 1);
        }
        return _paramSB.toString();
    }
    return url;
}

From source file:net.ymate.framework.commons.ParamUtils.java

public static Map<String, String> parseQueryParamStr(String paramStr, boolean decode, String charset) {
    // &?/*ww w .  j  a  v  a2 s.  c om*/
    String[] _paramArr = StringUtils.split(paramStr, '&');
    // ??????
    Map<String, String> _returnValue = new HashMap<String, String>(_paramArr.length);
    for (String _param : _paramArr) {
        //=?
        int nPos = _param.indexOf('=');
        //
        int nLen = _param.length();
        //????
        String strKey = _param.substring(0, nPos);
        //
        String strValue = _param.substring(nPos + 1, nLen);
        if (decode) {
            try {
                strValue = URLDecoder.decode(strValue, StringUtils.defaultIfBlank(charset, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                _LOG.warn("", RuntimeUtils.unwrapThrow(e));
            }
        }
        //MAP
        _returnValue.put(strKey, strValue);
    }
    return _returnValue;
}

From source file:net.ymate.framework.commons.ParamUtils.java

public static String buildActionForm(String actionUrl, boolean usePost, boolean encode, boolean enctype,
        String charset, Map<String, String> params) {
    String _charset = StringUtils.defaultIfBlank(charset, "UTF-8");
    StringBuilder _payHtml = new StringBuilder();
    _payHtml.append("<form id=\"_payment_submit\" name=\"_payment_submit\" action=\"").append(actionUrl)
            .append("\" method=\"").append(usePost ? "POST" : "GET").append("\"");
    if (enctype) {
        _payHtml.append("\" enctype=\"application/x-www-form-urlencoded;charset=").append(_charset)
                .append("\"");
    }/*from ww w.  j  a v a 2s.c  o m*/
    _payHtml.append(">");
    //
    for (Map.Entry<String, String> _entry : params.entrySet()) {
        __doAppendHiddenElement(_payHtml, _entry.getKey(), _entry.getValue(), encode, _charset);
    }
    // submit???name
    _payHtml.append("<input type=\"submit\" value=\"doSubmit\" style=\"display:none;\"></form>");
    _payHtml.append("<script>document.forms['_payment_submit'].submit();</script>");
    return _payHtml.toString();
}

From source file:net.ymate.framework.commons.XPathHelper.java

private <T> T __doWrapperValues(Object parentNode, ClassUtils.BeanWrapper<T> _beanWrapper)
        throws XPathExpressionException, IllegalAccessException {
    for (Field _field : _beanWrapper.getFields()) {
        if (_field.isAnnotationPresent(XPathNode.class)) {
            XPathNode _fieldNodeAnno = _field.getAnnotation(XPathNode.class);
            if (_fieldNodeAnno.child()) {
                Object _childNode = StringUtils.isNotBlank(_fieldNodeAnno.value())
                        ? getNode(parentNode, _fieldNodeAnno.value())
                        : parentNode;/*  w ww .ja  v  a  2 s .co  m*/
                if (_childNode != null) {
                    Object _childObject = null;
                    Object _fieldValue = _beanWrapper.getValue(_field);
                    //
                    if (!INodeValueParser.class.equals(_fieldNodeAnno.parser())) {
                        try {
                            INodeValueParser _parser = _fieldNodeAnno.parser().newInstance();
                            _childObject = _parser.parse(this, parentNode, _field.getType(), _fieldValue);
                        } catch (InstantiationException e) {
                            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                        }
                    } else {
                        if (_fieldValue != null) {
                            _childObject = __toObject(_childNode, _fieldValue);
                        } else {
                            _childObject = __toObject(_childNode,
                                    Void.class.equals(_fieldNodeAnno.implClass()) ? _field.getType()
                                            : _fieldNodeAnno.implClass());
                        }
                    }
                    _beanWrapper.setValue(_field, _childObject);
                }
            } else {
                String _value = StringUtils.defaultIfBlank(StringUtils.isNotBlank(_fieldNodeAnno.value())
                        ? getStringValue(parentNode, _fieldNodeAnno.value())
                        : null, StringUtils.trimToNull(_fieldNodeAnno.defaultValue()));
                if (!INodeValueParser.class.equals(_fieldNodeAnno.parser())) {
                    try {
                        INodeValueParser _parser = _fieldNodeAnno.parser().newInstance();
                        _beanWrapper.setValue(_field,
                                BlurObject.bind(_parser.parse(this, parentNode, _field.getType(), _value))
                                        .toObjectValue(_field.getType()));
                    } catch (InstantiationException e) {
                        _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                    }
                } else {
                    _beanWrapper.setValue(_field, BlurObject.bind(_value).toObjectValue(_field.getType()));
                }
            }
        }
    }
    return _beanWrapper.getTargetObject();
}

From source file:net.ymate.framework.core.taglib.bootstrap.AlertTag.java

@Override
protected StringBuilder __doTagStart() {
    StringBuilder _classSB = new StringBuilder(StringUtils.trimToEmpty(this.get_class()))
            .append(" alert alert-").append(StringUtils.defaultIfBlank(style, "warning"));
    if (dismissable) {
        _classSB.append(" alert-dismissable");
    }/* ww  w  .ja  va  2s .  c om*/
    this.set_class(_classSB.toString());
    //
    return super.__doTagStart();
}