本文整理汇总了Java中org.elasticsearch.common.util.concurrent.ThreadContext类的典型用法代码示例。如果您正苦于以下问题:Java ThreadContext类的具体用法?Java ThreadContext怎么用?Java ThreadContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ThreadContext类属于org.elasticsearch.common.util.concurrent包,在下文中一共展示了ThreadContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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;
}
}
示例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);
}
}
示例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);
}
});
}
示例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"));
}
示例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 + "]\""));
}
}
示例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 + "\""));
}
}
示例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;
}
示例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);
}
示例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())));
}
示例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));
}
}
示例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;
}
示例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);
}
示例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);
}
}
示例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();
}
示例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;
}