Example usage for com.google.common.base Strings isNullOrEmpty

List of usage examples for com.google.common.base Strings isNullOrEmpty

Introduction

In this page you can find the example usage for com.google.common.base Strings isNullOrEmpty.

Prototype

public static boolean isNullOrEmpty(@Nullable String string) 

Source Link

Document

Returns true if the given string is null or is the empty string.

Usage

From source file:qa.qcri.nadeef.web.rest.TableAction.java

public static void setup(SQLDialect dialect) {
    SQLDialectBase dialectInstance = SQLDialectBase.createDialectBaseInstance(dialect);
    get("/:project/violation/metadata", (x, response) -> {
        String project = x.params("project");
        String rule = x.queryParams("rule");

        if (Strings.isNullOrEmpty(project) || Strings.isNullOrEmpty(rule))
            throw new IllegalArgumentException("Input is not valid");
        String sql = String.format(
                "select count(*), tablename from violation " + "where rid = '%s' group by tablename", rule);
        return SQLUtil.query(project, sql, true);
    });/*  w  ww .  j av  a 2s  . c om*/

    get("/:project/violation/:tablename", (x, response) -> {
        String project = x.params("project");
        String rule = x.queryParams("rule");
        String tableName = x.params("tablename");

        if (Strings.isNullOrEmpty(project) || Strings.isNullOrEmpty(rule) || Strings.isNullOrEmpty(tableName))
            throw new IllegalArgumentException("Input is not valid");

        String start_ = x.queryParams("start");
        String interval_ = x.queryParams("length");
        String filter = x.queryParams("search[value]");

        if (!(SQLUtil.isValidInteger(start_) && SQLUtil.isValidInteger(interval_)))
            throw new IllegalArgumentException("Input is not valid.");

        String vidFilter = "";
        String tidFilter = "";
        String columnFilter = "";
        if (!Strings.isNullOrEmpty(filter)) {
            if (filter.startsWith(":=")) {
                vidFilter = filter.substring(2).trim();
                if (!Strings.isNullOrEmpty(vidFilter)) {
                    String[] tokens = vidFilter.split(",");
                    for (String token : tokens)
                        if (!SQLUtil.isValidInteger(token))
                            throw new IllegalArgumentException("Input is not valid.");
                    vidFilter = "and vid = any(array[" + vidFilter + "])";
                }
            } else if (filter.startsWith("?=")) {
                tidFilter = filter.substring(2).trim();
                if (!Strings.isNullOrEmpty(tidFilter)) {
                    String[] tokens = tidFilter.split(",");
                    for (String token : tokens)
                        if (!SQLUtil.isValidInteger(token))
                            throw new IllegalArgumentException("Input is not valid.");
                    tidFilter = "and tupleid = any(array[" + tidFilter + "])";
                }
            } else {
                columnFilter = "and value like '%" + filter + "%' ";
            }
        }

        int start = Strings.isNullOrEmpty(start_) ? 0 : Integer.parseInt(start_);
        int interval = Strings.isNullOrEmpty(interval_) ? 10 : Integer.parseInt(interval_);

        String rawSql = String.format(
                "select a.*, b.vid, b._attrs from %s a inner join "
                        + "(select vid, tupleid, array_agg(attribute) as _attrs from violation "
                        + "where rid='%s' and tablename = '%s' %s %s %s group by vid, tupleid) b "
                        + "on a.tid = b.tupleid order by vid",
                tableName, rule, tableName, vidFilter, tidFilter, columnFilter);

        String limitSql = String.format("%s limit %d offset %d", rawSql, interval, start);
        JsonObject result = SQLUtil.query(project, limitSql, true);
        String countSql = String.format("select count(*) from (%s) a", rawSql);
        JsonObject countJson = SQLUtil.query(project, countSql, false);
        JsonArray dataArray = countJson.getAsJsonArray("data");
        int count = dataArray.get(0).getAsInt();
        result.add("iTotalRecords", new JsonPrimitive(count));
        result.add("iTotalDisplayRecords", new JsonPrimitive(count));
        if (x.queryParams("sEcho") != null)
            result.add("sEcho", new JsonPrimitive(x.queryParams("sEcho")));
        return result;
    });

    /**
     * Gets data table with pagination support.
     */
    get("/:project/table/:tablename", (x, response) -> {
        String tableName = x.params("tablename");
        String project = x.params("project");

        if (Strings.isNullOrEmpty(tableName) || Strings.isNullOrEmpty(project))
            throw new IllegalArgumentException("Input is not valid");

        JsonObject queryJson;
        String start_ = x.queryParams("start");
        String interval_ = x.queryParams("length");

        if (!(SQLUtil.isValidInteger(start_) && SQLUtil.isValidInteger(interval_)))
            throw new IllegalArgumentException("Input is not valid.");

        int start = Strings.isNullOrEmpty(start_) ? 0 : Integer.parseInt(start_);
        int interval = Strings.isNullOrEmpty(interval_) ? 10 : Integer.parseInt(interval_);
        String filter = x.queryParams("search[value]");
        ArrayList columns = null;
        if (!Strings.isNullOrEmpty(filter)) {
            JsonObject objSchema = SQLUtil.query(project, dialectInstance.querySchema(tableName), true);
            columns = new Gson().fromJson(objSchema.getAsJsonArray("schema"), ArrayList.class);
        }

        queryJson = SQLUtil.query(project,
                dialectInstance.queryTable(tableName, start, interval, columns, filter), true);

        JsonObject countJson = SQLUtil.query(project, dialectInstance.countTable(tableName), true);
        JsonArray dataArray = countJson.getAsJsonArray("data");
        int count = dataArray.get(0).getAsInt();
        queryJson.add("iTotalRecords", new JsonPrimitive(count));
        queryJson.add("iTotalDisplayRecords", new JsonPrimitive(count));
        if (x.queryParams("sEcho") != null)
            queryJson.add("sEcho", new JsonPrimitive(x.queryParams("sEcho")));
        return queryJson;
    });

    get("/:project/table/:tablename/schema", (request, response) -> {
        String tableName = request.params("tablename");
        String project = request.params("project");

        if (Strings.isNullOrEmpty(tableName) || Strings.isNullOrEmpty(project))
            throw new IllegalArgumentException("Input is not valid.");

        return SQLUtil.query(project, dialectInstance.querySchema(tableName), true);
    });

    delete("/:project/table/violation", (request, response) -> {
        String project = request.params("project");
        if (Strings.isNullOrEmpty(project))
            throw new IllegalArgumentException("Input is not valid.");

        return SQLUtil.update(project, dialectInstance.deleteViolation());
    });
}

From source file:org.apache.james.modules.mailbox.ListenerConfiguration.java

public static ListenerConfiguration from(HierarchicalConfiguration configuration) {
    String listenerClass = configuration.getString("class");
    Preconditions.checkState(!Strings.isNullOrEmpty(listenerClass), "class name is mandatory");
    Optional<Boolean> isAsync = Optional.ofNullable(configuration.getBoolean("async", null));
    return new ListenerConfiguration(listenerClass, extractSubconfiguration(configuration), isAsync);
}

From source file:de.cbb.mplayer.mapping.String2TextFieldMapper.java

@Override
public void map(String value) throws Exception {
    TextField tf = (TextField) MappingUtil.getAccessableControl(fieldname, object);
    if (Strings.isNullOrEmpty(value))
        tf.setText("");
    else/*from  w  w w.  ja v a 2s.c  o  m*/
        tf.setText(value);

}

From source file:com.enonic.cms.core.search.facet.builder.AbstractElasticsearchFacetBuilder.java

protected static String[] getCommaDelimitedStringAsArraySkipWhitespaces(String commaSeparatedString) {
    if (Strings.isNullOrEmpty(commaSeparatedString)) {
        return null;
    }//w  w  w  .j  a  va 2s.c  om

    return commaSeparatedString.split(",\\s*");
}

From source file:com.olacabs.fabric.compute.builder.impl.ArtifactoryJarPathResolver.java

public static String resolve(final String artifactoryUrl, final String groupId, final String artifactId,
        final String version) throws Exception {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(artifactoryUrl), "Artifactory URL cannot be null");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(groupId), "Group Id cannot be null");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(artifactId), "Artifact Id cannot be null");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(version), "Artifact version cannot be null");
    boolean isSnapshot = version.contains("SNAPSHOT");
    LOGGER.info("Artifact is snapshot: {}", isSnapshot);
    final String repoName = isSnapshot ? "libs-snapshot-local" : "libs-release-local";

    Artifactory client = ArtifactoryClient.create(artifactoryUrl);
    LOGGER.info("Aritifactory client created successfully with uri {}", client.getUri());
    FileAttribute<Set<PosixFilePermission>> perms = PosixFilePermissions
            .asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x"));
    java.nio.file.Path tempFilePath = Files.createTempFile(Long.toString(System.currentTimeMillis()), "xml",
            perms);//  w w  w  . j a va2  s . co  m
    String metadataStr = null;
    if (isSnapshot) {
        metadataStr = String.format("%s/%s/%s/maven-metadata.xml", groupId.replaceAll("\\.", "/"), artifactId,
                version);
    } else {
        metadataStr = String.format("%s/%s/maven-metadata.xml", groupId.replaceAll("\\.", "/"), artifactId);
    }

    LOGGER.info("Repo-name - {}, metadataStr - {}", repoName, metadataStr);
    InputStream response = client.repository(repoName).download(metadataStr).doDownload();
    LOGGER.info("download complete");
    Files.copy(response, tempFilePath, StandardCopyOption.REPLACE_EXISTING);
    LOGGER.info("Metadata file downloaded to: {}", tempFilePath.toAbsolutePath().toString());

    final String url = String.format("%s/%s/%s/%s/%s/%s-%s.jar", artifactoryUrl, repoName,
            groupId.replaceAll("\\.", "/"), artifactId, version, artifactId, version);
    LOGGER.info("Jar will be downloaded from: " + url);
    return url;
}

From source file:com.b2international.snowowl.snomed.core.domain.constraint.SnomedConceptSetDefinition.java

public static String getCharacteristicTypeExpression(final String characteristicTypeId) {
    return Strings.isNullOrEmpty(characteristicTypeId) ? "<" + Concepts.CHARACTERISTIC_TYPE
            : "<<" + characteristicTypeId;
}

From source file:com.jarlenai.wcl.WarcraftLogsApi.java

/**
 * Get an instance of the API that uses the given API key
 * @param apiKey API Key to acceess WarcraftLogs API
 * @return Instance of the API/*from   w  w w  . j  a  va 2 s.  c o m*/
 */
public static WarcraftLogsApi get(final String apiKey) {

    checkArgument(!Strings.isNullOrEmpty(apiKey), "A valid API Key must be provided");

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint("https://www.warcraftlogs.com:443/v1")
            .setRequestInterceptor(request -> request.addQueryParam("api_key", apiKey)).build();

    return restAdapter.create(WarcraftLogsApi.class);
}

From source file:com.enonic.cms.core.portal.datasource.handler.base.SimpleDataSourceHandler.java

protected final String requiredParam(final DataSourceRequest req, String name) {
    final String value = req.getParams().get(name);
    if (Strings.isNullOrEmpty(value)) {
        throw new DataSourceException("Parameter [{0}] is required for data source [{1}]", name, getName());
    }/*from ww  w  .  ja  v  a  2  s .  c  o  m*/

    return value;
}

From source file:com.google.api.tools.framework.importers.swagger.SwaggerFileWriter.java

/** Saves the file contents on the disk and returns the saved file paths. */
public static Map<String, FileWrapper> saveFilesOnDisk(List<FileWrapper> inputFiles) {

    ImmutableMap.Builder<String, FileWrapper> savedFiles = ImmutableMap.builder();
    File tempDir = Files.createTempDir();
    String tmpDirLocation = tempDir.getAbsolutePath();
    for (FileWrapper inputFile : inputFiles) {
        String filePath = inputFile.getFilename().replaceAll("[\\\\/:]", "_");

        Preconditions.checkState(!Strings.isNullOrEmpty(inputFile.getFileContents().toString()),
                "swagger spec file contents empty");
        Preconditions.checkState(!Strings.isNullOrEmpty(filePath), "swagger spec file path not provided");

        String filePathToSave = File.separator + tmpDirLocation + File.separator + "swagger_spec_files"
                + File.separator + filePath;
        FileWrapper fileToSave = FileWrapper.create(filePathToSave, inputFile.getFileContents());
        try {/*ww  w.  ja  v  a2  s . c  o m*/
            saveFileOnDisk(fileToSave);
            savedFiles.put(inputFile.getFilename(), fileToSave);
        } catch (IOException ex) {
            throw new IllegalStateException(
                    String.format("Unable to save the swagger spec contents on the disk at %s", filePathToSave),
                    ex);
        }
    }
    return savedFiles.build();
}

From source file:org.xacml4j.v30.types.AnyURIExp.java

/**
 * Creates an XACML expression of {@link XacmlTypes#ANYURI} 
 * from a given string// ww  w  .  j  av  a 2 s  . c om
 * 
 * @param v a string value
 * @return {@link AnyURIExp} instance
 */
public static AnyURIExp of(String v) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(v));
    return new AnyURIExp(URI.create(v).normalize());
}