Java Code Examples for org.elasticsearch.common.Strings#hasLength()

The following examples show how to use org.elasticsearch.common.Strings#hasLength() . 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 check out the related API usage on the sidebar.
Example 1
Source File: TaskId.java    From crate with Apache License 2.0 6 votes vote down vote up
public TaskId(String taskId) {
    if (Strings.hasLength(taskId) && "unset".equals(taskId) == false) {
        String[] s = Strings.split(taskId, ":");
        if (s == null || s.length != 2) {
            throw new IllegalArgumentException("malformed task id " + taskId);
        }
        this.nodeId = s[0];
        try {
            this.id = Long.parseLong(s[1]);
        } catch (NumberFormatException ex) {
            throw new IllegalArgumentException("malformed task id " + taskId, ex);
        }
    } else {
        nodeId = "";
        id = -1L;
    }
}
 
Example 2
Source File: CsvProcessor.java    From elasticsearch-ingest-csv with Apache License 2.0 6 votes vote down vote up
@Override
public IngestDocument execute(IngestDocument ingestDocument) throws Exception {
    String content = ingestDocument.getFieldValue(field, String.class);

    if (Strings.hasLength(content)) {
        String[] values;
        synchronized (parser) {
            values = parser.parseLine(content);
        }
        if (values.length != this.columns.size()) {
            // TODO should be error?
            throw new IllegalArgumentException("field[" + this.field + "] size ["
                + values.length + "] doesn't match header size [" + columns.size() + "].");
        }

        for (int i = 0; i < columns.size(); i++) {
            ingestDocument.setFieldValue(columns.get(i), values[i]);
        }
    } else {
        // TODO should we have ignoreMissing flag?
        throw new IllegalArgumentException("field[" + this.field + "] is empty string.");
    }
    return ingestDocument;
}
 
Example 3
Source File: SnapshotsService.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private static void validate(SnapshotId snapshotId) {
    String name = snapshotId.getSnapshot();
    if (!Strings.hasLength(name)) {
        throw new InvalidSnapshotNameException(snapshotId, "cannot be empty");
    }
    if (name.contains(" ")) {
        throw new InvalidSnapshotNameException(snapshotId, "must not contain whitespace");
    }
    if (name.contains(",")) {
        throw new InvalidSnapshotNameException(snapshotId, "must not contain ','");
    }
    if (name.contains("#")) {
        throw new InvalidSnapshotNameException(snapshotId, "must not contain '#'");
    }
    if (name.charAt(0) == '_') {
        throw new InvalidSnapshotNameException(snapshotId, "must not start with '_'");
    }
    if (!name.toLowerCase(Locale.ROOT).equals(name)) {
        throw new InvalidSnapshotNameException(snapshotId, "must be lowercase");
    }
    if (!Strings.validFileName(name)) {
        throw new InvalidSnapshotNameException(snapshotId, "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
    }
}
 
Example 4
Source File: DiscoveryNode.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    if (nodeName.length() > 0) {
        sb.append('{').append(nodeName).append('}');
    }
    if (nodeId != null) {
        sb.append('{').append(nodeId).append('}');
    }
    if (Strings.hasLength(hostName)) {
        sb.append('{').append(hostName).append('}');
    }
    if (address != null) {
        sb.append('{').append(address).append('}');
    }
    if (!attributes.isEmpty()) {
        sb.append(attributes);
    }
    return sb.toString();
}
 
Example 5
Source File: RestAliasAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private Table buildTable(RestRequest request, GetAliasesResponse response) {
    Table table = getTableWithHeader(request);

    for (ObjectObjectCursor<String, List<AliasMetaData>> cursor : response.getAliases()) {
        String indexName = cursor.key;
        for (AliasMetaData aliasMetaData : cursor.value) {
            table.startRow();
            table.addCell(aliasMetaData.alias());
            table.addCell(indexName);
            table.addCell(aliasMetaData.filteringRequired() ? "*" : "-");
            String indexRouting = Strings.hasLength(aliasMetaData.indexRouting()) ? aliasMetaData.indexRouting() : "-";
            table.addCell(indexRouting);
            String searchRouting = Strings.hasLength(aliasMetaData.searchRouting()) ? aliasMetaData.searchRouting() : "-";
            table.addCell(searchRouting);
            table.endRow();
        }
    }

    return table;
}
 
Example 6
Source File: SnapshotsService.java    From crate with Apache License 2.0 6 votes vote down vote up
private static void validate(final String repositoryName, final String snapshotName) {
    if (Strings.hasLength(snapshotName) == false) {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "cannot be empty");
    }
    if (snapshotName.contains(" ")) {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "must not contain whitespace");
    }
    if (snapshotName.contains(",")) {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "must not contain ','");
    }
    if (snapshotName.contains("#")) {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "must not contain '#'");
    }
    if (snapshotName.charAt(0) == '_') {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "must not start with '_'");
    }
    if (snapshotName.toLowerCase(Locale.ROOT).equals(snapshotName) == false) {
        throw new InvalidSnapshotNameException(repositoryName, snapshotName, "must be lowercase");
    }
    if (Strings.validFileName(snapshotName) == false) {
        throw new InvalidSnapshotNameException(repositoryName,
            snapshotName,
            "must not contain the following characters " + Strings.INVALID_FILENAME_CHARS);
    }
}
 
Example 7
Source File: ReproduceInfoPrinter.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Append a single VM option.
 */
@Override
public ReproduceErrorMessageBuilder appendOpt(String sysPropName, String value) {
    if (sysPropName.equals(SYSPROP_ITERATIONS())) { // we don't want the iters to be in there!
        return this;
    }
    if (sysPropName.equals(SYSPROP_TESTMETHOD())) {
        //don't print out the test method, we print it ourselves in appendAllOpts
        //without filtering out the parameters (needed for REST tests)
        return this;
    }
    if (sysPropName.equals(SYSPROP_PREFIX())) {
        // we always use the default prefix
        return this;
    }
    if (Strings.hasLength(value)) {
        return super.appendOpt(sysPropName, value);
    }
    return this;
}
 
Example 8
Source File: AzureRepository.java    From crate with Apache License 2.0 5 votes vote down vote up
private static BlobPath buildBasePath(RepositoryMetaData metadata) {
    final String basePath = Strings.trimLeadingCharacter(Repository.BASE_PATH_SETTING.get(metadata.settings()), '/');
    if (Strings.hasLength(basePath)) {
        // Remove starting / if any
        BlobPath path = new BlobPath();
        for (final String elem : basePath.split("/")) {
            path = path.add(elem);
        }
        return path;
    } else {
        return BlobPath.cleanPath();
    }
}
 
Example 9
Source File: AliasValidator.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Allows to partially validate an alias, without knowing which index it'll get applied to.
 * Useful with index templates containing aliases. Checks also that it is possible to parse
 * the alias filter via {@link org.elasticsearch.common.xcontent.XContentParser},
 * without validating it as a filter though.
 * @throws IllegalArgumentException if the alias is not valid
 */
public void validateAliasStandalone(Alias alias) {
    validateAliasStandalone(alias.name(), alias.indexRouting());
    if (Strings.hasLength(alias.filter())) {
        try (XContentParser parser = XContentFactory.xContent(alias.filter()).createParser(alias.filter())) {
            parser.map();
        } catch (Throwable e) {
            throw new IllegalArgumentException("failed to parse filter for alias [" + alias.name() + "]", e);
        }
    }
}
 
Example 10
Source File: ScriptModes.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static ScriptMode getScriptContextMode(Settings settings, String prefix, ScriptContext scriptContext) {
    String settingValue = settings.get(prefix + scriptContext.getKey());
    if (Strings.hasLength(settingValue)) {
        return ScriptMode.parse(settingValue);
    }
    return null;
}
 
Example 11
Source File: Settings.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns group settings for the given setting prefix.
 */
public Map<String, Settings> getGroups(String settingPrefix, boolean ignoreNonGrouped) throws SettingsException {
    if (!Strings.hasLength(settingPrefix)) {
        throw new IllegalArgumentException("illegal setting prefix " + settingPrefix);
    }
    if (settingPrefix.charAt(settingPrefix.length() - 1) != '.') {
        settingPrefix = settingPrefix + ".";
    }
    return getGroupsInternal(settingPrefix, ignoreNonGrouped);
}
 
Example 12
Source File: Lucene.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static Version parse(String toParse, Version defaultValue) {
    if (Strings.hasLength(toParse)) {
        try {
            return Version.parseLeniently(toParse);
        } catch (ParseException e) {
            // pass to default
        }
    }
    return defaultValue;
}
 
Example 13
Source File: HdfsRepository.java    From crate with Apache License 2.0 5 votes vote down vote up
public HdfsRepository(RepositoryMetaData metadata, Environment environment,
                      NamedXContentRegistry namedXContentRegistry, ThreadPool threadPool) {
    super(metadata, environment.settings(), namedXContentRegistry, threadPool, BlobPath.cleanPath());

    this.environment = environment;
    this.chunkSize = metadata.settings().getAsBytesSize("chunk_size", null);

    String uriSetting = getMetadata().settings().get("uri");
    if (Strings.hasText(uriSetting) == false) {
        throw new IllegalArgumentException("No 'uri' defined for hdfs snapshot/restore");
    }
    uri = URI.create(uriSetting);
    if ("hdfs".equalsIgnoreCase(uri.getScheme()) == false) {
        throw new IllegalArgumentException(String.format(Locale.ROOT,
            "Invalid scheme [%s] specified in uri [%s]; only 'hdfs' uri allowed for hdfs snapshot/restore",
            uri.getScheme(), uriSetting));
    }
    if (Strings.hasLength(uri.getPath()) && uri.getPath().equals("/") == false) {
        throw new IllegalArgumentException(String.format(Locale.ROOT,
            "Use 'path' option to specify a path [%s], not the uri [%s] for hdfs snapshot/restore", uri.getPath(), uriSetting));
    }

    pathSetting = getMetadata().settings().get("path");
    // get configuration
    if (pathSetting == null) {
        throw new IllegalArgumentException("No 'path' defined for hdfs snapshot/restore");
    }
}
 
Example 14
Source File: Lucene.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Version parse(String toParse, Version defaultValue) {
    if (Strings.hasLength(toParse)) {
        try {
            return Version.parseLeniently(toParse);
        } catch (ParseException e) {
            // pass to default
        }
    }
    return defaultValue;
}
 
Example 15
Source File: OpenNlpProcessor.java    From elasticsearch-ingest-opennlp with Apache License 2.0 5 votes vote down vote up
@Override
public IngestDocument execute(IngestDocument ingestDocument) {
    String content = ingestDocument.getFieldValue(sourceField, String.class);

    if (Strings.hasLength(content)) {
        Map<String, Set<String>> entities = new HashMap<>();
        mergeExisting(entities, ingestDocument, targetField);

        List<ExtractedEntities> extractedEntities = new ArrayList<>();
        for (String field : fields) {
            ExtractedEntities data = openNlpService.find(content, field);
            extractedEntities.add(data);
            merge(entities, field, data.getEntityValues());
        }

        // convert set to list, otherwise toXContent serialization in simulate pipeline fails
        Map<String, List<String>> entitiesToStore = new HashMap<>();
        Iterator<Map.Entry<String, Set<String>>> iterator = entities.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Set<String>> entry = iterator.next();
            entitiesToStore.put(entry.getKey(), new ArrayList<>(entry.getValue()));
        }

        ingestDocument.setFieldValue(targetField, entitiesToStore);

        if (Strings.hasLength(annotatedTextField) && extractedEntities.isEmpty() == false) {
            String annotatedText = OpenNlpService.createAnnotatedText(content, extractedEntities);
            ingestDocument.setFieldValue(annotatedTextField, annotatedText);
        }
    }

    return ingestDocument;
}
 
Example 16
Source File: ReproduceInfoPrinter.java    From crate with Apache License 2.0 5 votes vote down vote up
protected ReproduceErrorMessageBuilder appendProperties(String... properties) {
    for (String sysPropName : properties) {
        if (Strings.hasLength(System.getProperty(sysPropName))) {
            appendOpt(sysPropName, System.getProperty(sysPropName));
        }
    }
    return this;
}
 
Example 17
Source File: NodeTestHelper.java    From elasticsearch-graphite-plugin with Do What The F*ck You Want To Public License 5 votes vote down vote up
public static Node createNode(String clusterName, int graphitePort, String refreshInterval, String includeRegex,
                              String excludeRegex, String prefix) throws IOException {
    ImmutableSettings.Builder settingsBuilder = ImmutableSettings.settingsBuilder();

    settingsBuilder.put("path.conf", NodeTestHelper.class.getResource("/").getFile());

    settingsBuilder.put("gateway.type", "none");
    settingsBuilder.put("cluster.name", clusterName);
    settingsBuilder.put("index.number_of_shards", 1);
    settingsBuilder.put("index.number_of_replicas", 1);

    settingsBuilder.put("metrics.graphite.host", "localhost");
    settingsBuilder.put("metrics.graphite.port", graphitePort);
    settingsBuilder.put("metrics.graphite.every", refreshInterval);
    if (!Strings.isEmpty(prefix)) {
        settingsBuilder.put("metrics.graphite.prefix", prefix);
    }

    if (Strings.hasLength(includeRegex)) {
        settingsBuilder.put("metrics.graphite.include", includeRegex);
    }

    if (Strings.hasLength(excludeRegex)) {
        settingsBuilder.put("metrics.graphite.exclude", excludeRegex);
    }

    LogConfigurator.configure(settingsBuilder.build());

    return NodeBuilder.nodeBuilder().settings(settingsBuilder.build()).node();
}
 
Example 18
Source File: IsPrimeSearchScriptFactory.java    From elasticsearch-native-script-example with Apache License 2.0 5 votes vote down vote up
/**
 * This method is called for every search on every shard.
 *
 * @param params list of script parameters passed with the query
 * @return new native script
 */
@Override
public ExecutableScript newScript(@Nullable Map<String, Object> params) {
    // Example of a mandatory string parameter
    // The XContentMapValues helper class can be used to simplify parameter parsing
    String fieldName = params == null ? null : XContentMapValues.nodeStringValue(params.get("field"), defaultFieldName);
    if (!Strings.hasLength(fieldName)) {
        throw new IllegalArgumentException("Missing the field parameter");
    }

    // Example of an optional integer  parameter
    int certainty = params == null ? 10 : XContentMapValues.nodeIntegerValue(params.get("certainty"), 10);
    return new IsPrimeSearchScript(fieldName, certainty);
}
 
Example 19
Source File: NettyTransport.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void doStart() {
    boolean success = false;
    try {
        clientBootstrap = createClientBootstrap();
        if (settings.getAsBoolean("network.server", true)) {
            final OpenChannelsHandler openChannels = new OpenChannelsHandler(logger);
            this.serverOpenChannels = openChannels;

            // extract default profile first and create standard bootstrap
            Map<String, Settings> profiles = settings.getGroups("transport.profiles", true);
            if (!profiles.containsKey(DEFAULT_PROFILE)) {
                profiles = Maps.newHashMap(profiles);
                profiles.put(DEFAULT_PROFILE, Settings.EMPTY);
            }

            Settings fallbackSettings = createFallbackSettings();
            Settings defaultSettings = profiles.get(DEFAULT_PROFILE);

            // loop through all profiles and start them up, special handling for default one
            for (Map.Entry<String, Settings> entry : profiles.entrySet()) {
                Settings profileSettings = entry.getValue();
                String name = entry.getKey();

                if (!Strings.hasLength(name)) {
                    logger.info("transport profile configured without a name. skipping profile with settings [{}]", profileSettings.toDelimitedString(','));
                    continue;
                } else if (DEFAULT_PROFILE.equals(name)) {
                    profileSettings = settingsBuilder()
                            .put(profileSettings)
                            .put("port", profileSettings.get("port", this.settings.get("transport.tcp.port", DEFAULT_PORT_RANGE)))
                            .build();
                } else if (profileSettings.get("port") == null) {
                    // if profile does not have a port, skip it
                    logger.info("No port configured for profile [{}], not binding", name);
                    continue;
                }

                // merge fallback settings with default settings with profile settings so we have complete settings with default values
                Settings mergedSettings = settingsBuilder()
                        .put(fallbackSettings)
                        .put(defaultSettings)
                        .put(profileSettings)
                        .build();

                createServerBootstrap(name, mergedSettings);
                bindServerBootstrap(name, mergedSettings);
            }
        }
        success = true;
    } finally {
        if (success == false) {
            doStop();
        }
    }
}
 
Example 20
Source File: SameShardAllocationDecider.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
    Iterable<ShardRouting> assignedShards = allocation.routingNodes().assignedShards(shardRouting.shardId());
    Decision decision = decideSameNode(shardRouting, node, allocation, assignedShards);
    if (decision.type() == Decision.Type.NO || sameHost == false) {
        // if its already a NO decision looking at the node, or we aren't configured to look at the host, return the decision
        return decision;
    }
    if (node.node() != null) {
        for (RoutingNode checkNode : allocation.routingNodes()) {
            if (checkNode.node() == null) {
                continue;
            }
            // check if its on the same host as the one we want to allocate to
            boolean checkNodeOnSameHostName = false;
            boolean checkNodeOnSameHostAddress = false;
            if (Strings.hasLength(checkNode.node().getHostAddress()) && Strings.hasLength(node.node().getHostAddress())) {
                if (checkNode.node().getHostAddress().equals(node.node().getHostAddress())) {
                    checkNodeOnSameHostAddress = true;
                }
            } else if (Strings.hasLength(checkNode.node().getHostName()) && Strings.hasLength(node.node().getHostName())) {
                if (checkNode.node().getHostName().equals(node.node().getHostName())) {
                    checkNodeOnSameHostName = true;
                }
            }
            if (checkNodeOnSameHostAddress || checkNodeOnSameHostName) {
                for (ShardRouting assignedShard : assignedShards) {
                    if (checkNode.nodeId().equals(assignedShard.currentNodeId())) {
                        String hostType = checkNodeOnSameHostAddress ? "address" : "name";
                        String host = checkNodeOnSameHostAddress ? node.node().getHostAddress() : node.node().getHostName();
                        return allocation.decision(Decision.NO, NAME,
                            "the shard cannot be allocated on host %s [%s], where it already exists on node [%s]; " +
                                "set cluster setting [%s] to false to allow multiple nodes on the same host to hold the same " +
                                "shard copies",
                            hostType, host, node.nodeId(), CLUSTER_ROUTING_ALLOCATION_SAME_HOST_SETTING.getKey());
                    }
                }
            }
        }
    }
    return allocation.decision(Decision.YES, NAME, "the shard does not exist on the same host");
}