Java 类org.elasticsearch.common.xcontent.NamedXContentRegistry 实例源码

项目:elasticsearch_my    文件:URLRepository.java   
/**
 * Constructs a read-only URL-based repository
 */
public URLRepository(RepositoryMetaData metadata, Environment environment,
                     NamedXContentRegistry namedXContentRegistry) throws IOException {
    super(metadata, environment.settings(), namedXContentRegistry);

    if (URL_SETTING.exists(metadata.settings()) == false && REPOSITORIES_URL_SETTING.exists(settings) ==  false) {
        throw new RepositoryException(metadata.name(), "missing url");
    }
    supportedProtocols = SUPPORTED_PROTOCOLS_SETTING.get(settings);
    urlWhiteList = ALLOWED_URLS_SETTING.get(settings).toArray(new URIPattern[]{});
    this.environment = environment;

    URL url = URL_SETTING.exists(metadata.settings()) ? URL_SETTING.get(metadata.settings()) : REPOSITORIES_URL_SETTING.get(settings);
    URL normalizedURL = checkURL(url);
    blobStore = new URLBlobStore(settings, normalizedURL);
    basePath = BlobPath.cleanPath();
}
项目:elasticsearch_my    文件:BaseAggregationTestCase.java   
/**
 * Setup for the whole base test class.
 */
@Override
public void setUp() throws Exception {
    super.setUp();
    Settings settings = Settings.builder()
        .put("node.name", AbstractQueryTestCase.class.toString())
        .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
        .build();
    IndicesModule indicesModule = new IndicesModule(Collections.emptyList());
    SearchModule searchModule = new SearchModule(settings, false, emptyList());
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.addAll(indicesModule.getNamedWriteables());
    entries.addAll(searchModule.getNamedWriteables());
    namedWriteableRegistry = new NamedWriteableRegistry(entries);
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
    //create some random type with some default field, those types will stick around for all of the subclasses
    currentTypes = new String[randomIntBetween(0, 5)];
    for (int i = 0; i < currentTypes.length; i++) {
        String type = randomAsciiOfLengthBetween(1, 10);
        currentTypes[i] = type;
    }
}
项目:elasticsearch_my    文件:PipelineConfigurationTests.java   
public void testParser() throws IOException {
    ContextParser<Void, PipelineConfiguration> parser = PipelineConfiguration.getParser();
    XContentType xContentType = randomFrom(XContentType.values());
    final BytesReference bytes;
    try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) {
        new PipelineConfiguration("1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), XContentType.JSON)
            .toXContent(builder, ToXContent.EMPTY_PARAMS);
        bytes = builder.bytes();
    }

    XContentParser xContentParser = xContentType.xContent().createParser(NamedXContentRegistry.EMPTY, bytes);
    PipelineConfiguration parsed = parser.parse(xContentParser, null);
    assertEquals(xContentType, parsed.getXContentType());
    assertEquals("{}", XContentHelper.convertToJson(parsed.getConfig(), false, parsed.getXContentType()));
    assertEquals("1", parsed.getId());
}
项目:elasticsearch_my    文件:MapperService.java   
public MapperService(IndexSettings indexSettings, IndexAnalyzers indexAnalyzers, NamedXContentRegistry xContentRegistry,
                     SimilarityService similarityService, MapperRegistry mapperRegistry,
                     Supplier<QueryShardContext> queryShardContextSupplier) {
    super(indexSettings);
    this.indexAnalyzers = indexAnalyzers;
    this.fieldTypes = new FieldTypeLookup();
    this.documentParser = new DocumentMapperParser(indexSettings, this, indexAnalyzers, xContentRegistry, similarityService,
            mapperRegistry, queryShardContextSupplier);
    this.indexAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultIndexAnalyzer(), p -> p.indexAnalyzer());
    this.searchAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchAnalyzer(), p -> p.searchAnalyzer());
    this.searchQuoteAnalyzer = new MapperAnalyzerWrapper(indexAnalyzers.getDefaultSearchQuoteAnalyzer(), p -> p.searchQuoteAnalyzer());
    this.mapperRegistry = mapperRegistry;

    this.dynamic = this.indexSettings.getValue(INDEX_MAPPER_DYNAMIC_SETTING);
    defaultMappingSource = "{\"_default_\":{}}";

    if (logger.isTraceEnabled()) {
        logger.trace("using dynamic[{}], default mapping source[{}]", dynamic, defaultMappingSource);
    } else if (logger.isDebugEnabled()) {
        logger.debug("using dynamic[{}]", dynamic);
    }
}
项目:elasticsearch_my    文件:RestRequest.java   
/**
 * Creates a new RestRequest
 * @param xContentRegistry the xContentRegistry to use when parsing XContent
 * @param uri the URI of the request that potentially contains request parameters
 * @param headers a map of the headers. This map should implement a Case-Insensitive hashing for keys as HTTP header names are case
 *                insensitive
 */
public RestRequest(NamedXContentRegistry xContentRegistry, String uri, Map<String, List<String>> headers) {
    this.xContentRegistry = xContentRegistry;
    final Map<String, String> params = new HashMap<>();
    int pathEndPos = uri.indexOf('?');
    if (pathEndPos < 0) {
        this.rawPath = uri;
    } else {
        this.rawPath = uri.substring(0, pathEndPos);
        RestUtils.decodeQueryString(uri, pathEndPos + 1, params);
    }
    this.params = params;
    this.headers = Collections.unmodifiableMap(headers);
    final List<String> contentType = getAllHeaderValues("Content-Type");
    final XContentType xContentType = parseContentType(contentType);
    if (xContentType != null) {
        this.xContentType.set(xContentType);
    }
}
项目:elasticsearch_my    文件:BasePipelineAggregationTestCase.java   
/**
 * Setup for the whole base test class.
 */
@Override
public void setUp() throws Exception {
    super.setUp();
    Settings settings = Settings.builder()
        .put("node.name", AbstractQueryTestCase.class.toString())
        .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir())
        .build();
    IndicesModule indicesModule = new IndicesModule(Collections.emptyList());
    SearchModule searchModule = new SearchModule(settings, false, emptyList());
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.addAll(indicesModule.getNamedWriteables());
    entries.addAll(searchModule.getNamedWriteables());
    namedWriteableRegistry = new NamedWriteableRegistry(entries);
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
    //create some random type with some default field, those types will stick around for all of the subclasses
    currentTypes = new String[randomIntBetween(0, 5)];
    for (int i = 0; i < currentTypes.length; i++) {
        String type = randomAsciiOfLengthBetween(1, 10);
        currentTypes[i] = type;
    }
}
项目:elasticsearch_my    文件:MockRepository.java   
public MockRepository(RepositoryMetaData metadata, Environment environment,
                      NamedXContentRegistry namedXContentRegistry) throws IOException {
    super(overrideSettings(metadata, environment), environment, namedXContentRegistry);
    randomControlIOExceptionRate = metadata.settings().getAsDouble("random_control_io_exception_rate", 0.0);
    randomDataFileIOExceptionRate = metadata.settings().getAsDouble("random_data_file_io_exception_rate", 0.0);
    useLuceneCorruptionException = metadata.settings().getAsBoolean("use_lucene_corruption", false);
    maximumNumberOfFailures = metadata.settings().getAsLong("max_failure_number", 100L);
    blockOnControlFiles = metadata.settings().getAsBoolean("block_on_control", false);
    blockOnDataFiles = metadata.settings().getAsBoolean("block_on_data", false);
    blockOnInitialization = metadata.settings().getAsBoolean("block_on_init", false);
    randomPrefix = metadata.settings().get("random", "default");
    waitAfterUnblock = metadata.settings().getAsLong("wait_after_unblock", 0L);
    atomicMove = metadata.settings().getAsBoolean("atomic_move", true);
    logger.info("starting mock repository with random prefix {}", randomPrefix);
    mockBlobStore = new MockBlobStore(super.blobStore());
}
项目:elasticsearch_my    文件:FileBasedDiscoveryPlugin.java   
@Override
public Collection<Object> createComponents(
        Client client,
        ClusterService clusterService,
        ThreadPool threadPool,
        ResourceWatcherService resourceWatcherService,
        ScriptService scriptService,
        NamedXContentRegistry xContentRegistry) {
    final int concurrentConnects = UnicastZenPing.DISCOVERY_ZEN_PING_UNICAST_CONCURRENT_CONNECTS_SETTING.get(settings);
    final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(settings, "[file_based_discovery_resolve]");
    fileBasedDiscoveryExecutorService = EsExecutors.newScaling(
        "file_based_discovery_resolve",
        0,
        concurrentConnects,
        60,
        TimeUnit.SECONDS,
        threadFactory,
        threadPool.getThreadContext());

    return Collections.emptyList();
}
项目:elasticsearch_my    文件:JsonXContentGenerator.java   
@Override
public void writeRawField(String name, InputStream content, XContentType contentType) throws IOException {
    if (mayWriteRawData(contentType) == false) {
        // EMPTY is safe here because we never call namedObject when writing raw data
        try (XContentParser parser = XContentFactory.xContent(contentType).createParser(NamedXContentRegistry.EMPTY, content)) {
            parser.nextToken();
            writeFieldName(name);
            copyCurrentStructure(parser);
        }
    } else {
        writeStartRaw(name);
        flush();
        Streams.copy(content, os);
        writeEndRaw();
    }
}
项目:elasticsearch_my    文件:Netty4HttpRequest.java   
Netty4HttpRequest(NamedXContentRegistry xContentRegistry, FullHttpRequest request, Channel channel) {
    super(xContentRegistry, request.uri(), new HttpHeadersMap(request.headers()));
    this.request = request;
    this.channel = channel;
    if (request.content().isReadable()) {
        this.content = Netty4Utils.toBytesReference(request.content());
    } else {
        this.content = BytesArray.EMPTY;
    }
}
项目:elasticsearch_my    文件:Netty4Plugin.java   
@Override
public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                                                                    CircuitBreakerService circuitBreakerService,
                                                                    NamedWriteableRegistry namedWriteableRegistry,
                                                                    NamedXContentRegistry xContentRegistry,
                                                                    NetworkService networkService,
                                                                    HttpServerTransport.Dispatcher dispatcher) {
    return Collections.singletonMap(NETTY_HTTP_TRANSPORT_NAME,
        () -> new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry, dispatcher));
}
项目:elasticsearch_my    文件:RemoteRequestBuilders.java   
static HttpEntity initialSearchEntity(SearchRequest searchRequest, BytesReference query) {
    // EMPTY is safe here because we're not calling namedObject
    try (XContentBuilder entity = JsonXContent.contentBuilder();
            XContentParser queryParser = XContentHelper.createParser(NamedXContentRegistry.EMPTY, query)) {
        entity.startObject();

        entity.field("query"); {
            /* We're intentionally a bit paranoid here - copying the query as xcontent rather than writing a raw field. We don't want
             * poorly written queries to escape. Ever. */
            entity.copyCurrentStructure(queryParser);
            XContentParser.Token shouldBeEof = queryParser.nextToken();
            if (shouldBeEof != null) {
                throw new ElasticsearchException(
                        "query was more than a single object. This first token after the object is [" + shouldBeEof + "]");
            }
        }

        if (searchRequest.source().fetchSource() != null) {
            entity.field("_source", searchRequest.source().fetchSource());
        } else {
            entity.field("_source", true);
        }

        entity.endObject();
        BytesRef bytes = entity.bytes().toBytesRef();
        return new ByteArrayEntity(bytes.bytes, bytes.offset, bytes.length, ContentType.APPLICATION_JSON);
    } catch (IOException e) {
        throw new ElasticsearchException("unexpected error building entity", e);
    }
}
项目:elasticsearch_my    文件:RestControllerTests.java   
public void testDispatchBadRequest() {
    final FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).build();
    final AssertingChannel channel = new AssertingChannel(fakeRestRequest, true, RestStatus.BAD_REQUEST);
    restController.dispatchBadRequest(
            fakeRestRequest,
            channel,
            new ThreadContext(Settings.EMPTY),
            randomBoolean() ? new IllegalStateException("bad request") : new Throwable("bad request"));
    assertTrue(channel.getSendResponseCalled());
    assertThat(channel.getRestResponse().content().utf8ToString(), containsString("bad request"));
}
项目:elasticsearch_my    文件:URLRepositoryTests.java   
public void testWhiteListingRepoURL() throws IOException {
    String repoPath = createTempDir().resolve("repository").toUri().toURL().toString();
    Settings baseSettings = Settings.builder()
        .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString())
        .put(URLRepository.ALLOWED_URLS_SETTING.getKey(), repoPath)
        .put(URLRepository.REPOSITORIES_URL_SETTING.getKey(), repoPath)
        .build();
    RepositoryMetaData repositoryMetaData = new RepositoryMetaData("url", URLRepository.TYPE, baseSettings);
    new URLRepository(repositoryMetaData, new Environment(baseSettings), new NamedXContentRegistry(Collections.emptyList()));
}
项目:elasticsearch_my    文件:MetaDataStateFormatTests.java   
public void testCorruption() throws IOException {
    Path[] dirs = new Path[randomIntBetween(1, 5)];
    for (int i = 0; i < dirs.length; i++) {
        dirs[i] = createTempDir();
    }
    final long id = addDummyFiles("foo-", dirs);
    Format format = new Format(randomFrom(XContentType.values()), "foo-");
    DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean());
    int version = between(0, Integer.MAX_VALUE/2);
    format.write(state, dirs);
    for (Path file : dirs) {
        Path[] list = content("*", file);
        assertEquals(list.length, 1);
        assertThat(list[0].getFileName().toString(), equalTo(MetaDataStateFormat.STATE_DIR_NAME));
        Path stateDir = list[0];
        assertThat(Files.isDirectory(stateDir), is(true));
        list = content("foo-*", stateDir);
        assertEquals(list.length, 1);
        assertThat(list[0].getFileName().toString(), equalTo("foo-" + id + ".st"));
        DummyState read = format.read(NamedXContentRegistry.EMPTY, list[0]);
        assertThat(read, equalTo(state));
        // now corrupt it
        corruptFile(list[0], logger);
        try {
            format.read(NamedXContentRegistry.EMPTY, list[0]);
            fail("corrupted file");
        } catch (CorruptStateException ex) {
            // expected
        }
    }
}
项目:elasticsearch_my    文件:RestHighLevelClient.java   
/**
 * Creates a {@link RestHighLevelClient} given the low level {@link RestClient} that it should use to perform requests and
 * a list of entries that allow to parse custom response sections added to Elasticsearch through plugins.
 */
protected RestHighLevelClient(RestClient restClient, List<NamedXContentRegistry.Entry> namedXContentEntries) {
    this.client = Objects.requireNonNull(restClient);
    this.registry = new NamedXContentRegistry(Stream.of(
            getNamedXContents().stream(),
            namedXContentEntries.stream()
    ).flatMap(Function.identity()).collect(toList()));
}
项目:elasticsearch_my    文件:TransportGetTaskAction.java   
@Inject
public TransportGetTaskAction(Settings settings, ThreadPool threadPool, TransportService transportService, ActionFilters actionFilters,
        IndexNameExpressionResolver indexNameExpressionResolver, ClusterService clusterService, Client client,
        NamedXContentRegistry xContentRegistry) {
    super(settings, GetTaskAction.NAME, threadPool, transportService, actionFilters, indexNameExpressionResolver, GetTaskRequest::new);
    this.clusterService = clusterService;
    this.transportService = transportService;
    this.client = client;
    this.xContentRegistry = xContentRegistry;
}
项目:elasticsearch_my    文件:AbstractSearchTestCase.java   
public void setUp() throws Exception {
    super.setUp();
    IndicesModule indicesModule = new IndicesModule(Collections.emptyList());
    searchExtPlugin = new TestSearchExtPlugin();
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.singletonList(searchExtPlugin));
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.addAll(indicesModule.getNamedWriteables());
    entries.addAll(searchModule.getNamedWriteables());
    namedWriteableRegistry = new NamedWriteableRegistry(entries);
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
项目:elasticsearch_my    文件:ESIntegTestCase.java   
@Override
protected NamedXContentRegistry xContentRegistry() {
    if (isInternalCluster() && cluster().size() > 0) {
        // If it's internal cluster - using existing registry in case plugin registered custom data
        return internalCluster().getInstance(NamedXContentRegistry.class);
    } else {
        // If it's external cluster - fall back to the standard set
        return new NamedXContentRegistry(ClusterModule.getNamedXWriteables());
    }
}
项目:elasticsearch_my    文件:SuggestBuilderTests.java   
/**
 * Setup for the whole base test class.
 */
@BeforeClass
public static void init() {
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
    namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
项目:elasticsearch_my    文件:FakeRestRequest.java   
private FakeRestRequest(NamedXContentRegistry xContentRegistry, Map<String, List<String>> headers, Map<String, String> params,
                        BytesReference content, Method method, String path, SocketAddress remoteAddress) {
    super(xContentRegistry, params, path, headers);
    this.content = content;
    this.method = method;
    this.remoteAddress = remoteAddress;
}
项目:elasticsearch_my    文件:QueryRescoreBuilderTests.java   
/**
 * setup for the whole base test class
 */
@BeforeClass
public static void init() {
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
    namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
项目:elasticsearch_my    文件:IndicesService.java   
public IndicesService(Settings settings, PluginsService pluginsService, NodeEnvironment nodeEnv, NamedXContentRegistry xContentRegistry,
                      ClusterSettings clusterSettings, AnalysisRegistry analysisRegistry,
                      IndexNameExpressionResolver indexNameExpressionResolver,
                      MapperRegistry mapperRegistry, NamedWriteableRegistry namedWriteableRegistry,
                      ThreadPool threadPool, IndexScopedSettings indexScopedSettings, CircuitBreakerService circuitBreakerService,
                      BigArrays bigArrays, ScriptService scriptService, ClusterService clusterService, Client client,
                      MetaStateService metaStateService) {
    super(settings);
    this.threadPool = threadPool;
    this.pluginsService = pluginsService;
    this.nodeEnv = nodeEnv;
    this.xContentRegistry = xContentRegistry;
    this.shardsClosedTimeout = settings.getAsTime(INDICES_SHARDS_CLOSED_TIMEOUT, new TimeValue(1, TimeUnit.DAYS));
    this.analysisRegistry = analysisRegistry;
    this.indexNameExpressionResolver = indexNameExpressionResolver;
    this.indicesRequestCache = new IndicesRequestCache(settings);
    this.indicesQueryCache = new IndicesQueryCache(settings);
    this.mapperRegistry = mapperRegistry;
    this.namedWriteableRegistry = namedWriteableRegistry;
    indexingMemoryController = new IndexingMemoryController(settings, threadPool,
                                                            // ensure we pull an iter with new shards - flatten makes a copy
                                                            () -> Iterables.flatten(this).iterator());
    this.indexScopeSetting = indexScopedSettings;
    this.circuitBreakerService = circuitBreakerService;
    this.bigArrays = bigArrays;
    this.scriptService = scriptService;
    this.clusterService = clusterService;
    this.client = client;
    this.indicesFieldDataCache = new IndicesFieldDataCache(settings, new IndexFieldDataCache.Listener() {
        @Override
        public void onRemoval(ShardId shardId, String fieldName, boolean wasEvicted, long sizeInBytes) {
            assert sizeInBytes >= 0 : "When reducing circuit breaker, it should be adjusted with a number higher or equal to 0 and not [" + sizeInBytes + "]";
            circuitBreakerService.getBreaker(CircuitBreaker.FIELDDATA).addWithoutBreaking(-sizeInBytes);
        }
    });
    this.cleanInterval = INDICES_CACHE_CLEAN_INTERVAL_SETTING.get(settings);
    this.cacheCleaner = new CacheCleaner(indicesFieldDataCache, indicesRequestCache,  logger, threadPool, this.cleanInterval);
    this.metaStateService = metaStateService;
}
项目:elasticsearch_my    文件:AbstractSuggestionBuilderTestCase.java   
/**
 * setup for the whole base test class
 */
@BeforeClass
public static void init() throws IOException {
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, emptyList());
    namedWriteableRegistry = new NamedWriteableRegistry(searchModule.getNamedWriteables());
    xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents());
}
项目:elasticsearch_my    文件:BlobStoreRepository.java   
/**
 * Constructs new BlobStoreRepository
 *
 * @param metadata       The metadata for this repository including name and settings
 * @param globalSettings Settings for the node this repository object is created on
 */
protected BlobStoreRepository(RepositoryMetaData metadata, Settings globalSettings, NamedXContentRegistry namedXContentRegistry) {
    super(globalSettings);
    this.metadata = metadata;
    this.namedXContentRegistry = namedXContentRegistry;
    snapshotRateLimiter = getRateLimiter(metadata.settings(), "max_snapshot_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB));
    restoreRateLimiter = getRateLimiter(metadata.settings(), "max_restore_bytes_per_sec", new ByteSizeValue(40, ByteSizeUnit.MB));
    readOnly = metadata.settings().getAsBoolean("readonly", false);

    indexShardSnapshotFormat = new ChecksumBlobStoreFormat<>(SNAPSHOT_CODEC, SNAPSHOT_NAME_FORMAT,
        BlobStoreIndexShardSnapshot::fromXContent, namedXContentRegistry, isCompress());
    indexShardSnapshotsFormat = new ChecksumBlobStoreFormat<>(SNAPSHOT_INDEX_CODEC, SNAPSHOT_INDEX_NAME_FORMAT,
        BlobStoreIndexShardSnapshots::fromXContent, namedXContentRegistry, isCompress());
}
项目:elasticsearch_my    文件:BlobStoreFormat.java   
/**
 * @param blobNameFormat format of the blobname in {@link String#format(Locale, String, Object...)} format
 * @param reader the prototype object that can deserialize objects with type T
 */
protected BlobStoreFormat(String blobNameFormat, CheckedFunction<XContentParser, T, IOException> reader,
        NamedXContentRegistry namedXContentRegistry) {
    this.reader = reader;
    this.blobNameFormat = blobNameFormat;
    this.namedXContentRegistry = namedXContentRegistry;
}
项目:elasticsearch_my    文件:SearchModule.java   
private void registerAggregation(AggregationSpec spec) {
    if (false == transportClient) {
        namedXContents.add(new NamedXContentRegistry.Entry(BaseAggregationBuilder.class, spec.getName(), (p, c) -> {
            AggregatorFactories.AggParseContext context = (AggregatorFactories.AggParseContext) c;
            return spec.getParser().parse(context.name, context.queryParseContext);
        }));
    }
    namedWriteables.add(
            new NamedWriteableRegistry.Entry(AggregationBuilder.class, spec.getName().getPreferredName(), spec.getReader()));
    for (Map.Entry<String, Writeable.Reader<? extends InternalAggregation>> t : spec.getResultReaders().entrySet()) {
        String writeableName = t.getKey();
        Writeable.Reader<? extends InternalAggregation> internalReader = t.getValue();
        namedWriteables.add(new NamedWriteableRegistry.Entry(InternalAggregation.class, writeableName, internalReader));
    }
}
项目:elasticsearch_my    文件:SuggestTests.java   
static NamedXContentRegistry getSuggestersRegistry() {
    List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>();
    namedXContents.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField("term"),
            (parser, context) -> TermSuggestion.fromXContent(parser, (String)context)));
    namedXContents.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField("phrase"),
            (parser, context) -> PhraseSuggestion.fromXContent(parser, (String)context)));
    namedXContents.add(new NamedXContentRegistry.Entry(Suggest.Suggestion.class, new ParseField("completion"),
            (parser, context) -> CompletionSuggestion.fromXContent(parser, (String)context)));
    return new NamedXContentRegistry(namedXContents);
}
项目:elasticsearch_my    文件:DedicatedClusterSnapshotRestoreIT.java   
private <T extends MetaData.Custom> void registerMetaDataCustom(String name, Writeable.Reader<T> reader,
                                                                Writeable.Reader<NamedDiff> diffReader,
                                                                CheckedFunction<XContentParser, T, IOException> parser) {
    namedWritables.add(new NamedWriteableRegistry.Entry(MetaData.Custom.class, name, reader));
    namedWritables.add(new NamedWriteableRegistry.Entry(NamedDiff.class, name, diffReader));
    namedXContents.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(name), parser));
}
项目:elasticsearch_my    文件:InternalEngineTests.java   
public TranslogHandler(NamedXContentRegistry xContentRegistry, String indexName, Logger logger) {
    super(new ShardId("test", "_na_", 0), null, logger);
    Settings settings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
    Index index = new Index(indexName, "_na_");
    IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
    NamedAnalyzer defaultAnalyzer = new NamedAnalyzer("default", AnalyzerScope.INDEX, new StandardAnalyzer());
    IndexAnalyzers indexAnalyzers = new IndexAnalyzers(indexSettings, defaultAnalyzer, defaultAnalyzer, defaultAnalyzer, Collections.emptyMap(), Collections.emptyMap());
    SimilarityService similarityService = new SimilarityService(indexSettings, Collections.emptyMap());
    MapperRegistry mapperRegistry = new IndicesModule(Collections.emptyList()).getMapperRegistry();
    mapperService = new MapperService(indexSettings, indexAnalyzers, xContentRegistry, similarityService, mapperRegistry,
            () -> null);
}
项目:elasticsearch_my    文件:DecayFunctionBuilder.java   
@Override
protected ScoreFunction doToFunction(QueryShardContext context) throws IOException {
    AbstractDistanceScoreFunction scoreFunction;
    // EMPTY is safe because parseVariable doesn't use namedObject
    try (XContentParser parser = XContentFactory.xContent(functionBytes).createParser(NamedXContentRegistry.EMPTY, functionBytes)) {
        scoreFunction = parseVariable(fieldName, parser, context, multiValueMode);
    }
    return scoreFunction;
}
项目:elasticsearch_my    文件:QueryShardContext.java   
public QueryShardContext(int shardId, IndexSettings indexSettings, BitsetFilterCache bitsetFilterCache,
        IndexFieldDataService indexFieldDataService, MapperService mapperService, SimilarityService similarityService,
        ScriptService scriptService, NamedXContentRegistry xContentRegistry,
        Client client, IndexReader reader, LongSupplier nowInMillis) {
    super(indexSettings, mapperService, scriptService, xContentRegistry, client, reader, nowInMillis);
    this.shardId = shardId;
    this.indexSettings = indexSettings;
    this.similarityService = similarityService;
    this.mapperService = mapperService;
    this.bitsetFilterCache = bitsetFilterCache;
    this.indexFieldDataService = indexFieldDataService;
    this.allowUnmappedFields = indexSettings.isDefaultAllowUnmappedFields();
    this.nestedScope = new NestedScope();

}
项目:elasticsearch_my    文件:QueryRewriteContext.java   
public QueryRewriteContext(IndexSettings indexSettings, MapperService mapperService, ScriptService scriptService,
        NamedXContentRegistry xContentRegistry, Client client, IndexReader reader,
        LongSupplier nowInMillis) {
    this.mapperService = mapperService;
    this.scriptService = scriptService;
    this.indexSettings = indexSettings;
    this.xContentRegistry = xContentRegistry;
    this.client = client;
    this.reader = reader;
    this.nowInMillis = nowInMillis;
}
项目:elasticsearch-indexing-proxy    文件:IndexingProxyPlugin.java   
@Override
public Collection<Object> createComponents(final Client client, final ClusterService clusterService, final ThreadPool threadPool,
        final ResourceWatcherService resourceWatcherService, final ScriptService scriptService,
        final NamedXContentRegistry xContentRegistry) {
    final Collection<Object> components = new ArrayList<>();
    components.add(pluginComponent);
    return components;
}
项目:elasticsearch_my    文件:ShardPath.java   
/**
 * This method walks through the nodes shard paths to find the data and state path for the given shard. If multiple
 * directories with a valid shard state exist the one with the highest version will be used.
 * <b>Note:</b> this method resolves custom data locations for the shard.
 */
public static ShardPath loadShardPath(Logger logger, NodeEnvironment env, ShardId shardId, IndexSettings indexSettings) throws IOException {
    final String indexUUID = indexSettings.getUUID();
    final Path[] paths = env.availableShardPaths(shardId);
    Path loadedPath = null;
    for (Path path : paths) {
        // EMPTY is safe here because we never call namedObject
        ShardStateMetaData load = ShardStateMetaData.FORMAT.loadLatestState(logger, NamedXContentRegistry.EMPTY, path);
        if (load != null) {
            if (load.indexUUID.equals(indexUUID) == false && IndexMetaData.INDEX_UUID_NA_VALUE.equals(load.indexUUID) == false) {
                logger.warn("{} found shard on path: [{}] with a different index UUID - this shard seems to be leftover from a different index with the same name. Remove the leftover shard in order to reuse the path with the current index", shardId, path);
                throw new IllegalStateException(shardId + " index UUID in shard state was: " + load.indexUUID + " expected: " + indexUUID + " on shard path: " + path);
            }
            if (loadedPath == null) {
                loadedPath = path;
            } else{
                throw new IllegalStateException(shardId + " more than one shard state found");
            }
        }

    }
    if (loadedPath == null) {
        return null;
    } else {
        final Path dataPath;
        final Path statePath = loadedPath;
        if (indexSettings.hasCustomDataPath()) {
            dataPath = env.resolveCustomLocation(indexSettings, shardId);
        } else {
            dataPath = statePath;
        }
        logger.debug("{} loaded data path [{}], state path [{}]", shardId, dataPath, statePath);
        return new ShardPath(indexSettings.hasCustomDataPath(), dataPath, statePath, shardId);
    }
}
项目:elasticsearch_my    文件:DocumentMapperParser.java   
public DocumentMapperParser(IndexSettings indexSettings, MapperService mapperService, IndexAnalyzers indexAnalyzers,
                            NamedXContentRegistry xContentRegistry, SimilarityService similarityService, MapperRegistry mapperRegistry,
                            Supplier<QueryShardContext> queryShardContextSupplier) {
    this.mapperService = mapperService;
    this.indexAnalyzers = indexAnalyzers;
    this.xContentRegistry = xContentRegistry;
    this.similarityService = similarityService;
    this.queryShardContextSupplier = queryShardContextSupplier;
    this.typeParsers = mapperRegistry.getMapperParsers();
    this.rootTypeParsers = mapperRegistry.getMetadataMapperParsers();
    indexVersionCreated = indexSettings.getIndexVersionCreated();
}
项目:elasticsearch_my    文件:RestRequest.java   
/**
 * Creates a new RestRequest
 * @param xContentRegistry the xContentRegistry to use when parsing XContent
 * @param params the parameters of the request
 * @param path the path of the request. This should not contain request parameters
 * @param headers a map of the headers. This map should implement a Case-Insensitive hashing for keys as HTTP header names are case
 *                insensitive
 */
public RestRequest(NamedXContentRegistry xContentRegistry, Map<String, String> params, String path, Map<String, List<String>> headers) {
    this.xContentRegistry = xContentRegistry;
    this.params = params;
    this.rawPath = path;
    this.headers = Collections.unmodifiableMap(headers);
    final List<String> contentType = getAllHeaderValues("Content-Type");
    final XContentType xContentType = parseContentType(contentType);
    if (xContentType != null) {
        this.xContentType.set(xContentType);
    }
}
项目:elasticsearch_my    文件:ClusterModule.java   
public static List<NamedXContentRegistry.Entry> getNamedXWriteables() {
    List<NamedXContentRegistry.Entry> entries = new ArrayList<>();
    // Metadata
    entries.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(RepositoriesMetaData.TYPE),
        RepositoriesMetaData::fromXContent));
    entries.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(IngestMetadata.TYPE),
        IngestMetadata::fromXContent));
    entries.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(ScriptMetaData.TYPE),
        ScriptMetaData::fromXContent));
    entries.add(new NamedXContentRegistry.Entry(MetaData.Custom.class, new ParseField(IndexGraveyard.TYPE),
        IndexGraveyard::fromXContent));
    return entries;
}
项目:elasticsearch_my    文件:MetaDataIndexTemplateService.java   
@Inject
public MetaDataIndexTemplateService(Settings settings, ClusterService clusterService,
                                    MetaDataCreateIndexService metaDataCreateIndexService,
                                    AliasValidator aliasValidator, IndicesService indicesService,
                                    IndexScopedSettings indexScopedSettings, NamedXContentRegistry xContentRegistry) {
    super(settings);
    this.clusterService = clusterService;
    this.aliasValidator = aliasValidator;
    this.indicesService = indicesService;
    this.metaDataCreateIndexService = metaDataCreateIndexService;
    this.indexScopedSettings = indexScopedSettings;
    this.xContentRegistry = xContentRegistry;
}
项目:elasticsearch_my    文件:AliasValidator.java   
/**
 * Validates an alias filter by parsing it using the
 * provided {@link org.elasticsearch.index.query.QueryShardContext}
 * @throws IllegalArgumentException if the filter is not valid
 */
public void validateAliasFilter(String alias, byte[] filter, QueryShardContext queryShardContext,
        NamedXContentRegistry xContentRegistry) {
    assert queryShardContext != null;
    try (XContentParser parser = XContentFactory.xContent(filter).createParser(xContentRegistry, filter)) {
        validateAliasFilter(parser, queryShardContext);
    } catch (Exception e) {
        throw new IllegalArgumentException("failed to parse filter for alias [" + alias + "]", e);
    }
}