• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Java ThreadContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中org.elasticsearch.common.util.concurrent.ThreadContext的典型用法代码示例。如果您正苦于以下问题:Java ThreadContext类的具体用法?Java ThreadContext怎么用?Java ThreadContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ThreadContext类属于org.elasticsearch.common.util.concurrent包,在下文中一共展示了ThreadContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: resetDeprecationLogger

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * Reset the deprecation logger by removing the current thread context, and setting a new thread context if {@code setNewThreadContext}
 * is set to {@code true} and otherwise clearing the current thread context.
 *
 * @param setNewThreadContext whether or not to attach a new thread context to the deprecation logger
 */
private void resetDeprecationLogger(final boolean setNewThreadContext) {
    // "clear" current warning headers by setting a new ThreadContext
    DeprecationLogger.removeThreadContext(this.threadContext);
    try {
        this.threadContext.close();
        // catch IOException to avoid that call sites have to deal with it. It is only declared because this class implements Closeable
        // but it is impossible that this implementation will ever throw an IOException.
    } catch (IOException ex) {
        throw new AssertionError("IOException thrown while closing deprecation logger's thread context", ex);
    }
    if (setNewThreadContext) {
        this.threadContext = new ThreadContext(Settings.EMPTY);
        DeprecationLogger.setThreadContext(this.threadContext);
    } else {
        this.threadContext = null;
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:24,代码来源:ESTestCase.java


示例2: deprecated

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * Logs a deprecated message to the deprecation log, as well as to the local {@link ThreadContext}.
 *
 * @param threadContexts The node's {@link ThreadContext} (outside of concurrent tests, this should only ever have one context).
 * @param message The deprecation message.
 * @param params The parameters used to fill in the message, if any exist.
 */
@SuppressLoggerChecks(reason = "safely delegates to logger")
void deprecated(final Set<ThreadContext> threadContexts, final String message, final Object... params) {
    final Iterator<ThreadContext> iterator = threadContexts.iterator();

    if (iterator.hasNext()) {
        final String formattedMessage = LoggerMessageFormat.format(message, params);
        final String warningHeaderValue = formatWarning(formattedMessage);
        assert WARNING_HEADER_PATTERN.matcher(warningHeaderValue).matches();
        assert extractWarningValueFromWarningHeader(warningHeaderValue).equals(escape(formattedMessage));
        while (iterator.hasNext()) {
            try {
                final ThreadContext next = iterator.next();
                next.addResponseHeader("Warning", warningHeaderValue, DeprecationLogger::extractWarningValueFromWarningHeader);
            } catch (final IllegalStateException e) {
                // ignored; it should be removed shortly
            }
        }
        logger.warn(formattedMessage);
    } else {
        logger.warn(message, params);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:30,代码来源:DeprecationLogger.java


示例3: getTransportInterceptors

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
@Override
public List<TransportInterceptor> getTransportInterceptors(NamedWriteableRegistry namedWriteableRegistry,
                                                           ThreadContext threadContext) {
    return Collections.singletonList(new TransportInterceptor() {
        @Override
        public <T extends TransportRequest> TransportRequestHandler<T> interceptHandler(String action, String executor,
                                                                                    boolean forceExecution,
                                                                                    TransportRequestHandler<T> actualHandler) {
            return instance.interceptHandler(action, executor, forceExecution, actualHandler);
        }

        @Override
        public AsyncSender interceptSender(AsyncSender sender) {
            return instance.interceptSender(sender);
        }
    });
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:18,代码来源:TransportClientHeadersTests.java


示例4: testApplyRelevantHeaders

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public void testApplyRelevantHeaders() throws Exception {
    final ThreadContext threadContext = new ThreadContext(Settings.EMPTY);
    Set<String> headers = new HashSet<>(Arrays.asList("header.1", "header.2"));
    final RestController restController = new RestController(Settings.EMPTY, headers, null, null, circuitBreakerService);
    Map<String, List<String>> restHeaders = new HashMap<>();
    restHeaders.put("header.1", Collections.singletonList("true"));
    restHeaders.put("header.2", Collections.singletonList("true"));
    restHeaders.put("header.3", Collections.singletonList("false"));
    restController.dispatchRequest(new FakeRestRequest.Builder(xContentRegistry()).withHeaders(restHeaders).build(), null, null,
        threadContext, (RestRequest request, RestChannel channel, NodeClient client) -> {
            assertEquals("true", threadContext.getHeader("header.1"));
            assertEquals("true", threadContext.getHeader("header.2"));
            assertNull(threadContext.getHeader("header.3"));
        });
    // the rest controller relies on the caller to stash the context, so we should expect these values here as we didn't stash the
    // context in this test
    assertEquals("true", threadContext.getHeader("header.1"));
    assertEquals("true", threadContext.getHeader("header.2"));
    assertNull(threadContext.getHeader("header.3"));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:21,代码来源:RestControllerTests.java


示例5: testAddsHeaderWithThreadContext

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public void testAddsHeaderWithThreadContext() throws IOException {
    try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
        final Set<ThreadContext> threadContexts = Collections.singleton(threadContext);

        final String param = randomAsciiOfLengthBetween(1, 5);
        logger.deprecated(threadContexts, "A simple message [{}]", param);

        final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders();

        assertThat(responseHeaders.size(), equalTo(1));
        final List<String> responses = responseHeaders.get("Warning");
        assertThat(responses, hasSize(1));
        assertThat(responses.get(0), warningValueMatcher);
        assertThat(responses.get(0), containsString("\"A simple message [" + param + "]\""));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:DeprecationLoggerTests.java


示例6: testAddsCombinedHeaderWithThreadContext

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public void testAddsCombinedHeaderWithThreadContext() throws IOException {
    try (ThreadContext threadContext = new ThreadContext(Settings.EMPTY)) {
        final Set<ThreadContext> threadContexts = Collections.singleton(threadContext);

        final String param = randomAsciiOfLengthBetween(1, 5);
        logger.deprecated(threadContexts, "A simple message [{}]", param);
        final String second = randomAsciiOfLengthBetween(1, 10);
        logger.deprecated(threadContexts, second);

        final Map<String, List<String>> responseHeaders = threadContext.getResponseHeaders();

        assertEquals(1, responseHeaders.size());

        final List<String> responses = responseHeaders.get("Warning");

        assertEquals(2, responses.size());
        assertThat(responses.get(0), warningValueMatcher);
        assertThat(responses.get(0), containsString("\"A simple message [" + param + "]\""));
        assertThat(responses.get(1), warningValueMatcher);
        assertThat(responses.get(1), containsString("\"" + second + "\""));
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:DeprecationLoggerTests.java


示例7: getSafeFromHeader

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public static String getSafeFromHeader(final ThreadContext context, final String headerName) {

        if (context == null || headerName == null || headerName.isEmpty()) {
            return null;
        }

        String headerValue = null;
        	
        Map<String, String> headers = context.getHeaders();
        if (!headers.containsKey(headerName) || (headerValue = headers.get(headerName)) == null) {
            return null;
        }

        if (isInterClusterRequest(context) || isDirectRequest(context)) {
            return headerValue;
        }

        return null;
    }
 
开发者ID:floragunncom,项目名称:search-guard,代码行数:20,代码来源:HeaderHelper.java


示例8: createOrGetTrial

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
private SearchGuardLicense createOrGetTrial(String msg) {
    long created = System.currentTimeMillis();
    ThreadContext threadContext = threadPool.getThreadContext();
    
    try(StoredContext ctx = threadContext.stashContext()) {
        threadContext.putHeader(ConfigConstants.SG_CONF_REQUEST_HEADER, "true");
        GetResponse get = client.prepareGet(searchguardIndex, "sg", "tattr").get();
        if(get.isExists()) {
            created = (long) get.getSource().get("val");
        } else {
            client.index(new IndexRequest(searchguardIndex)
            .type("sg")
            .id("tattr")
            .setRefreshPolicy(RefreshPolicy.IMMEDIATE)
            .source("{\"val\": "+System.currentTimeMillis()+"}", XContentType.JSON)).actionGet();
        }
    }
    
    return SearchGuardLicense.createTrialLicense(formatDate(created), clusterService, msg);
}
 
开发者ID:floragunncom,项目名称:search-guard,代码行数:21,代码来源:IndexBaseConfigurationRepository.java


示例9: testAuthenticateBadUser

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public void testAuthenticateBadUser() {
    Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build();
    Settings realmSettings = Settings.builder()
            .put("type", CustomRealm.TYPE)
            .put("users.john.password", "doe")
            .put("users.john.roles", "user")
            .put("users.jane.password", "test")
            .putList("users.jane.roles", "user", "admin")
            .build();

    CustomRealm realm = new CustomRealm(new RealmConfig("test", realmSettings, globalSettings,
            new Environment(globalSettings, createTempDir()), new ThreadContext(globalSettings)));
    UsernamePasswordToken token =
            new UsernamePasswordToken("john1", new SecureString(randomAlphaOfLengthBetween(4, 16).toCharArray()));
    realm.authenticate(token, ActionListener.wrap(result -> {
        assertFalse(result.isAuthenticated());
        assertThat(result.getUser(), nullValue());
    }, e -> fail("Failed with exception: " + e.getMessage())));
}
 
开发者ID:elastic,项目名称:shield-custom-realm-example,代码行数:20,代码来源:CustomRealmTests.java


示例10: testTransportClient

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public void testTransportClient() throws Exception {
    NodesInfoResponse nodeInfos = client().admin().cluster().prepareNodesInfo().get();
    List<NodeInfo>  nodes = nodeInfos.getNodes();
    assertTrue(nodes.size() > 0);
    TransportAddress publishAddress = randomFrom(nodes).getTransport().address().publishAddress();
    String clusterName = nodeInfos.getClusterName().value();

    Settings settings = Settings.builder()
            .put("cluster.name", clusterName)
            .put(ThreadContext.PREFIX + "." + CustomRealm.USER_HEADER, randomFrom(KNOWN_USERS))
            .put(ThreadContext.PREFIX + "." + CustomRealm.PW_HEADER, PASSWORD)
            .build();
    try (TransportClient client = new PreBuiltXPackTransportClient(settings)) {
        client.addTransportAddress(publishAddress);
        ClusterHealthResponse response = client.admin().cluster().prepareHealth().execute().actionGet();
        assertThat(response.isTimedOut(), is(false));
    }
}
 
开发者ID:elastic,项目名称:shield-custom-realm-example,代码行数:19,代码来源:CustomRealmIT.java


示例11: Netty4HttpChannel

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * @param transport             The corresponding <code>NettyHttpServerTransport</code> where this channel belongs to.
 * @param request               The request that is handled by this channel.
 * @param pipelinedRequest      If HTTP pipelining is enabled provide the corresponding pipelined request. May be null if
 *                              HTTP pipelining is disabled.
 * @param detailedErrorsEnabled true iff error messages should include stack traces.
 * @param threadContext         the thread context for the channel
 */
Netty4HttpChannel(
        final Netty4HttpServerTransport transport,
        final Netty4HttpRequest request,
        final HttpPipelinedRequest pipelinedRequest,
        final boolean detailedErrorsEnabled,
        final ThreadContext threadContext) {
    super(request, detailedErrorsEnabled);
    this.transport = transport;
    this.channel = request.getChannel();
    this.nettyRequest = request.request();
    this.pipelinedRequest = pipelinedRequest;
    this.threadContext = threadContext;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:Netty4HttpChannel.java


示例12: HttpChannelHandler

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
protected HttpChannelHandler(
        final Netty4HttpServerTransport transport,
        final boolean detailedErrorsEnabled,
        final ThreadContext threadContext) {
    this.transport = transport;
    this.requestHandler = new Netty4HttpRequestHandler(transport, detailedErrorsEnabled, threadContext);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:8,代码来源:Netty4HttpServerTransport.java


示例13: before

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
@Before
public final void before()  {
    logger.info("[{}]: before test", getTestName());
    assertNull("Thread context initialized twice", threadContext);
    if (enableWarningsCheck()) {
        this.threadContext = new ThreadContext(Settings.EMPTY);
        DeprecationLogger.setThreadContext(threadContext);
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:10,代码来源:ESTestCase.java


示例14: buildClient

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
    RestClientBuilder builder = RestClient.builder(hosts);
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
        } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) {
            throw new RuntimeException("Error setting up ssl", e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:36,代码来源:ESRestTestCase.java


示例15: Parameters

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
public Parameters(Environment env, ScriptService scriptService, TemplateService templateService,
                  AnalysisRegistry analysisRegistry, ThreadContext threadContext) {
    this.env = env;
    this.scriptService = scriptService;
    this.templateService = templateService;
    this.threadContext = threadContext;
    this.analysisRegistry = analysisRegistry;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:9,代码来源:Processor.java


示例16: filterWithHeader

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
@Override
public Client filterWithHeader(Map<String, String> headers) {
    return new FilterClient(this) {
        @Override
        protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
            ThreadContext threadContext = threadPool().getThreadContext();
            try (ThreadContext.StoredContext ctx = threadContext.stashAndMergeHeaders(headers)) {
                super.doExecute(action, request, listener);
            }
        }
    };
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:13,代码来源:AbstractClient.java


示例17: dispatchRequest

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
@Override
public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
    if (request.rawPath().equals("/favicon.ico")) {
        handleFavicon(request, channel);
        return;
    }
    RestChannel responseChannel = channel;
    try {
        final int contentLength = request.hasContent() ? request.content().length() : 0;
        assert contentLength >= 0 : "content length was negative, how is that possible?";
        final RestHandler handler = getHandler(request);

        if (contentLength > 0 && hasContentType(request, handler) == false) {
            sendContentTypeErrorMessage(request, responseChannel);
        } else if (contentLength > 0 && handler != null && handler.supportsContentStream() &&
            request.getXContentType() != XContentType.JSON && request.getXContentType() != XContentType.SMILE) {
            responseChannel.sendResponse(BytesRestResponse.createSimpleErrorResponse(RestStatus.NOT_ACCEPTABLE, "Content-Type [" +
                request.getXContentType() + "] does not support stream parsing. Use JSON or SMILE instead"));
        } else {
            if (canTripCircuitBreaker(request)) {
                inFlightRequestsBreaker(circuitBreakerService).addEstimateBytesAndMaybeBreak(contentLength, "<http_request>");
            } else {
                inFlightRequestsBreaker(circuitBreakerService).addWithoutBreaking(contentLength);
            }
            // iff we could reserve bytes for the request we need to send the response also over this channel
            responseChannel = new ResourceHandlingHttpChannel(channel, circuitBreakerService, contentLength);
            dispatchRequest(request, responseChannel, client, threadContext, handler);
        }
    } catch (Exception e) {
        try {
            responseChannel.sendResponse(new BytesRestResponse(channel, e));
        } catch (Exception inner) {
            inner.addSuppressed(e);
            logger.error((Supplier<?>) () ->
                new ParameterizedMessage("failed to send failure response for uri [{}]", request.uri()), inner);
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:39,代码来源:RestController.java


示例18: ClusterStateObserver

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * @param timeout        a global timeout for this observer. After it has expired the observer
 *                       will fail any existing or new #waitForNextChange calls. Set to null
 *                       to wait indefinitely
 */
public ClusterStateObserver(ClusterState initialState, ClusterService clusterService, @Nullable TimeValue timeout, Logger logger,
                            ThreadContext contextHolder) {
    this.clusterService = clusterService;
    this.lastObservedState = new AtomicReference<>(new StoredState(initialState));
    this.timeOutValue = timeout;
    if (timeOutValue != null) {
        this.startTimeNS = System.nanoTime();
    }
    this.logger = logger;
    this.contextHolder = contextHolder;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:ClusterStateObserver.java


示例19: setThreadContext

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * Set the {@link ThreadContext} used to add deprecation headers to network responses.
 * <p>
 * This is expected to <em>only</em> be invoked by the {@code Node}'s constructor (therefore once outside of tests).
 *
 * @param threadContext The thread context owned by the {@code ThreadPool} (and implicitly a {@code Node})
 * @throws IllegalStateException if this {@code threadContext} has already been set
 */
public static void setThreadContext(ThreadContext threadContext) {
    Objects.requireNonNull(threadContext, "Cannot register a null ThreadContext");

    // add returning false means it _did_ have it already
    if (THREAD_CONTEXT.add(threadContext) == false) {
        throw new IllegalStateException("Double-setting ThreadContext not allowed!");
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:DeprecationLogger.java


示例20: removeThreadContext

import org.elasticsearch.common.util.concurrent.ThreadContext; //导入依赖的package包/类
/**
 * Remove the {@link ThreadContext} used to add deprecation headers to network responses.
 * <p>
 * This is expected to <em>only</em> be invoked by the {@code Node}'s {@code close} method (therefore once outside of tests).
 *
 * @param threadContext The thread context owned by the {@code ThreadPool} (and implicitly a {@code Node})
 * @throws IllegalStateException if this {@code threadContext} is unknown (and presumably already unset before)
 */
public static void removeThreadContext(ThreadContext threadContext) {
    assert threadContext != null;

    // remove returning false means it did not have it already
    if (THREAD_CONTEXT.remove(threadContext) == false) {
        throw new IllegalStateException("Removing unknown ThreadContext not allowed!");
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:17,代码来源:DeprecationLogger.java



注:本文中的org.elasticsearch.common.util.concurrent.ThreadContext类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java AreaReference类代码示例发布时间:2022-05-22
下一篇:
Java ActionBuilder类代码示例发布时间:2022-05-22
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap