org.elasticsearch.common.io.stream.NamedWriteableRegistry Java Examples

The following examples show how to use org.elasticsearch.common.io.stream.NamedWriteableRegistry. 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: DiffableTestUtils.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Tests making random changes to an object, calculating diffs for these changes, sending this
 * diffs over the wire and appling these diffs on the other side.
 */
public static <T extends Diffable<T>> void testDiffableSerialization(Supplier<T> testInstance,
                                                                     Function<T, T> modifier,
                                                                     NamedWriteableRegistry namedWriteableRegistry,
                                                                     Reader<T> reader,
                                                                     Reader<Diff<T>> diffReader) throws IOException {
    T remoteInstance = testInstance.get();
    T localInstance = assertSerialization(remoteInstance, namedWriteableRegistry, reader);
    for (int runs = 0; runs < NUMBER_OF_DIFF_TEST_RUNS; runs++) {
        T remoteChanges = modifier.apply(remoteInstance);
        Diff<T> remoteDiffs = remoteChanges.diff(remoteInstance);
        Diff<T> localDiffs = copyInstance(remoteDiffs, namedWriteableRegistry, diffReader);
        localInstance = assertDiffApplication(remoteChanges, localInstance, localDiffs);
        remoteInstance = remoteChanges;
    }
}
 
Example #2
Source File: DynamicRanker.java    From elasticsearch-dynarank with Apache License 2.0 6 votes vote down vote up
@Inject
public DynamicRanker(final Settings settings, final Client client, final ClusterService clusterService,
        final ScriptService scriptService, final ThreadPool threadPool, final ActionFilters filters,
        final NamedWriteableRegistry namedWriteableRegistry) {
    this.client = client;
    this.clusterService = clusterService;
    this.scriptService = scriptService;
    this.threadPool = threadPool;
    this.namedWriteableRegistry = namedWriteableRegistry;

    logger.info("Initializing DynamicRanker");

    final TimeValue expire = SETTING_DYNARANK_CACHE_EXPIRE.get(settings);
    cleanInterval = SETTING_DYNARANK_CACHE_CLEAN_INTERVAL.get(settings);

    final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().concurrencyLevel(16);
    if (expire.millis() >= 0) {
        builder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }
    scriptInfoCache = builder.build();
}
 
Example #3
Source File: Netty4Plugin.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                                                                    CircuitBreakerService circuitBreakerService,
                                                                    NamedWriteableRegistry namedWriteableRegistry,
                                                                    NamedXContentRegistry xContentRegistry,
                                                                    NetworkService networkService,
                                                                    NodeClient nodeClient) {
    return Collections.singletonMap(
        NETTY_HTTP_TRANSPORT_NAME,
        () -> new Netty4HttpServerTransport(
            settings,
            networkService,
            bigArrays,
            threadPool,
            xContentRegistry,
            pipelineRegistry,
            nodeClient
        )
    );
}
 
Example #4
Source File: EnterpriseUsersExtension.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>(4);
    entries.add(new NamedWriteableRegistry.Entry(
        MetaData.Custom.class,
        UsersMetaData.TYPE,
        UsersMetaData::new
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        NamedDiff.class,
        UsersMetaData.TYPE,
        in -> UsersMetaData.readDiffFrom(MetaData.Custom.class, UsersMetaData.TYPE, in)
    ));

    entries.add(new NamedWriteableRegistry.Entry(
        MetaData.Custom.class,
        UsersPrivilegesMetaData.TYPE,
        UsersPrivilegesMetaData::new
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        NamedDiff.class,
        UsersPrivilegesMetaData.TYPE,
        in -> UsersPrivilegesMetaData.readDiffFrom(MetaData.Custom.class, UsersPrivilegesMetaData.TYPE, in)
    ));
    return entries;
}
 
Example #5
Source File: PublicationTransportHandler.java    From crate with Apache License 2.0 6 votes vote down vote up
public PublicationTransportHandler(TransportService transportService, NamedWriteableRegistry namedWriteableRegistry,
                                   Function<PublishRequest, PublishWithJoinResponse> handlePublishRequest,
                                   BiConsumer<ApplyCommitRequest, ActionListener<Void>> handleApplyCommit) {
    this.transportService = transportService;
    this.namedWriteableRegistry = namedWriteableRegistry;
    this.handlePublishRequest = handlePublishRequest;

    transportService.registerRequestHandler(
        PUBLISH_STATE_ACTION_NAME,
        BytesTransportRequest::new,
        ThreadPool.Names.GENERIC,
        false,
        false,
        (request, channel, task) -> channel.sendResponse(handleIncomingPublishRequest(request))
    );

    transportService.registerRequestHandler(
        COMMIT_STATE_ACTION_NAME,
        ThreadPool.Names.GENERIC,
        false,
        false,
        ApplyCommitRequest::new,
        (request, channel, task) -> handleApplyCommit.accept(request, transportCommitCallback(channel))
    );
}
 
Example #6
Source File: Netty4Plugin.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Supplier<Transport>> getTransports(Settings settings,
                                                      ThreadPool threadPool,
                                                      BigArrays bigArrays,
                                                      PageCacheRecycler pageCacheRecycler,
                                                      CircuitBreakerService circuitBreakerService,
                                                      NamedWriteableRegistry namedWriteableRegistry,
                                                      NetworkService networkService) {
    return Collections.singletonMap(
        NETTY_TRANSPORT_NAME,
        () -> new Netty4Transport(
            settings,
            threadPool,
            networkService,
            bigArrays,
            namedWriteableRegistry,
            circuitBreakerService
        )
    );
}
 
Example #7
Source File: LtrQueryParserPlugin.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Object> createComponents(Client client,
                                           ClusterService clusterService,
                                           ThreadPool threadPool,
                                           ResourceWatcherService resourceWatcherService,
                                           ScriptService scriptService,
                                           NamedXContentRegistry xContentRegistry,
                                           Environment environment,
                                           NodeEnvironment nodeEnvironment,
                                           NamedWriteableRegistry namedWriteableRegistry,
                                           IndexNameExpressionResolver indexNameExpressionResolver) {
    clusterService.addListener(event -> {
        for (Index i : event.indicesDeleted()) {
            if (IndexFeatureStore.isIndexStore(i.getName())) {
                caches.evict(i.getName());
            }
        }
    });
    return asList(caches, parserFactory);
}
 
Example #8
Source File: OpenDistroSecuritySSLPlugin.java    From deprecated-security-ssl with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
        CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
        NamedXContentRegistry xContentRegistry, NetworkService networkService, Dispatcher dispatcher) {
    
    final Map<String, Supplier<HttpServerTransport>> httpTransports = new HashMap<String, Supplier<HttpServerTransport>>(1);
    if (!client && httpSSLEnabled) {
        
        final ValidatingDispatcher validatingDispatcher = new ValidatingDispatcher(threadPool.getThreadContext(), dispatcher, settings, configPath, NOOP_SSL_EXCEPTION_HANDLER);
        final OpenDistroSecuritySSLNettyHttpServerTransport sgsnht = new OpenDistroSecuritySSLNettyHttpServerTransport(settings, networkService, bigArrays, threadPool, odsks, xContentRegistry, validatingDispatcher, NOOP_SSL_EXCEPTION_HANDLER);
        
        httpTransports.put("com.amazon.opendistroforelasticsearch.security.ssl.http.netty.OpenDistroSecuritySSLNettyHttpServerTransport", () -> sgsnht);
        
    }
    return httpTransports;
}
 
Example #9
Source File: MockTcpTransport.java    From crate with Apache License 2.0 6 votes vote down vote up
public MockTcpTransport(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                        CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
                        NetworkService networkService, Version mockVersion) {
    super("mock-tcp-transport",
          settings,
          threadPool,
          bigArrays,
          circuitBreakerService,
          namedWriteableRegistry,
          networkService);
    // we have our own crazy cached threadpool this one is not bounded at all...
    // using the ES thread factory here is crucial for tests otherwise disruption tests won't block that thread
    executor = Executors.newCachedThreadPool(EsExecutors.daemonThreadFactory(settings,
                                                                             Transports.TEST_MOCK_TRANSPORT_THREAD_PREFIX));
    this.mockVersion = mockVersion;
}
 
Example #10
Source File: AzureDiscoveryPlugin.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Object> createComponents(Client client,
                                           ClusterService clusterService,
                                           ThreadPool threadPool,
                                           NamedXContentRegistry xContentRegistry,
                                           Environment environment,
                                           NodeEnvironment nodeEnvironment,
                                           NamedWriteableRegistry namedWriteableRegistry) {
    if (AzureConfiguration.isDiscoveryReady(settings, logger)) {
        return Collections.singletonList(azureComputeService());
    }
    return Collections.emptyList();
}
 
Example #11
Source File: Coordinator.java    From crate with Apache License 2.0 5 votes vote down vote up
public Coordinator(String nodeName, Settings settings, ClusterSettings clusterSettings, TransportService transportService,
                   NamedWriteableRegistry namedWriteableRegistry, AllocationService allocationService, MasterService masterService,
                   Supplier<CoordinationState.PersistedState> persistedStateSupplier, SeedHostsProvider seedHostsProvider,
                   ClusterApplier clusterApplier, Collection<BiConsumer<DiscoveryNode, ClusterState>> onJoinValidators, Random random) {
    this.settings = settings;
    this.transportService = transportService;
    this.masterService = masterService;
    this.allocationService = allocationService;
    this.onJoinValidators = JoinTaskExecutor.addBuiltInJoinValidators(onJoinValidators);
    this.singleNodeDiscovery = DiscoveryModule.SINGLE_NODE_DISCOVERY_TYPE.equals(DiscoveryModule.DISCOVERY_TYPE_SETTING.get(settings));
    this.joinHelper = new JoinHelper(settings, allocationService, masterService, transportService,
        this::getCurrentTerm, this::getStateForMasterService, this::handleJoinRequest, this::joinLeaderInTerm, this.onJoinValidators);
    this.persistedStateSupplier = persistedStateSupplier;
    this.noMasterBlockService = new NoMasterBlockService(settings, clusterSettings);
    this.lastKnownLeader = Optional.empty();
    this.lastJoin = Optional.empty();
    this.joinAccumulator = new InitialJoinAccumulator();
    this.publishTimeout = PUBLISH_TIMEOUT_SETTING.get(settings);
    this.random = random;
    this.electionSchedulerFactory = new ElectionSchedulerFactory(settings, random, transportService.getThreadPool());
    this.preVoteCollector = new PreVoteCollector(transportService, this::startElection, this::updateMaxTermSeen);
    configuredHostsResolver = new SeedHostsResolver(nodeName, settings, transportService, seedHostsProvider);
    this.peerFinder = new CoordinatorPeerFinder(settings, transportService,
        new HandshakingTransportAddressConnector(settings, transportService), configuredHostsResolver);
    this.publicationHandler = new PublicationTransportHandler(transportService, namedWriteableRegistry,
        this::handlePublishRequest, this::handleApplyCommit);
    this.leaderChecker = new LeaderChecker(settings, transportService, getOnLeaderFailure());
    this.followersChecker = new FollowersChecker(settings, transportService, this::onFollowerCheckRequest, this::removeNode);
    this.nodeRemovalExecutor = new NodeRemovalClusterStateTaskExecutor(allocationService, LOGGER);
    this.clusterApplier = clusterApplier;
    masterService.setClusterStateSupplier(this::getStateForMasterService);
    this.reconfigurator = new Reconfigurator(settings, clusterSettings);
    this.clusterBootstrapService = new ClusterBootstrapService(settings, transportService, this::getFoundPeers,
        this::isInitialConfigurationSet, this::setInitialConfiguration);
    this.lagDetector = new LagDetector(settings, transportService.getThreadPool(), n -> removeNode(n, "lagging"),
        transportService::getLocalNode);
    this.clusterFormationFailureHelper = new ClusterFormationFailureHelper(settings, this::getClusterFormationState,
        transportService.getThreadPool(), joinHelper::logLastFailedJoinAttempt);
}
 
Example #12
Source File: TcpTransport.java    From crate with Apache License 2.0 5 votes vote down vote up
public TcpTransport(String transportName, Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                    CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
                    NetworkService networkService) {
    this.settings = settings;
    this.profileSettings = getProfileSettings(settings);
    this.threadPool = threadPool;
    this.bigArrays = bigArrays;
    this.circuitBreakerService = circuitBreakerService;
    this.namedWriteableRegistry = namedWriteableRegistry;
    this.compress = Transport.TRANSPORT_TCP_COMPRESS.get(settings);
    this.networkService = networkService;
    this.transportName = transportName;
    this.nodeName = Node.NODE_NAME_SETTING.get(settings);
    final Settings defaultFeatures = DEFAULT_FEATURES_SETTING.get(settings);
    if (defaultFeatures == null) {
        this.features = new String[0];
    } else {
        defaultFeatures.names().forEach(key -> {
            if (Booleans.parseBoolean(defaultFeatures.get(key)) == false) {
                throw new IllegalArgumentException("feature settings must have default [true] value");
            }
        });
        // use a sorted set to present the features in a consistent order
        this.features = new TreeSet<>(defaultFeatures.names()).toArray(new String[defaultFeatures.names().size()]);
    }

    try (BytesStreamOutput out = new BytesStreamOutput()) {
        out.writeByte((byte) 'E');
        out.writeByte((byte) 'S');
        out.writeInt(TcpTransport.PING_DATA_SIZE);
        pingMessage = out.bytes();
    } catch (IOException e) {
        throw new AssertionError(e.getMessage(), e); // won't happen
    }
}
 
Example #13
Source File: Netty4Plugin.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Object> createComponents(Client client,
                                           ClusterService clusterService,
                                           ThreadPool threadPool,
                                           NamedXContentRegistry xContentRegistry,
                                           Environment environment,
                                           NodeEnvironment nodeEnvironment,
                                           NamedWriteableRegistry namedWriteableRegistry) {
    // pipelineRegistry is returned here so that it's bound in guice and can be injected in other places
    return Collections.singletonList(pipelineRegistry);
}
 
Example #14
Source File: OpenDistroSecuritySSLPlugin.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<Object> createComponents(Client localClient, ClusterService clusterService, ThreadPool threadPool,
        ResourceWatcherService resourceWatcherService, ScriptService scriptService, NamedXContentRegistry xContentRegistry,
        Environment environment, NodeEnvironment nodeEnvironment, NamedWriteableRegistry namedWriteableRegistry) {

    final List<Object> components = new ArrayList<>(1);
    
    if(client) {
        return components;
    }
    
    final String principalExtractorClass = settings.get(SSLConfigConstants.OPENDISTRO_SECURITY_SSL_TRANSPORT_PRINCIPAL_EXTRACTOR_CLASS, null);

    if(principalExtractorClass == null) {
        principalExtractor = new com.amazon.opendistroforelasticsearch.security.ssl.transport.DefaultPrincipalExtractor();
    } else {
        try {
            log.debug("Try to load and instantiate '{}'", principalExtractorClass);
            Class<?> principalExtractorClazz = Class.forName(principalExtractorClass);
            principalExtractor = (PrincipalExtractor) principalExtractorClazz.newInstance();
        } catch (Exception e) {
            log.error("Unable to load '{}' due to", principalExtractorClass, e);
            throw new ElasticsearchException(e);
        }
    }
    
    components.add(principalExtractor);
    
    return components;
}
 
Example #15
Source File: OpenDistroSecuritySSLNettyTransport.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
public OpenDistroSecuritySSLNettyTransport(final Settings settings, final Version version, final ThreadPool threadPool, final NetworkService networkService,
    final PageCacheRecycler pageCacheRecycler, final NamedWriteableRegistry namedWriteableRegistry,
    final CircuitBreakerService circuitBreakerService, final OpenDistroSecurityKeyStore odks, final SslExceptionHandler errorHandler) {
    super(settings, version, threadPool, networkService, pageCacheRecycler, namedWriteableRegistry, circuitBreakerService);
    this.odks = odks;
    this.errorHandler = errorHandler;
}
 
Example #16
Source File: EnterpriseLicenseExtension.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.add(new NamedWriteableRegistry.Entry(
        MetaData.Custom.class,
        LicenseKey.WRITEABLE_TYPE,
        LicenseKey::new
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        NamedDiff.class,
        LicenseKey.WRITEABLE_TYPE,
        in -> LicenseKey.readDiffFrom(MetaData.Custom.class, LicenseKey.WRITEABLE_TYPE, in)
    ));
    return entries;
}
 
Example #17
Source File: TransportModule.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public TransportModule(Settings settings, NamedWriteableRegistry namedWriteableRegistry) {
    this.settings = settings;
    this.logger = Loggers.getLogger(getClass(), settings);
    addTransport(LOCAL_TRANSPORT, LocalTransport.class);
    addTransport(NETTY_TRANSPORT, NettyTransport.class);
    this.namedWriteableRegistry = namedWriteableRegistry;
}
 
Example #18
Source File: LocalTransport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public LocalTransport(Settings settings, ThreadPool threadPool, Version version, NamedWriteableRegistry namedWriteableRegistry) {
    super(settings);
    this.threadPool = threadPool;
    this.version = version;
    int workerCount = this.settings.getAsInt(TRANSPORT_LOCAL_WORKERS, EsExecutors.boundedNumberOfProcessors(settings));
    int queueSize = this.settings.getAsInt(TRANSPORT_LOCAL_QUEUE, -1);
    logger.debug("creating [{}] workers, queue_size [{}]", workerCount, queueSize);
    final ThreadFactory threadFactory = EsExecutors.daemonThreadFactory(this.settings, LOCAL_TRANSPORT_THREAD_NAME_PREFIX);
    this.workers = EsExecutors.newFixed(LOCAL_TRANSPORT_THREAD_NAME_PREFIX, workerCount, queueSize, threadFactory);
    this.namedWriteableRegistry = namedWriteableRegistry;
}
 
Example #19
Source File: DiffableTestUtils.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Simulates sending diffs over the wire
 */
public static <T extends Writeable> T copyInstance(T diffs, NamedWriteableRegistry namedWriteableRegistry,
                                                              Reader<T> reader) throws IOException {
    try (BytesStreamOutput output = new BytesStreamOutput()) {
        diffs.writeTo(output);
        try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
            return reader.read(in);
        }
    }
}
 
Example #20
Source File: DiffableTestUtils.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that testInstance can be correctly.
 */
public static  <T extends Writeable> T assertSerialization(T testInstance, NamedWriteableRegistry namedWriteableRegistry,
                                                      Reader<T> reader) throws IOException {
    T deserializedInstance = copyInstance(testInstance, namedWriteableRegistry, reader);
    assertEquals(testInstance, deserializedInstance);
    assertEquals(testInstance.hashCode(), deserializedInstance.hashCode());
    assertNotSame(testInstance, deserializedInstance);
    return deserializedInstance;
}
 
Example #21
Source File: MockTransportService.java    From crate with Apache License 2.0 5 votes vote down vote up
public static MockTcpTransport newMockTransport(Settings settings, Version version, ThreadPool threadPool) {
    // some tests use MockTransportService to do network based testing. Yet, we run tests in multiple JVMs that means
    // concurrent tests could claim port that another JVM just released and if that test tries to simulate a disconnect it might
    // be smart enough to re-connect depending on what is tested. To reduce the risk, since this is very hard to debug we use
    // a different default port range per JVM unless the incoming settings override it
    int basePort = 10300 + (JVM_ORDINAL * 100); // use a non-default port otherwise some cluster in this JVM might reuse a port
    settings = Settings.builder().put(TransportSettings.PORT.getKey(), basePort + "-" + (basePort + 100)).put(settings).build();
    NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry(ClusterModule.getNamedWriteables());
    return new MockTcpTransport(settings, threadPool, BigArrays.NON_RECYCLING_INSTANCE,
        new NoneCircuitBreakerService(), namedWriteableRegistry, new NetworkService(Collections.emptyList()), version);
}
 
Example #22
Source File: ESTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
protected static <T> T copyInstance(T original, NamedWriteableRegistry namedWriteableRegistry, Writeable.Writer<T> writer,
                                  Writeable.Reader<T> reader, Version version) throws IOException {
    try (BytesStreamOutput output = new BytesStreamOutput()) {
        output.setVersion(version);
        writer.write(output, original);
        try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
            in.setVersion(version);
            return reader.read(in);
        }
    }
}
 
Example #23
Source File: NetworkPlugin.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map of {@link Transport} suppliers.
 * See {@link org.elasticsearch.common.network.NetworkModule#TRANSPORT_TYPE_KEY} to configure a specific implementation.
 */
default Map<String, Supplier<Transport>> getTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                                                       PageCacheRecycler pageCacheRecycler,
                                                       CircuitBreakerService circuitBreakerService,
                                                       NamedWriteableRegistry namedWriteableRegistry,
                                                       NetworkService networkService) {
    return Collections.emptyMap();
}
 
Example #24
Source File: NetworkPlugin.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map of {@link HttpServerTransport} suppliers.
 * See {@link org.elasticsearch.common.network.NetworkModule#HTTP_TYPE_SETTING} to configure a specific implementation.
 */
default Map<String, Supplier<HttpServerTransport>> getHttpTransports(Settings settings,
                                                                     ThreadPool threadPool,
                                                                     BigArrays bigArrays,
                                                                     CircuitBreakerService circuitBreakerService,
                                                                     NamedWriteableRegistry namedWriteableRegistry,
                                                                     NamedXContentRegistry xContentRegistry,
                                                                     NetworkService networkService,
                                                                     NodeClient nodeClient) {
    return Collections.emptyMap();
}
 
Example #25
Source File: SQLPlugin.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
    List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
    entries.add(new NamedWriteableRegistry.Entry(
        MetaData.Custom.class,
        UserDefinedFunctionsMetaData.TYPE,
        UserDefinedFunctionsMetaData::new
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        MetaData.Custom.class,
        ViewsMetaData.TYPE,
        ViewsMetaData::new
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        NamedDiff.class,
        UserDefinedFunctionsMetaData.TYPE,
        in -> UserDefinedFunctionsMetaData.readDiffFrom(MetaData.Custom.class, UserDefinedFunctionsMetaData.TYPE, in)
    ));
    entries.add(new NamedWriteableRegistry.Entry(
        NamedDiff.class,
        ViewsMetaData.TYPE,
        in -> ViewsMetaData.readDiffFrom(MetaData.Custom.class, ViewsMetaData.TYPE, in)
    ));
    if (userExtension != null) {
        entries.addAll(userExtension.getNamedWriteables());
    }
    if (licenseExtension != null) {
        entries.addAll(licenseExtension.getNamedWriteables());
    }
    return entries;
}
 
Example #26
Source File: ESIntegTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry) {
    return Arrays.asList(new TransportInterceptor() {
        @Override
        public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor,
                                                                                        boolean forceExecution,
                                                                                        TransportRequestHandler<T> actualHandler) {
            if (TransportService.isValidActionName(action) == false) {
                throw new IllegalArgumentException("invalid action name [" + action + "] must start with one of: " +
                    TransportService.VALID_ACTION_PREFIXES );
            }
            return actualHandler;
        }
    });
}
 
Example #27
Source File: CoordinationMetaDataTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testCoordinationMetaDataSerializationEqualsHashCode() {
    CoordinationMetaData initialMetaData = new CoordinationMetaData(randomNonNegativeLong(), randomVotingConfig(), randomVotingConfig(),
            randomVotingTombstones());
    // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type
    EqualsHashCodeTestUtils.checkEqualsAndHashCode(initialMetaData,
            (CopyFunction<CoordinationMetaData>) orig -> ESTestCase.copyWriteable(orig,
                    new NamedWriteableRegistry(Collections.emptyList()), CoordinationMetaData::new),
        meta -> {
            CoordinationMetaData.Builder builder = CoordinationMetaData.builder(meta);
            switch (randomInt(3)) {
                case 0:
                    builder.term(randomValueOtherThan(meta.term(), ESTestCase::randomNonNegativeLong));
                    break;
                case 1:
                    builder.lastCommittedConfiguration(randomlyChangeVotingConfiguration(meta.getLastCommittedConfiguration()));
                    break;
                case 2:
                    builder.lastAcceptedConfiguration(randomlyChangeVotingConfiguration(meta.getLastAcceptedConfiguration()));
                    break;
                case 3:
                    if (meta.getVotingConfigExclusions().isEmpty() == false && randomBoolean()) {
                        builder.clearVotingConfigExclusions();
                    } else {
                        randomVotingTombstones().forEach(dn -> builder.addVotingConfigExclusion(dn));
                    }
                    break;
            }
            return builder.build();
        });
}
 
Example #28
Source File: MockTcpTransportPlugin.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Supplier<Transport>> getTransports(Settings settings, ThreadPool threadPool, BigArrays bigArrays,
                                                      PageCacheRecycler pageCacheRecycler,
                                                      CircuitBreakerService circuitBreakerService,
                                                      NamedWriteableRegistry namedWriteableRegistry,
                                                      NetworkService networkService) {
    return Collections.singletonMap(MOCK_TCP_TRANSPORT_NAME,
        () -> new MockTcpTransport(settings, threadPool, bigArrays, circuitBreakerService, namedWriteableRegistry, networkService));
}
 
Example #29
Source File: CoordinationMetaDataTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testVotingConfigurationSerializationEqualsHashCode() {
    VotingConfiguration initialConfig = randomVotingConfig();
    // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type
    EqualsHashCodeTestUtils.checkEqualsAndHashCode(initialConfig,
            (CopyFunction<VotingConfiguration>) orig -> ESTestCase.copyWriteable(orig,
                    new NamedWriteableRegistry(Collections.emptyList()), VotingConfiguration::new),
            cfg -> randomlyChangeVotingConfiguration(cfg));
}
 
Example #30
Source File: CoordinationMetaDataTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testVotingTombstoneSerializationEqualsHashCode() {
    VotingConfigExclusion tombstone = new VotingConfigExclusion(randomAlphaOfLength(10), randomAlphaOfLength(10));
    // Note: the explicit cast of the CopyFunction is needed for some IDE (specifically Eclipse 4.8.0) to infer the right type
    EqualsHashCodeTestUtils.checkEqualsAndHashCode(tombstone,
            (CopyFunction<VotingConfigExclusion>) orig -> ESTestCase.copyWriteable(orig,
                    new NamedWriteableRegistry(Collections.emptyList()), VotingConfigExclusion::new),
            orig -> randomlyChangeVotingTombstone(orig));
}