Java Code Examples for org.apache.commons.lang.StringUtils#defaultIfEmpty()

The following examples show how to use org.apache.commons.lang.StringUtils#defaultIfEmpty() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
public SolrQuery convert(SOURCE request) {
  SolrQuery solrQuery = new SolrQuery();
  String unit = StringUtils.defaultIfEmpty(request.getUnit(), "+1HOUR");
  solrQuery.setQuery("*:*");
  solrQuery.setFacet(true);
  solrQuery.addFacetPivotField("{!range=r1}" + getTypeFieldName());
  solrQuery.setFacetMinCount(1);
  solrQuery.setFacetLimit(-1);
  solrQuery.setFacetSort(LogSearchConstants.FACET_INDEX);
  solrQuery.add("facet.range", "{!tag=r1}" + getDateFieldName());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.start"), request.getFrom());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.end"), request.getTo());
  solrQuery.add(String.format(Locale.ROOT, "f.%s.%s", getDateFieldName(), "facet.range.gap"), unit);
  solrQuery.remove("sort");
  solrQuery.setRows(0);
  solrQuery.setStart(0);
  return solrQuery;
}
 
Example 2
public GerritApiBuilder stepContext(StepContext context)
    throws URISyntaxException, IOException, InterruptedException {
  EnvVars envVars = context.get(EnvVars.class);
  logger(context.get(TaskListener.class).getLogger());
  if (StringUtils.isNotEmpty(envVars.get("GERRIT_API_URL"))) {
    gerritApiUrl(envVars.get("GERRIT_API_URL"));
  } else if (StringUtils.isNotEmpty(envVars.get("GERRIT_CHANGE_URL"))) {
    gerritApiUrl(new GerritURI(new URIish(envVars.get("GERRIT_CHANGE_URL"))).getApiURI());
  }
  insecureHttps(Boolean.parseBoolean(envVars.get("GERRIT_API_INSECURE_HTTPS")));
  String credentialsId = StringUtils.defaultIfEmpty(envVars.get("GERRIT_CREDENTIALS_ID"), null);
  if (credentialsId != null) {
    credentials(
        CredentialsProvider.findCredentialById(
            credentialsId, StandardUsernamePasswordCredentials.class, context.get(Run.class)));
  }
  return this;
}
 
Example 3
@Before
public void setUp() throws Exception {
    if (client == null) {
        Properties properties = new Properties();
        properties.load(getClass().getResourceAsStream("/test.properties"));

        String url = properties.getProperty("vmware.url");
        String username = properties.getProperty("vmware.username");
        String password = properties.getProperty("vmware.password");
        boolean ignoreCert = BooleanUtils.toBoolean(properties.getProperty("vmware.ignoreCert"));
        String datacenterName = StringUtils.defaultIfEmpty(properties.getProperty("vmware.datacenterName"), null);

        VmwareClientFactory factory = new VmwareClientFactory();
        factory.setUrl(url);
        factory.setUsername(username);
        factory.setPassword(password);
        factory.setIgnoreCert(ignoreCert);
        factory.setDatacenterName(datacenterName);

        client = factory.createVmwareClient();
    }
}
 
Example 4
public static String extensionForMIME(String mimeType) {
    if (mimeType.isEmpty())
        return DEFAULT_EXT;

    MimeType mime = null;
    try {
        mime = MimeTypes.getDefaultMimeTypes().forName(mimeType);
    } catch (MimeTypeException ex) {
        LOGGER.log(Level.WARNING, "can't find mimetype", ex);
    }

    String m = mime != null ? mime.getExtension() : "";
    // remove dot
    if (!m.isEmpty())
        m = m.substring(1);
    return StringUtils.defaultIfEmpty(m, DEFAULT_EXT);
}
 
Example 5
static int compareContacts(Contact c1, Contact c2) {
    if (c1.isMe()) return +1;
    if (c2.isMe()) return -1;

    String s1 = StringUtils.defaultIfEmpty(c1.getName(), c1.getJID().asUnescapedString());
    String s2 = StringUtils.defaultIfEmpty(c2.getName(), c2.getJID().asUnescapedString());
    return s1.compareToIgnoreCase(s2);
}
 
Example 6
private String getKibanaVersion(final RestRequest request) {
    String kbnVersion = StringUtils.defaultIfEmpty(request.header(kbnVersionHeader), "");
    if (StringUtils.isEmpty(kbnVersion)) {
        return this.kibanaVersion;
    }
    return kbnVersion;
}
 
Example 7
public String getBearerToken(RestRequest request) {
    String token = request.header(X_FORWARDED_ACCESS_TOKEN);
    if(token == null) {
        if (request.header(AUTHORIZATION_HEADER) != null) {
            final String[] auth = StringUtils.defaultIfEmpty(request.header(AUTHORIZATION_HEADER), "").split(" ");
            if (auth.length >= 2 && "Bearer".equals(auth[0])) {
                token = auth[1];
            }
        }
    }
    return  StringUtils.defaultIfEmpty(token, "");
}
 
Example 8
void mayCreateImagePreview(KonMessage message) {
        Attachment att = message.getContent().getAttachment().orElse(null);
        if (att == null) {
            LOGGER.warning("no attachment in message: "+message);
            return;
        }
        Path path = att.getFilePath();

        String mime = StringUtils.defaultIfEmpty(att.getMimeType(),
                // guess from file
                MediaUtils.mimeForFile(path));

        if (!isImage(mime))
            return;

        BufferedImage image = MediaUtils.readImage(path);
        // the attachment image could be smaller than the thumbnail - nobody cares
//        if (image.getWidth() <= THUMBNAIL_DIM.width && image.getHeight() <= THUMBNAIL_DIM.height)
//           return;

        Image thumb = MediaUtils.scaleAsync(image,
                THUMBNAIL_DIM.width ,
                THUMBNAIL_DIM.height);

        String format = MediaUtils.extensionForMIME(THUMBNAIL_MIME);

        byte[] bytes = MediaUtils.imageToByteArray(thumb, format);
        if (bytes.length <= 0)
            return;

        this.writePreview(bytes, message.getID(), THUMBNAIL_MIME);
        Preview preview = new Preview(bytes, THUMBNAIL_MIME);
        LOGGER.info("created: "+preview);

        message.setPreview(preview);
    }
 
Example 9
/**
 * Initiate rabbitmq connection factory from the connection parameters
 *
 * @param parameters connection parameters
 */
private void initConnectionFactory(Map<String, String> parameters) throws RabbitMQException {
    String hostnames = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_HOST_NAME), ConnectionFactory.DEFAULT_HOST);
    String ports = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PORT), String.valueOf(ConnectionFactory.DEFAULT_AMQP_PORT));
    String username = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_USER_NAME), ConnectionFactory.DEFAULT_USER);
    String password = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_PASSWORD), ConnectionFactory.DEFAULT_PASS);
    String virtualHost = StringUtils.defaultIfEmpty(
            parameters.get(RabbitMQConstants.SERVER_VIRTUAL_HOST), ConnectionFactory.DEFAULT_VHOST);
    int heartbeat = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.HEARTBEAT), ConnectionFactory.DEFAULT_HEARTBEAT);
    int connectionTimeout = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.CONNECTION_TIMEOUT), ConnectionFactory.DEFAULT_CONNECTION_TIMEOUT);
    long networkRecoveryInterval = NumberUtils.toLong(
            parameters.get(RabbitMQConstants.NETWORK_RECOVERY_INTERVAL), ConnectionFactory.DEFAULT_NETWORK_RECOVERY_INTERVAL);
    this.retryInterval = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_INTERVAL), RabbitMQConstants.DEFAULT_RETRY_INTERVAL);
    this.retryCount = NumberUtils.toInt(
            parameters.get(RabbitMQConstants.RETRY_COUNT), RabbitMQConstants.DEFAULT_RETRY_COUNT);
    boolean sslEnabled = BooleanUtils.toBooleanDefaultIfNull(
            BooleanUtils.toBoolean(parameters.get(RabbitMQConstants.SSL_ENABLED)), false);

    String[] hostnameArray = hostnames.split(",");
    String[] portArray = ports.split(",");
    if (hostnameArray.length == portArray.length) {
        addresses = new Address[hostnameArray.length];
        for (int i = 0; i < hostnameArray.length; i++) {
            try {
                addresses[i] = new Address(hostnameArray[i].trim(), Integer.parseInt(portArray[i].trim()));
            } catch (NumberFormatException e) {
                throw new RabbitMQException("Number format error in port number", e);
            }
        }
    } else {
        throw new RabbitMQException("The number of hostnames must be equal to the number of ports");
    }

    connectionFactory = new ConnectionFactory();
    connectionFactory.setUsername(username);
    connectionFactory.setPassword(password);
    connectionFactory.setVirtualHost(virtualHost);
    connectionFactory.setRequestedHeartbeat(heartbeat);
    connectionFactory.setConnectionTimeout(connectionTimeout);
    connectionFactory.setNetworkRecoveryInterval(networkRecoveryInterval);
    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setTopologyRecoveryEnabled(true);
    setSSL(parameters, sslEnabled);
}
 
Example 10
private String effectiveRegistryName(DockerImageName dockerImageName) {
    return StringUtils.defaultIfEmpty(dockerImageName.getRegistry(), DEFAULT_REGISTRY_NAME);
}
 
Example 11
@Override
public String getString(String key, String defaultValue) {
    return StringUtils.defaultIfEmpty(getString(key), defaultValue);
}
 
Example 12
Source Project: DBus   File: FlowLineCheckParser.java    License: Apache License 2.0 4 votes vote down vote up
private String getCanalPid() {
    return StringUtils.defaultIfEmpty(this.payload().getString("canalPid"), StringUtils.EMPTY);
}
 
Example 13
Source Project: DBus   File: FlowLineCheckParser.java    License: Apache License 2.0 4 votes vote down vote up
private String getOggStatus() {
    return StringUtils.defaultIfEmpty(this.payload().getString("oggStatus"), StringUtils.EMPTY);
}
 
Example 14
/**
 * @return Monitor name.
 */
public String getName() {
    return StringUtils.defaultIfEmpty(this.name, getClass().getSimpleName());
}
 
Example 15
@Override
public Object getContent(@Nonnull StaplerRequest request, @Nonnull Item item) {
    String path = StringUtils.defaultIfEmpty(request.getParameter("path"), null);
    String type = StringUtils.defaultIfEmpty(request.getParameter("type"), null);
    String repo = StringUtils.defaultIfEmpty(request.getParameter("repo"), null);
    String branch = StringUtils.defaultIfEmpty(request.getParameter("branch"),null);

    List<ErrorMessage.Error> errors = new ArrayList<>();

    if(!(item instanceof MultiBranchProject) && repo == null){
        errors.add(
                new ErrorMessage.Error("repo",ErrorMessage.Error.ErrorCodes.MISSING.toString(),
                        String.format("repo and branch parameters are required because pipeline %s is not a multi-branch project ",
                                item.getFullName())));
    }

    if(type != null && !type.equals("file")){
        errors.add(
                new ErrorMessage.Error("file",ErrorMessage.Error.ErrorCodes.INVALID.toString(),
                        String.format("type %s not supported. Only 'file' type supported.", type)));
    }


    if(path == null){
        errors.add(
                new ErrorMessage.Error("path",ErrorMessage.Error.ErrorCodes.MISSING.toString(),
                        "path is required query parameter"));
    }
    if(!errors.isEmpty()){
        throw new ServiceException.BadRequestException(
                new ErrorMessage(400, "Failed to load scm file").addAll(errors));
    }

    ScmContentProviderParams scmParamsFromItem = getScmParamsFromItem(item);

    //if no repo param, then see if its there in given Item.
    if(repo == null && scmParamsFromItem.getRepo() == null){
        throw new ServiceException.BadRequestException("github repo could not be determine from pipeline: "+item.getFullName());
    }

    // If both, repo param and repo in pipeline scm configuration present, they better match
    if(repo != null && scmParamsFromItem.getRepo() != null && !repo.equals(scmParamsFromItem.getRepo())){
        throw new ServiceException.BadRequestException(
                String.format("repo parameter %s doesn't match with repo in pipeline %s github configuration repo: %s ",
                        repo, item.getFullName(), scmParamsFromItem.getRepo()));
    }

    if(repo == null){
        repo = scmParamsFromItem.getRepo();
    }

    ScmGetRequest scmGetRequest = new ScmGetRequest.Builder(scmParamsFromItem.getApiUrl())
            .branch(branch)
            .owner(scmParamsFromItem.getOwner())
            .repo(repo)
            .branch(branch)
            .path(path)
            .credentials(scmParamsFromItem.getCredentials()).build();

    return getContent(scmGetRequest);
}
 
Example 16
Source Project: ymate-platform-v2   File: JsonView.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @param callback 回调方法名称
 * @return 设置并采用JSONP方式输出,回调方法名称由参数callback指定,若callback参数无效则不启用
 */
public JsonView withJsonCallback(String callback) {
    __jsonCallback = StringUtils.defaultIfEmpty(callback, null);
    return this;
}
 
Example 17
Source Project: smart-framework   File: StringUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 若字符串为空,则取默认值
 */
public static String defaultIfEmpty(String str, String defaultValue) {
    return StringUtils.defaultIfEmpty(str, defaultValue);
}
 
Example 18
public String getUser(RestRequest request) {
    return StringUtils.defaultIfEmpty(request.header(proxyUserHeader), "");
}
 
Example 19
Source Project: rebuild   File: AES.java    License: GNU General Public License v3.0 2 votes vote down vote up
/**
 * 通过 `-Drbpass=KEY` 指定 AES 秘钥
 * 
 * @return
 */
public static String getPassKey() {
	String key = StringUtils.defaultIfEmpty(System.getenv("rbpass"), System.getProperty("rbpass"));
	return StringUtils.defaultIfEmpty(key, "REBUILD2018");
}
 
Example 20
/**
 * @param key
 * @param defaultLang
 * @return
 */
private String getLang(String key, String defaultLang) {
    return StringUtils.defaultIfEmpty(bundle.getString(key), defaultLang);
}