Dataset Viewer
code
stringlengths 72
362k
| identifier
stringlengths 3
50
⌀ | lang
stringclasses 1
value | repository
stringclasses 36
values |
---|---|---|---|
package org.elasticsearch.http;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.rest.RestStatus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class TestHttpResponse implements HttpResponse {
private final RestStatus [MASK];
private final BytesReference content;
private final Map<String, List<String>> headers = new HashMap<>();
TestHttpResponse(RestStatus [MASK], BytesReference content) {
this.[MASK] = [MASK];
this.content = content;
}
public BytesReference content() {
return content;
}
public RestStatus [MASK]() {
return [MASK];
}
public Map<String, List<String>> headers() {
return headers;
}
@Override
public void addHeader(String name, String value) {
if (headers.containsKey(name) == false) {
ArrayList<String> values = new ArrayList<>();
values.add(value);
headers.put(name, values);
} else {
headers.get(name).add(value);
}
}
@Override
public boolean containsHeader(String name) {
return headers.containsKey(name);
}
} | status | java | elasticsearch |
package org.elasticsearch.xpack.inference.services.azureaistudio.request;
import org.elasticsearch.common.Strings;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xcontent.XContentFactory;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.inference.services.azureaistudio.AzureAiStudioEndpointType;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.CoreMatchers.is;
public class AzureAiStudioChatCompletionRequestEntityTests extends ESTestCase {
public void testToXContent_WhenTokenEndpoint_NoParameters() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.TOKEN,
null,
null,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedTokenEndpointRequest(List.of("abc"), null, null, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenTokenEndpoint_WithTemperatureParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.TOKEN,
1.0,
null,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedTokenEndpointRequest(List.of("abc"), 1.0, null, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenTokenEndpoint_WithTopPParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.TOKEN,
null,
2.0,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedTokenEndpointRequest(List.of("abc"), null, 2.0, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenTokenEndpoint_WithDoSampleParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.TOKEN,
null,
null,
true,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedTokenEndpointRequest(List.of("abc"), null, null, true, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenTokenEndpoint_WithMaxNewTokensParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.TOKEN,
null,
null,
null,
512,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedTokenEndpointRequest(List.of("abc"), null, null, null, 512);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenRealtimeEndpoint_NoParameters() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.REALTIME,
null,
null,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedRealtimeEndpointRequest(List.of("abc"), null, null, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenRealtimeEndpoint_WithTemperatureParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.REALTIME,
1.0,
null,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedRealtimeEndpointRequest(List.of("abc"), 1.0, null, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenRealtimeEndpoint_WithTopPParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.REALTIME,
null,
2.0,
null,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedRealtimeEndpointRequest(List.of("abc"), null, 2.0, null, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenRealtimeEndpoint_WithDoSampleParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.REALTIME,
null,
null,
true,
null,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedRealtimeEndpointRequest(List.of("abc"), null, null, true, null);
assertThat(request, is(expectedRequest));
}
public void testToXContent_WhenRealtimeEndpoint_WithMaxNewTokensParam() throws IOException {
var entity = new AzureAiStudioChatCompletionRequestEntity(
List.of("abc"),
AzureAiStudioEndpointType.REALTIME,
null,
null,
null,
512,
false
);
var request = getXContentAsString(entity);
var expectedRequest = getExpectedRealtimeEndpointRequest(List.of("abc"), null, null, null, 512);
assertThat(request, is(expectedRequest));
}
private String getXContentAsString(AzureAiStudioChatCompletionRequestEntity entity) throws IOException {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
entity.toXContent(builder, null);
return Strings.toString(builder);
}
private String getExpectedTokenEndpointRequest(
List<String> inputs,
@Nullable Double temperature,
@Nullable Double topP,
@Nullable Boolean doSample,
@Nullable Integer [MASK]
) {
String expected = "{";
expected = addMessageInputs("messages", expected, inputs);
expected = addParameters(expected, temperature, topP, doSample, [MASK]);
expected += "}";
return expected;
}
private String getExpectedRealtimeEndpointRequest(
List<String> inputs,
@Nullable Double temperature,
@Nullable Double topP,
@Nullable Boolean doSample,
@Nullable Integer [MASK]
) {
String expected = "{\"input_data\":{";
expected = addMessageInputs("input_string", expected, inputs);
expected = addParameters(expected, temperature, topP, doSample, [MASK]);
expected += "}}";
return expected;
}
private String addMessageInputs(String fieldName, String expected, List<String> inputs) {
StringBuilder messages = new StringBuilder(Strings.format("\"%s\":[", fieldName));
var hasOne = false;
for (String input : inputs) {
if (hasOne) {
messages.append(",");
}
messages.append(getMessageString(input));
hasOne = true;
}
messages.append("]");
return expected + messages;
}
private String getMessageString(String input) {
return Strings.format("{\"content\":\"%s\",\"role\":\"user\"}", input);
}
private String addParameters(String expected, Double temperature, Double topP, Boolean doSample, Integer [MASK]) {
if (temperature == null && topP == null && doSample == null && [MASK] == null) {
return expected;
}
StringBuilder parameters = new StringBuilder(",\"parameters\":{");
var hasOne = false;
if (temperature != null) {
parameters.append(Strings.format("\"temperature\":%.1f", temperature));
hasOne = true;
}
if (topP != null) {
if (hasOne) {
parameters.append(",");
}
parameters.append(Strings.format("\"top_p\":%.1f", topP));
hasOne = true;
}
if (doSample != null) {
if (hasOne) {
parameters.append(",");
}
parameters.append(Strings.format("\"do_sample\":%s", doSample.equals(Boolean.TRUE)));
hasOne = true;
}
if ([MASK] != null) {
if (hasOne) {
parameters.append(",");
}
parameters.append(Strings.format("\"max_new_tokens\":%d", [MASK]));
}
parameters.append("}");
return expected + parameters;
}
} | maxNewTokens | java | elasticsearch |
package com.google.common.eventbus.outside;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.Lists;
import com.google.common.eventbus.Subscribe;
import com.google.common.eventbus.outside.NeitherAbstractNorAnnotatedInSuperclassTest.SubClass;
import java.util.List;
public class NeitherAbstractNorAnnotatedInSuperclassTest extends AbstractEventBusTest<SubClass> {
static class SuperClass {
final List<Object> neitherOverriddenNorAnnotatedEvents = Lists.newArrayList();
final List<Object> overriddenInSubclassNowhereAnnotatedEvents = Lists.newArrayList();
final List<Object> [MASK] = Lists.newArrayList();
public void neitherOverriddenNorAnnotated(Object o) {
neitherOverriddenNorAnnotatedEvents.add(o);
}
public void overriddenInSubclassNowhereAnnotated(Object o) {
overriddenInSubclassNowhereAnnotatedEvents.add(o);
}
public void overriddenAndAnnotatedInSubclass(Object o) {
[MASK].add(o);
}
}
static class SubClass extends SuperClass {
@Override
@SuppressWarnings("RedundantOverride")
public void overriddenInSubclassNowhereAnnotated(Object o) {
super.overriddenInSubclassNowhereAnnotated(o);
}
@Subscribe
@Override
public void overriddenAndAnnotatedInSubclass(Object o) {
super.overriddenAndAnnotatedInSubclass(o);
}
}
public void testNeitherOverriddenNorAnnotated() {
assertThat(getSubscriber().neitherOverriddenNorAnnotatedEvents).isEmpty();
}
public void testOverriddenInSubclassNowhereAnnotated() {
assertThat(getSubscriber().overriddenInSubclassNowhereAnnotatedEvents).isEmpty();
}
public void testOverriddenAndAnnotatedInSubclass() {
assertThat(getSubscriber().[MASK]).contains(EVENT);
}
@Override
SubClass createSubscriber() {
return new SubClass();
}
} | overriddenAndAnnotatedInSubclassEvents | java | guava |
package org.elasticsearch.xpack.ml.rest.dataframe;
import org.elasticsearch.[MASK].internal.node.NodeClient;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.Scope;
import org.elasticsearch.rest.ServerlessScope;
import org.elasticsearch.rest.action.RestCancellableNodeClient;
import org.elasticsearch.rest.action.RestToXContentListener;
import org.elasticsearch.xpack.core.ml.action.EvaluateDataFrameAction;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.rest.RestRequest.Method.POST;
import static org.elasticsearch.xpack.ml.MachineLearning.BASE_PATH;
@ServerlessScope(Scope.PUBLIC)
public class RestEvaluateDataFrameAction extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(POST, BASE_PATH + "data_frame/_evaluate"));
}
@Override
public String getName() {
return "ml_evaluate_data_frame_action";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient [MASK]) throws IOException {
EvaluateDataFrameAction.Request request = EvaluateDataFrameAction.Request.parseRequest(restRequest.contentOrSourceParamParser());
return channel -> new RestCancellableNodeClient([MASK], restRequest.getHttpChannel()).execute(
EvaluateDataFrameAction.INSTANCE,
request,
new RestToXContentListener<>(channel)
);
}
} | client | java | elasticsearch |
package org.elasticsearch.index.fielddata;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.SortedSetDocValuesField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NoMergePolicy;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.breaker.CircuitBreaker;
import org.elasticsearch.common.breaker.CircuitBreakingException;
import org.elasticsearch.common.breaker.NoopCircuitBreaker;
import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader;
import org.elasticsearch.index.fielddata.plain.PagedBytesIndexFieldData;
import org.elasticsearch.index.fielddata.plain.SortedSetOrdinalsIndexFieldData;
import org.elasticsearch.index.mapper.TextFieldMapper;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.script.field.DelegateDocValuesField;
import org.elasticsearch.script.field.ToScriptFieldFactory;
import org.elasticsearch.search.aggregations.support.CoreValuesSourceType;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.FieldMaskingReader;
import static org.hamcrest.Matchers.equalTo;
public class FieldDataCacheTests extends ESTestCase {
private static final ToScriptFieldFactory<SortedSetDocValues> MOCK_TO_SCRIPT_FIELD = (dv, n) -> new DelegateDocValuesField(
new ScriptDocValues.Strings(new ScriptDocValues.StringsSupplier(FieldData.toString(dv))),
n
);
public void testLoadGlobal_neverCacheIfFieldIsMissing() throws Exception {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(null);
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
IndexWriter iw = new IndexWriter(dir, iwc);
long numDocs = scaledRandomIntBetween(32, 128);
for (int i = 1; i <= numDocs; i++) {
Document doc = new Document();
doc.add(new SortedSetDocValuesField("field1", new BytesRef(String.valueOf(i))));
doc.add(new StringField("field2", String.valueOf(i), Field.Store.NO));
iw.addDocument(doc);
if (i % 24 == 0) {
iw.commit();
}
}
iw.close();
DirectoryReader ir = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(dir), new ShardId("_index", "_na_", 0));
DummyAccountingFieldDataCache fieldDataCache = new DummyAccountingFieldDataCache();
SortedSetOrdinalsIndexFieldData sortedSetOrdinalsIndexFieldData = createSortedDV("field1", fieldDataCache);
sortedSetOrdinalsIndexFieldData.loadGlobal(ir);
assertThat(fieldDataCache.cachedGlobally, equalTo(1));
sortedSetOrdinalsIndexFieldData.loadGlobal(new FieldMaskingReader("field1", ir));
assertThat(fieldDataCache.cachedGlobally, equalTo(1));
PagedBytesIndexFieldData pagedBytesIndexFieldData = createPagedBytes("field2", fieldDataCache);
pagedBytesIndexFieldData.loadGlobal(ir);
assertThat(fieldDataCache.cachedGlobally, equalTo(2));
pagedBytesIndexFieldData.loadGlobal(new FieldMaskingReader("field2", ir));
assertThat(fieldDataCache.cachedGlobally, equalTo(2));
ir.close();
dir.close();
}
public void testGlobalOrdinalsCircuitBreaker() throws Exception {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(null);
iwc.setMergePolicy(NoMergePolicy.INSTANCE);
IndexWriter iw = new IndexWriter(dir, iwc);
long numDocs = randomIntBetween(66000, 70000);
for (int i = 1; i <= numDocs; i++) {
Document doc = new Document();
doc.add(new SortedSetDocValuesField("field1", new BytesRef(String.valueOf(i))));
iw.addDocument(doc);
if (i % 10000 == 0) {
iw.commit();
}
}
iw.close();
DirectoryReader ir = ElasticsearchDirectoryReader.wrap(DirectoryReader.open(dir), new ShardId("_index", "_na_", 0));
int[] timesCalled = new int[1];
SortedSetOrdinalsIndexFieldData sortedSetOrdinalsIndexFieldData = new SortedSetOrdinalsIndexFieldData(
new DummyAccountingFieldDataCache(),
"field1",
CoreValuesSourceType.KEYWORD,
new NoneCircuitBreakerService() {
@Override
public CircuitBreaker getBreaker(String name) {
assertThat(name, equalTo(CircuitBreaker.FIELDDATA));
return new NoopCircuitBreaker("test") {
@Override
public void addEstimateBytesAndMaybeBreak(long bytes, String [MASK]) throws CircuitBreakingException {
assertThat([MASK], equalTo("Global Ordinals"));
assertThat(bytes, equalTo(0L));
timesCalled[0]++;
}
};
}
},
MOCK_TO_SCRIPT_FIELD
);
sortedSetOrdinalsIndexFieldData.loadGlobal(ir);
assertThat(timesCalled[0], equalTo(2));
ir.close();
dir.close();
}
private SortedSetOrdinalsIndexFieldData createSortedDV(String fieldName, IndexFieldDataCache indexFieldDataCache) {
return new SortedSetOrdinalsIndexFieldData(
indexFieldDataCache,
fieldName,
CoreValuesSourceType.KEYWORD,
new NoneCircuitBreakerService(),
MOCK_TO_SCRIPT_FIELD
);
}
private PagedBytesIndexFieldData createPagedBytes(String fieldName, IndexFieldDataCache indexFieldDataCache) {
return new PagedBytesIndexFieldData(
fieldName,
CoreValuesSourceType.KEYWORD,
indexFieldDataCache,
new NoneCircuitBreakerService(),
TextFieldMapper.Defaults.FIELDDATA_MIN_FREQUENCY,
TextFieldMapper.Defaults.FIELDDATA_MAX_FREQUENCY,
TextFieldMapper.Defaults.FIELDDATA_MIN_SEGMENT_SIZE,
MOCK_TO_SCRIPT_FIELD
);
}
private class DummyAccountingFieldDataCache implements IndexFieldDataCache {
private int cachedGlobally = 0;
@Override
public <FD extends LeafFieldData, IFD extends IndexFieldData<FD>> FD load(LeafReaderContext context, IFD indexFieldData)
throws Exception {
return indexFieldData.loadDirect(context);
}
@Override
@SuppressWarnings("unchecked")
public <FD extends LeafFieldData, IFD extends IndexFieldData.Global<FD>> IFD load(DirectoryReader indexReader, IFD indexFieldData)
throws Exception {
cachedGlobally++;
return (IFD) indexFieldData.loadGlobalDirect(indexReader);
}
@Override
public void clear() {}
@Override
public void clear(String fieldName) {}
}
} | label | java | elasticsearch |
package org.elasticsearch.datastreams.options.action;
import org.elasticsearch.action.ActionType;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.core.TimeValue;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
public class DeleteDataStreamOptionsAction {
public static final ActionType<AcknowledgedResponse> INSTANCE = new ActionType<>("indices:admin/data_stream/options/delete");
private DeleteDataStreamOptionsAction() {}
public static final class Request extends AcknowledgedRequest<Request> implements IndicesRequest.Replaceable {
private String[] [MASK];
private IndicesOptions indicesOptions = IndicesOptions.builder()
.concreteTargetOptions(IndicesOptions.ConcreteTargetOptions.ERROR_WHEN_UNAVAILABLE_TARGETS)
.wildcardOptions(
IndicesOptions.WildcardOptions.builder().matchOpen(true).matchClosed(true).allowEmptyExpressions(true).resolveAliases(false)
)
.gatekeeperOptions(
IndicesOptions.GatekeeperOptions.builder().allowAliasToMultipleIndices(false).allowClosedIndices(true).allowSelectors(false)
)
.build();
public Request(StreamInput in) throws IOException {
super(in);
this.[MASK] = in.readOptionalStringArray();
this.indicesOptions = IndicesOptions.readIndicesOptions(in);
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalStringArray([MASK]);
indicesOptions.writeIndicesOptions(out);
}
public Request(TimeValue masterNodeTimeout, TimeValue ackTimeout, String[] [MASK]) {
super(masterNodeTimeout, ackTimeout);
this.[MASK] = [MASK];
}
public String[] getNames() {
return [MASK];
}
@Override
public String[] indices() {
return [MASK];
}
@Override
public IndicesOptions indicesOptions() {
return indicesOptions;
}
public Request indicesOptions(IndicesOptions indicesOptions) {
this.indicesOptions = indicesOptions;
return this;
}
@Override
public boolean includeDataStreams() {
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Arrays.equals([MASK], request.[MASK]) && Objects.equals(indicesOptions, request.indicesOptions);
}
@Override
public int hashCode() {
int result = Objects.hash(indicesOptions);
result = 31 * result + Arrays.hashCode([MASK]);
return result;
}
@Override
public IndicesRequest indices(String... indices) {
this.[MASK] = indices;
return this;
}
}
} | names | java | elasticsearch |
package android.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Log {
public static final int VERBOSE = 2;
public static final int DEBUG = 3;
public static final int INFO = 4;
public static final int WARN = 5;
public static final int ERROR = 6;
public static final int ASSERT = 7;
private static Logger globalLogger = Logger.getGlobal();
private static Map<String, Integer> tagLevels = new HashMap<String, Integer>();
private static final String LOG_TAG_PREFIX = "log.tag.";
static {
globalLogger.setLevel(Level.ALL);
InputStream input = Log.class.getResourceAsStream("/data/local.prop");
if (input != null) {
try {
Properties props = new Properties();
props.load(input);
for (Map.Entry<Object,Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
if (key.startsWith(LOG_TAG_PREFIX)) {
String tag = key.substring(LOG_TAG_PREFIX.length());
String value = (String) entry.getValue();
int level;
if ("ASSERT".equals(value)) {
level = ASSERT;
} else if ("DEBUG".equals(value)) {
level = DEBUG;
} else if ("ERROR".equals(value)) {
level = ERROR;
} else if ("INFO".equals(value)) {
level = INFO;
} else if ("VERBOSE".equals(value)) {
level = VERBOSE;
} else if ("WARN".equals(value)) {
level = WARN;
} else {
level = 0;
}
tagLevels.put(tag, Integer.valueOf(level));
}
}
} catch (IOException e) {
globalLogger.log(Level.WARNING, "failed parsing /data/local.prop", e);
}
}
}
private static class TerribleFailure extends Exception {
TerribleFailure(String [MASK], Throwable cause) { super([MASK], cause); }
}
public interface TerribleFailureHandler {
void onTerribleFailure(String tag, TerribleFailure what);
}
private static TerribleFailureHandler sWtfHandler = new TerribleFailureHandler() {
public void onTerribleFailure(String tag, TerribleFailure what) {
globalLogger.log(Level.SEVERE, tag, what);
}
};
private Log() {
}
public static int v(String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, [MASK]);
}
public static int v(String tag, String [MASK], Throwable tr) {
return println_native(LOG_ID_MAIN, VERBOSE, tag, [MASK] + '\n' + getStackTraceString(tr));
}
public static int d(String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, DEBUG, tag, [MASK]);
}
public static int d(String tag, String [MASK], Throwable tr) {
return println_native(LOG_ID_MAIN, DEBUG, tag, [MASK] + '\n' + getStackTraceString(tr));
}
public static int i(String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, INFO, tag, [MASK]);
}
public static int i(String tag, String [MASK], Throwable tr) {
return println_native(LOG_ID_MAIN, INFO, tag, [MASK] + '\n' + getStackTraceString(tr));
}
public static int w(String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, WARN, tag, [MASK]);
}
public static int w(String tag, String [MASK], Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, [MASK] + '\n' + getStackTraceString(tr));
}
public static boolean isLoggable(String tag, int level) {
Integer minimumLevel = tagLevels.get(tag);
if (minimumLevel != null) {
return level > minimumLevel.intValue();
}
return true;
}
public static int w(String tag, Throwable tr) {
return println_native(LOG_ID_MAIN, WARN, tag, getStackTraceString(tr));
}
public static int e(String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, ERROR, tag, [MASK]);
}
public static int e(String tag, String [MASK], Throwable tr) {
return println_native(LOG_ID_MAIN, ERROR, tag, [MASK] + '\n' + getStackTraceString(tr));
}
public static int wtf(String tag, String [MASK]) {
return wtf(LOG_ID_MAIN, tag, [MASK], null, false);
}
public static int wtfStack(String tag, String [MASK]) {
return wtf(LOG_ID_MAIN, tag, [MASK], null, true);
}
public static int wtf(String tag, Throwable tr) {
return wtf(LOG_ID_MAIN, tag, tr.getMessage(), tr, false);
}
public static int wtf(String tag, String [MASK], Throwable tr) {
return wtf(LOG_ID_MAIN, tag, [MASK], tr, false);
}
static int wtf(int logId, String tag, String [MASK], Throwable tr, boolean localStack) {
TerribleFailure what = new TerribleFailure([MASK], tr);
int bytes = println_native(logId, ASSERT, tag, [MASK] + '\n'
+ getStackTraceString(localStack ? what : tr));
sWtfHandler.onTerribleFailure(tag, what);
return bytes;
}
public static TerribleFailureHandler setWtfHandler(TerribleFailureHandler handler) {
if (handler == null) {
throw new NullPointerException("handler == null");
}
TerribleFailureHandler oldHandler = sWtfHandler;
sWtfHandler = handler;
return oldHandler;
}
public static String getStackTraceString(Throwable tr) {
if (tr == null) {
return "";
}
Throwable t = tr;
while (t != null) {
if (t instanceof UnknownHostException) {
return "";
}
t = t.getCause();
}
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, false);
tr.printStackTrace(pw);
pw.flush();
return sw.toString();
}
public static int println(int priority, String tag, String [MASK]) {
return println_native(LOG_ID_MAIN, priority, tag, [MASK]);
}
public static final int LOG_ID_MAIN = 0;
public static final int LOG_ID_RADIO = 1;
public static final int LOG_ID_EVENTS = 2;
public static final int LOG_ID_SYSTEM = 3;
public static int println_native(int bufID,
int priority, String tag, String [MASK]) {
String logMessage = String.format("%s: %s", tag, [MASK]);
globalLogger.log(priorityToLevel(priority), logMessage);
return logMessage.length();
}
private static Level priorityToLevel(int priority) {
switch (priority) {
case ASSERT:
case ERROR: return Level.SEVERE;
case WARN: return Level.WARNING;
case INFO: return Level.INFO;
case DEBUG: return Level.FINE;
case VERBOSE: return Level.FINER;
default:
return Level.FINEST;
}
}
} | msg | java | j2objc |
package org.elasticsearch.xpack.core.security.action.user;
import org.elasticsearch.test.ESTestCase;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.nullValue;
public class QueryUserRequestTests extends ESTestCase {
public void testValidate() {
final QueryUserRequest request1 = new QueryUserRequest(
null,
randomIntBetween(0, Integer.MAX_VALUE),
randomIntBetween(0, Integer.MAX_VALUE),
null,
null,
false
);
assertThat(request1.validate(), nullValue());
final QueryUserRequest [MASK] = new QueryUserRequest(
null,
randomIntBetween(Integer.MIN_VALUE, -1),
randomIntBetween(0, Integer.MAX_VALUE),
null,
null,
false
);
assertThat([MASK].validate().getMessage(), containsString("[from] parameter cannot be negative"));
final QueryUserRequest request3 = new QueryUserRequest(
null,
randomIntBetween(0, Integer.MAX_VALUE),
randomIntBetween(Integer.MIN_VALUE, -1),
null,
null,
false
);
assertThat(request3.validate().getMessage(), containsString("[size] parameter cannot be negative"));
}
} | request2 | java | elasticsearch |
package org.greenrobot.greendao.query;
import android.database.Cursor;
import org.greenrobot.greendao.AbstractDao;
import java.util.Date;
public class CursorQuery<T> extends AbstractQueryWithLimit<T> {
private final static class QueryData<T2> extends AbstractQueryData<T2, CursorQuery<T2>> {
private final int limitPosition;
private final int offsetPosition;
QueryData(AbstractDao dao, String [MASK], String[] initialValues, int limitPosition, int offsetPosition) {
super(dao, [MASK], initialValues);
this.limitPosition = limitPosition;
this.offsetPosition = offsetPosition;
}
@Override
protected CursorQuery<T2> createQuery() {
return new CursorQuery<T2>(this, dao, [MASK], initialValues.clone(), limitPosition, offsetPosition);
}
}
public static <T2> CursorQuery<T2> internalCreate(AbstractDao<T2, ?> dao, String [MASK], Object[] initialValues) {
return create(dao, [MASK], initialValues, -1, -1);
}
static <T2> CursorQuery<T2> create(AbstractDao<T2, ?> dao, String [MASK], Object[] initialValues, int limitPosition,
int offsetPosition) {
QueryData<T2> queryData = new QueryData<T2>(dao, [MASK], toStringArray(initialValues), limitPosition,
offsetPosition);
return queryData.forCurrentThread();
}
private final QueryData<T> queryData;
private CursorQuery(QueryData<T> queryData, AbstractDao<T, ?> dao, String [MASK], String[] initialValues, int limitPosition,
int offsetPosition) {
super(dao, [MASK], initialValues, limitPosition, offsetPosition);
this.queryData = queryData;
}
public CursorQuery forCurrentThread() {
return queryData.forCurrentThread(this);
}
public Cursor query() {
checkThread();
return dao.getDatabase().rawQuery([MASK], parameters);
}
@Override
public CursorQuery<T> setParameter(int index, Object parameter) {
return (CursorQuery<T>) super.setParameter(index, parameter);
}
@Override
public CursorQuery<T> setParameter(int index, Date parameter) {
return (CursorQuery<T>) super.setParameter(index, parameter);
}
@Override
public CursorQuery<T> setParameter(int index, Boolean parameter) {
return (CursorQuery<T>) super.setParameter(index, parameter);
}
} | sql | java | greenDAO |
package org.elasticsearch.xpack.core.ml.inference.assignment;
import org.elasticsearch.TransportVersions;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.core.Nullable;
import org.elasticsearch.xcontent.ToXContentObject;
import org.elasticsearch.xcontent.XContentBuilder;
import org.elasticsearch.xpack.core.ml.action.StartTrainedModelDeploymentAction;
import org.elasticsearch.xpack.core.ml.inference.trainedmodel.InferenceStats;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class AssignmentStats implements ToXContentObject, Writeable {
public static class NodeStats implements ToXContentObject, Writeable {
private final DiscoveryNode node;
private final Long inferenceCount;
private final Double [MASK];
private final Double avgInferenceTimeExcludingCacheHit;
private final Instant lastAccess;
private final Integer pendingCount;
private final int errorCount;
private final Long cacheHitCount;
private final int rejectedExecutionCount;
private final int timeoutCount;
private final RoutingStateAndReason routingState;
private final Instant startTime;
private final Integer threadsPerAllocation;
private final Integer numberOfAllocations;
private final long peakThroughput;
private final long throughputLastPeriod;
private final Double avgInferenceTimeLastPeriod;
private final Long cacheHitCountLastPeriod;
public static AssignmentStats.NodeStats forStartedState(
DiscoveryNode node,
long inferenceCount,
Double [MASK],
Double avgInferenceTimeExcludingCacheHit,
int pendingCount,
int errorCount,
long cacheHitCount,
int rejectedExecutionCount,
int timeoutCount,
Instant lastAccess,
Instant startTime,
Integer threadsPerAllocation,
Integer numberOfAllocations,
long peakThroughput,
long throughputLastPeriod,
Double avgInferenceTimeLastPeriod,
long cacheHitCountLastPeriod
) {
return new AssignmentStats.NodeStats(
node,
inferenceCount,
[MASK],
avgInferenceTimeExcludingCacheHit,
lastAccess,
pendingCount,
errorCount,
cacheHitCount,
rejectedExecutionCount,
timeoutCount,
new RoutingStateAndReason(RoutingState.STARTED, null),
Objects.requireNonNull(startTime),
threadsPerAllocation,
numberOfAllocations,
peakThroughput,
throughputLastPeriod,
avgInferenceTimeLastPeriod,
cacheHitCountLastPeriod
);
}
public static AssignmentStats.NodeStats forNotStartedState(DiscoveryNode node, RoutingState state, String reason) {
return new AssignmentStats.NodeStats(
node,
null,
null,
null,
null,
null,
0,
null,
0,
0,
new RoutingStateAndReason(state, reason),
null,
null,
null,
0L,
0L,
null,
null
);
}
public NodeStats(
DiscoveryNode node,
Long inferenceCount,
Double [MASK],
Double avgInferenceTimeExcludingCacheHit,
@Nullable Instant lastAccess,
Integer pendingCount,
int errorCount,
Long cacheHitCount,
int rejectedExecutionCount,
int timeoutCount,
RoutingStateAndReason routingState,
@Nullable Instant startTime,
@Nullable Integer threadsPerAllocation,
@Nullable Integer numberOfAllocations,
long peakThroughput,
long throughputLastPeriod,
Double avgInferenceTimeLastPeriod,
Long cacheHitCountLastPeriod
) {
this.node = node;
this.inferenceCount = inferenceCount;
this.[MASK] = [MASK];
this.avgInferenceTimeExcludingCacheHit = avgInferenceTimeExcludingCacheHit;
this.lastAccess = lastAccess;
this.pendingCount = pendingCount;
this.errorCount = errorCount;
this.cacheHitCount = cacheHitCount;
this.rejectedExecutionCount = rejectedExecutionCount;
this.timeoutCount = timeoutCount;
this.routingState = routingState;
this.startTime = startTime;
this.threadsPerAllocation = threadsPerAllocation;
this.numberOfAllocations = numberOfAllocations;
this.peakThroughput = peakThroughput;
this.throughputLastPeriod = throughputLastPeriod;
this.avgInferenceTimeLastPeriod = avgInferenceTimeLastPeriod;
this.cacheHitCountLastPeriod = cacheHitCountLastPeriod;
assert this.lastAccess != null || (inferenceCount == null || inferenceCount == 0);
}
public NodeStats(StreamInput in) throws IOException {
this.node = in.readOptionalWriteable(DiscoveryNode::new);
this.inferenceCount = in.readOptionalLong();
this.[MASK] = in.readOptionalDouble();
this.lastAccess = in.readOptionalInstant();
this.pendingCount = in.readOptionalVInt();
this.routingState = in.readOptionalWriteable(RoutingStateAndReason::new);
this.startTime = in.readOptionalInstant();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) {
this.threadsPerAllocation = in.readOptionalVInt();
this.numberOfAllocations = in.readOptionalVInt();
this.errorCount = in.readVInt();
this.rejectedExecutionCount = in.readVInt();
this.timeoutCount = in.readVInt();
} else {
this.threadsPerAllocation = null;
this.numberOfAllocations = null;
this.errorCount = 0;
this.rejectedExecutionCount = 0;
this.timeoutCount = 0;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_2_0)) {
this.peakThroughput = in.readVLong();
this.throughputLastPeriod = in.readVLong();
this.avgInferenceTimeLastPeriod = in.readOptionalDouble();
} else {
this.peakThroughput = 0;
this.throughputLastPeriod = 0;
this.avgInferenceTimeLastPeriod = null;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) {
this.cacheHitCount = in.readOptionalVLong();
this.cacheHitCountLastPeriod = in.readOptionalVLong();
} else {
this.cacheHitCount = null;
this.cacheHitCountLastPeriod = null;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_5_0)) {
this.avgInferenceTimeExcludingCacheHit = in.readOptionalDouble();
} else {
this.avgInferenceTimeExcludingCacheHit = null;
}
}
public DiscoveryNode getNode() {
return node;
}
public RoutingStateAndReason getRoutingState() {
return routingState;
}
public Optional<Long> getInferenceCount() {
return Optional.ofNullable(inferenceCount);
}
public Optional<Double> getAvgInferenceTime() {
return Optional.ofNullable([MASK]);
}
public Optional<Double> getAvgInferenceTimeExcludingCacheHit() {
return Optional.ofNullable(avgInferenceTimeExcludingCacheHit);
}
public Instant getLastAccess() {
return lastAccess;
}
public Integer getPendingCount() {
return pendingCount;
}
public int getErrorCount() {
return errorCount;
}
public Optional<Long> getCacheHitCount() {
return Optional.ofNullable(cacheHitCount);
}
public int getRejectedExecutionCount() {
return rejectedExecutionCount;
}
public int getTimeoutCount() {
return timeoutCount;
}
public Instant getStartTime() {
return startTime;
}
public Integer getThreadsPerAllocation() {
return threadsPerAllocation;
}
public Integer getNumberOfAllocations() {
return numberOfAllocations;
}
public long getPeakThroughput() {
return peakThroughput;
}
public long getThroughputLastPeriod() {
return throughputLastPeriod;
}
public Double getAvgInferenceTimeLastPeriod() {
return avgInferenceTimeLastPeriod;
}
public Optional<Long> getCacheHitCountLastPeriod() {
return Optional.ofNullable(cacheHitCountLastPeriod);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (node != null) {
builder.startObject("node");
node.toXContent(builder, params);
builder.endObject();
}
builder.field("routing_state", routingState);
if (inferenceCount != null) {
builder.field("inference_count", inferenceCount);
}
if (inferenceCount != null && inferenceCount > 0) {
if ([MASK] != null) {
builder.field("average_inference_time_ms", [MASK]);
}
if (avgInferenceTimeExcludingCacheHit != null) {
builder.field("average_inference_time_ms_excluding_cache_hits", avgInferenceTimeExcludingCacheHit);
}
}
if (cacheHitCount != null) {
builder.field("inference_cache_hit_count", cacheHitCount);
}
if (lastAccess != null) {
builder.timestampFieldsFromUnixEpochMillis("last_access", "last_access_string", lastAccess.toEpochMilli());
}
if (pendingCount != null) {
builder.field("number_of_pending_requests", pendingCount);
}
if (errorCount > 0) {
builder.field("error_count", errorCount);
}
if (rejectedExecutionCount > 0) {
builder.field("rejected_execution_count", rejectedExecutionCount);
}
if (timeoutCount > 0) {
builder.field("timeout_count", timeoutCount);
}
if (startTime != null) {
builder.timestampFieldsFromUnixEpochMillis("start_time", "start_time_string", startTime.toEpochMilli());
}
if (threadsPerAllocation != null) {
builder.field("threads_per_allocation", threadsPerAllocation);
}
if (numberOfAllocations != null) {
builder.field("number_of_allocations", numberOfAllocations);
}
builder.field("peak_throughput_per_minute", peakThroughput);
builder.field("throughput_last_minute", throughputLastPeriod);
if (avgInferenceTimeLastPeriod != null) {
builder.field("average_inference_time_ms_last_minute", avgInferenceTimeLastPeriod);
}
if (cacheHitCountLastPeriod != null) {
builder.field("inference_cache_hit_count_last_minute", cacheHitCountLastPeriod);
}
builder.endObject();
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalWriteable(node);
out.writeOptionalLong(inferenceCount);
out.writeOptionalDouble([MASK]);
out.writeOptionalInstant(lastAccess);
out.writeOptionalVInt(pendingCount);
out.writeOptionalWriteable(routingState);
out.writeOptionalInstant(startTime);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_1_0)) {
out.writeOptionalVInt(threadsPerAllocation);
out.writeOptionalVInt(numberOfAllocations);
out.writeVInt(errorCount);
out.writeVInt(rejectedExecutionCount);
out.writeVInt(timeoutCount);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_2_0)) {
out.writeVLong(peakThroughput);
out.writeVLong(throughputLastPeriod);
out.writeOptionalDouble(avgInferenceTimeLastPeriod);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) {
out.writeOptionalVLong(cacheHitCount);
out.writeOptionalVLong(cacheHitCountLastPeriod);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_5_0)) {
out.writeOptionalDouble(avgInferenceTimeExcludingCacheHit);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AssignmentStats.NodeStats that = (AssignmentStats.NodeStats) o;
return Objects.equals(inferenceCount, that.inferenceCount)
&& Objects.equals(that.[MASK], [MASK])
&& Objects.equals(that.avgInferenceTimeExcludingCacheHit, avgInferenceTimeExcludingCacheHit)
&& Objects.equals(node, that.node)
&& Objects.equals(lastAccess, that.lastAccess)
&& Objects.equals(pendingCount, that.pendingCount)
&& Objects.equals(errorCount, that.errorCount)
&& Objects.equals(cacheHitCount, that.cacheHitCount)
&& Objects.equals(rejectedExecutionCount, that.rejectedExecutionCount)
&& Objects.equals(timeoutCount, that.timeoutCount)
&& Objects.equals(routingState, that.routingState)
&& Objects.equals(startTime, that.startTime)
&& Objects.equals(threadsPerAllocation, that.threadsPerAllocation)
&& Objects.equals(numberOfAllocations, that.numberOfAllocations)
&& Objects.equals(peakThroughput, that.peakThroughput)
&& Objects.equals(throughputLastPeriod, that.throughputLastPeriod)
&& Objects.equals(avgInferenceTimeLastPeriod, that.avgInferenceTimeLastPeriod)
&& Objects.equals(cacheHitCountLastPeriod, that.cacheHitCountLastPeriod);
}
@Override
public int hashCode() {
return Objects.hash(
node,
inferenceCount,
[MASK],
avgInferenceTimeExcludingCacheHit,
lastAccess,
pendingCount,
errorCount,
cacheHitCount,
rejectedExecutionCount,
timeoutCount,
routingState,
startTime,
threadsPerAllocation,
numberOfAllocations,
peakThroughput,
throughputLastPeriod,
avgInferenceTimeLastPeriod,
cacheHitCountLastPeriod
);
}
}
private final String deploymentId;
private final String modelId;
private AssignmentState state;
private AllocationStatus allocationStatus;
private String reason;
@Nullable
private final Integer threadsPerAllocation;
@Nullable
private final Integer numberOfAllocations;
@Nullable
private final AdaptiveAllocationsSettings adaptiveAllocationsSettings;
@Nullable
private final Integer queueCapacity;
@Nullable
private final ByteSizeValue cacheSize;
private final Priority priority;
private final Instant startTime;
private final List<AssignmentStats.NodeStats> nodeStats;
public AssignmentStats(
String deploymentId,
String modelId,
@Nullable Integer threadsPerAllocation,
@Nullable Integer numberOfAllocations,
@Nullable AdaptiveAllocationsSettings adaptiveAllocationsSettings,
@Nullable Integer queueCapacity,
@Nullable ByteSizeValue cacheSize,
Instant startTime,
List<AssignmentStats.NodeStats> nodeStats,
Priority priority
) {
this.deploymentId = deploymentId;
this.modelId = modelId;
this.threadsPerAllocation = threadsPerAllocation;
this.numberOfAllocations = numberOfAllocations;
this.adaptiveAllocationsSettings = adaptiveAllocationsSettings;
this.queueCapacity = queueCapacity;
this.startTime = Objects.requireNonNull(startTime);
this.nodeStats = nodeStats;
this.cacheSize = cacheSize;
this.state = null;
this.reason = null;
this.priority = Objects.requireNonNull(priority);
}
public AssignmentStats(StreamInput in) throws IOException {
modelId = in.readString();
threadsPerAllocation = in.readOptionalVInt();
numberOfAllocations = in.readOptionalVInt();
queueCapacity = in.readOptionalVInt();
startTime = in.readInstant();
nodeStats = in.readCollectionAsList(AssignmentStats.NodeStats::new);
state = in.readOptionalEnum(AssignmentState.class);
reason = in.readOptionalString();
allocationStatus = in.readOptionalWriteable(AllocationStatus::new);
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) {
cacheSize = in.readOptionalWriteable(ByteSizeValue::readFrom);
} else {
cacheSize = null;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_6_0)) {
priority = in.readEnum(Priority.class);
} else {
priority = Priority.NORMAL;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
deploymentId = in.readString();
} else {
deploymentId = modelId;
}
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0)) {
adaptiveAllocationsSettings = in.readOptionalWriteable(AdaptiveAllocationsSettings::new);
} else {
adaptiveAllocationsSettings = null;
}
}
public String getDeploymentId() {
return deploymentId;
}
public String getModelId() {
return modelId;
}
@Nullable
public Integer getThreadsPerAllocation() {
return threadsPerAllocation;
}
@Nullable
public Integer getNumberOfAllocations() {
return numberOfAllocations;
}
@Nullable
public AdaptiveAllocationsSettings getAdaptiveAllocationsSettings() {
return adaptiveAllocationsSettings;
}
@Nullable
public Integer getQueueCapacity() {
return queueCapacity;
}
@Nullable
public ByteSizeValue getCacheSize() {
return cacheSize;
}
public Instant getStartTime() {
return startTime;
}
public List<AssignmentStats.NodeStats> getNodeStats() {
return nodeStats;
}
public AssignmentState getState() {
return state;
}
public AssignmentStats setState(AssignmentState state) {
this.state = state;
return this;
}
public AssignmentStats setAllocationStatus(AllocationStatus allocationStatus) {
this.allocationStatus = allocationStatus;
return this;
}
public String getReason() {
return reason;
}
public AssignmentStats setReason(String reason) {
this.reason = reason;
return this;
}
public Priority getPriority() {
return priority;
}
public InferenceStats getOverallInferenceStats() {
return new InferenceStats(
0L,
nodeStats.stream().filter(n -> n.getInferenceCount().isPresent()).mapToLong(n -> n.getInferenceCount().get()).sum(),
nodeStats.stream().mapToLong(n -> n.getErrorCount() + n.getTimeoutCount() + n.getRejectedExecutionCount()).sum(),
0L,
modelId,
null,
Instant.now()
);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
builder.field("deployment_id", deploymentId);
builder.field("model_id", modelId);
if (threadsPerAllocation != null) {
builder.field(StartTrainedModelDeploymentAction.TaskParams.THREADS_PER_ALLOCATION.getPreferredName(), threadsPerAllocation);
}
if (numberOfAllocations != null) {
builder.field(StartTrainedModelDeploymentAction.TaskParams.NUMBER_OF_ALLOCATIONS.getPreferredName(), numberOfAllocations);
}
if (adaptiveAllocationsSettings != null) {
builder.field(StartTrainedModelDeploymentAction.Request.ADAPTIVE_ALLOCATIONS.getPreferredName(), adaptiveAllocationsSettings);
}
if (queueCapacity != null) {
builder.field(StartTrainedModelDeploymentAction.TaskParams.QUEUE_CAPACITY.getPreferredName(), queueCapacity);
}
if (state != null) {
builder.field("state", state);
}
if (reason != null) {
builder.field("reason", reason);
}
if (allocationStatus != null) {
builder.field("allocation_status", allocationStatus);
}
if (cacheSize != null) {
builder.field("cache_size", cacheSize);
}
builder.field("priority", priority);
builder.timestampFieldsFromUnixEpochMillis("start_time", "start_time_string", startTime.toEpochMilli());
int totalErrorCount = nodeStats.stream().mapToInt(NodeStats::getErrorCount).sum();
int totalRejectedExecutionCount = nodeStats.stream().mapToInt(NodeStats::getRejectedExecutionCount).sum();
int totalTimeoutCount = nodeStats.stream().mapToInt(NodeStats::getTimeoutCount).sum();
long totalInferenceCount = nodeStats.stream()
.filter(n -> n.getInferenceCount().isPresent())
.mapToLong(n -> n.getInferenceCount().get())
.sum();
long peakThroughput = nodeStats.stream().mapToLong(NodeStats::getPeakThroughput).sum();
if (totalErrorCount > 0) {
builder.field("error_count", totalErrorCount);
}
if (totalRejectedExecutionCount > 0) {
builder.field("rejected_execution_count", totalRejectedExecutionCount);
}
if (totalTimeoutCount > 0) {
builder.field("timeout_count", totalTimeoutCount);
}
if (totalInferenceCount > 0) {
builder.field("inference_count", totalInferenceCount);
}
builder.field("peak_throughput_per_minute", peakThroughput);
builder.startArray("nodes");
for (AssignmentStats.NodeStats nodeStat : nodeStats) {
nodeStat.toXContent(builder, params);
}
builder.endArray();
builder.endObject();
return builder;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(modelId);
out.writeOptionalVInt(threadsPerAllocation);
out.writeOptionalVInt(numberOfAllocations);
out.writeOptionalVInt(queueCapacity);
out.writeInstant(startTime);
out.writeCollection(nodeStats);
if (AssignmentState.FAILED.equals(state) && out.getTransportVersion().before(TransportVersions.V_8_4_0)) {
out.writeOptionalEnum(AssignmentState.STARTING);
} else {
out.writeOptionalEnum(state);
}
out.writeOptionalString(reason);
out.writeOptionalWriteable(allocationStatus);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_4_0)) {
out.writeOptionalWriteable(cacheSize);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_6_0)) {
out.writeEnum(priority);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_8_0)) {
out.writeString(deploymentId);
}
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0)) {
out.writeOptionalWriteable(adaptiveAllocationsSettings);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AssignmentStats that = (AssignmentStats) o;
return Objects.equals(deploymentId, that.deploymentId)
&& Objects.equals(modelId, that.modelId)
&& Objects.equals(threadsPerAllocation, that.threadsPerAllocation)
&& Objects.equals(numberOfAllocations, that.numberOfAllocations)
&& Objects.equals(adaptiveAllocationsSettings, that.adaptiveAllocationsSettings)
&& Objects.equals(queueCapacity, that.queueCapacity)
&& Objects.equals(startTime, that.startTime)
&& Objects.equals(state, that.state)
&& Objects.equals(reason, that.reason)
&& Objects.equals(allocationStatus, that.allocationStatus)
&& Objects.equals(cacheSize, that.cacheSize)
&& Objects.equals(nodeStats, that.nodeStats)
&& priority == that.priority;
}
@Override
public int hashCode() {
return Objects.hash(
deploymentId,
modelId,
threadsPerAllocation,
numberOfAllocations,
adaptiveAllocationsSettings,
queueCapacity,
startTime,
nodeStats,
state,
reason,
allocationStatus,
cacheSize,
priority
);
}
@Override
public String toString() {
return Strings.toString(this);
}
} | avgInferenceTime | java | elasticsearch |
package antlr;
@Deprecated
public class ANTLRException extends IllegalArgumentException {
public ANTLRException(String [MASK]) {
super([MASK]);
}
public ANTLRException(String [MASK], Throwable cause) {
super([MASK], cause);
}
public ANTLRException(Throwable cause) {
super(cause);
}
} | message | java | jenkins |
package com.google.refine.importers.tree;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.refine.importers.ImporterUtilities;
import com.google.refine.model.Cell;
import com.google.refine.model.Column;
import com.google.refine.model.Project;
public abstract class TreeImportUtilities {
final static Logger logger = LoggerFactory.getLogger("TreeImportUtilities");
static protected void sortRecordElementCandidates(List<RecordElementCandidate> list) {
Collections.sort(list, new Comparator<RecordElementCandidate>() {
@Override
public int compare(RecordElementCandidate o1, RecordElementCandidate o2) {
return o2.count - o1.count;
}
});
}
static public void createColumnsFromImport(
Project project,
ImportColumnGroup columnGroup) {
int startColumnIndex = project.columnModel.columns.size();
List<ImportColumn> columns = new ArrayList<ImportColumn>(columnGroup.columns.values());
Collections.sort(columns, new Comparator<ImportColumn>() {
@Override
public int compare(ImportColumn o1, ImportColumn o2) {
if (o1.blankOnFirstRow != o2.blankOnFirstRow) {
return o1.blankOnFirstRow ? 1 : -1;
}
return o2.nonBlankCount - o1.nonBlankCount;
}
});
for (int i = 0; i < columns.size(); i++) {
ImportColumn c = columns.get(i);
Column column = new com.google.refine.model.Column(c.cellIndex, c.name);
project.columnModel.columns.add(column);
}
List<ImportColumnGroup> subgroups = new ArrayList<ImportColumnGroup>(columnGroup.subgroups.values());
Collections.sort(subgroups, new Comparator<ImportColumnGroup>() {
@Override
public int compare(ImportColumnGroup o1, ImportColumnGroup o2) {
return o2.nonBlankCount - o1.nonBlankCount;
}
});
for (ImportColumnGroup g : subgroups) {
createColumnsFromImport(project, g);
}
int endColumnIndex = project.columnModel.columns.size();
int span = endColumnIndex - startColumnIndex;
if (span > 1 && span < project.columnModel.columns.size()) {
project.columnModel.addColumnGroup(startColumnIndex, span, startColumnIndex);
}
}
@Deprecated
static protected void addCell(
Project project,
ImportColumnGroup columnGroup,
ImportRecord record,
String columnLocalName,
String text) {
addCell(project, columnGroup, record, columnLocalName, text, true, true);
}
static protected void addCell(
Project project,
ImportColumnGroup columnGroup,
ImportRecord record,
String columnLocalName,
String text,
boolean [MASK],
boolean guessDataType) {
Serializable value = text;
if (![MASK] && (text == null || (text).isEmpty())) {
return;
}
if (guessDataType) {
value = ImporterUtilities.parseCellValue(text);
}
addCell(project, columnGroup, record, columnLocalName, value);
}
protected static void addCell(Project project, ImportColumnGroup columnGroup, ImportRecord record,
String columnLocalName, Serializable value) {
ImportColumn column = getColumn(project, columnGroup, columnLocalName);
int cellIndex = column.cellIndex;
int rowIndex = Math.max(columnGroup.nextRowIndex, column.nextRowIndex);
List<Cell> row = record.rows.get(rowIndex);
if (row == null) {
row = new ArrayList<Cell>();
record.rows.set(rowIndex, row);
}
while (cellIndex >= row.size()) {
row.add(null);
}
row.set(cellIndex, new Cell(value, null));
column.nextRowIndex = rowIndex + 1;
column.nonBlankCount++;
}
static protected ImportColumn getColumn(
Project project,
ImportColumnGroup columnGroup,
String localName) {
if (columnGroup.columns.containsKey(localName)) {
return columnGroup.columns.get(localName);
}
ImportColumn column = createColumn(project, columnGroup, localName);
columnGroup.columns.put(localName, column);
return column;
}
static protected ImportColumn createColumn(
Project project,
ImportColumnGroup columnGroup,
String localName) {
ImportColumn newColumn = new ImportColumn();
newColumn.name = columnGroup.name.length() == 0 ? (localName == null ? "Text" : localName)
: (localName == null ? columnGroup.name : (columnGroup.name + " - " + localName));
newColumn.cellIndex = project.columnModel.allocateNewCellIndex();
newColumn.nextRowIndex = columnGroup.nextRowIndex;
return newColumn;
}
static protected ImportColumnGroup getColumnGroup(
Project project,
ImportColumnGroup columnGroup,
String localName) {
if (columnGroup.subgroups.containsKey(localName)) {
return columnGroup.subgroups.get(localName);
}
ImportColumnGroup subgroup = createColumnGroup(project, columnGroup, localName);
columnGroup.subgroups.put(localName, subgroup);
return subgroup;
}
static protected ImportColumnGroup createColumnGroup(
Project project,
ImportColumnGroup columnGroup,
String localName) {
ImportColumnGroup newGroup = new ImportColumnGroup();
newGroup.name = columnGroup.name.length() == 0 ? (localName == null ? "Text" : localName)
: (localName == null ? columnGroup.name : (columnGroup.name + " - " + localName));
newGroup.nextRowIndex = columnGroup.nextRowIndex;
return newGroup;
}
} | storeEmptyString | java | OpenRefine |
package dagger.internal;
import java.lang.reflect.AccessibleObject;
public abstract class Loader {
private final Memoizer<ClassLoader, Memoizer<String, Class<?>>> caches =
new Memoizer<ClassLoader, Memoizer<String, Class<?>>>() {
@Override protected Memoizer<String, Class<?>> create(final ClassLoader classLoader) {
return new Memoizer<String, Class<?>>() {
@Override protected Class<?> create(String className) {
try {
return classLoader.loadClass(className);
} catch (ClassNotFoundException e) {
return Void.class;
}
}
};
}
};
public abstract Binding<?> getAtInjectBinding(
String key, String className, ClassLoader classLoader, boolean mustHaveInjections);
public abstract <T> ModuleAdapter<T> getModuleAdapter(Class<T> moduleClass);
public abstract StaticInjection getStaticInjection(Class<?> [MASK]);
protected Class<?> loadClass(ClassLoader classLoader, String name) {
classLoader = (classLoader != null) ? classLoader : ClassLoader.getSystemClassLoader();
return caches.get(classLoader).get(name);
}
protected <T> T instantiate(String name, ClassLoader classLoader) {
try {
Class<?> generatedClass = loadClass(classLoader, name);
if (generatedClass == Void.class) {
return null;
}
@SuppressWarnings("unchecked")
T instance = (T) generatedClass.newInstance();
return instance;
} catch (InstantiationException e) {
throw new RuntimeException("Failed to initialize " + name, e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Failed to initialize " + name, e);
}
}
} | injectedClass | java | dagger |
package jenkins.security;
import static org.springframework.security.core.context.SecurityContextHolder.getContext;
import static org.springframework.security.core.context.SecurityContextHolder.setContext;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import jenkins.util.InterceptingExecutorService;
import org.springframework.security.core.context.SecurityContext;
public class SecurityContextExecutorService extends InterceptingExecutorService {
public SecurityContextExecutorService(ExecutorService service) {
super(service);
}
@Override
protected Runnable wrap(final Runnable r) {
final SecurityContext callingContext = getContext();
return new Runnable() {
@Override
public void run() {
SecurityContext [MASK] = getContext();
setContext(callingContext);
try {
r.run();
} finally {
setContext([MASK]);
}
}
};
}
@Override
protected <V> Callable<V> wrap(final Callable<V> c) {
final SecurityContext callingContext = getContext();
return new Callable<>() {
@Override
public V call() throws Exception {
SecurityContext [MASK] = getContext();
setContext(callingContext);
try {
return c.call();
} finally {
setContext([MASK]);
}
}
};
}
} | old | java | jenkins |
package com.google.devtools.common.options;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.escape.Escaper;
import com.google.common.html.HtmlEscapers;
import com.google.devtools.common.options.OptionsParser.HelpVerbosity;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class OptionsUsageTest {
private OptionsData data;
private static final Escaper HTML_ESCAPER = HtmlEscapers.htmlEscaper();
@Before
public void setUp() {
data = OptionsParser.getOptionsDataInternal(TestOptions.class);
}
private String getHtmlUsageWithoutTags(String [MASK]) {
StringBuilder builder = new StringBuilder();
OptionsUsage.getUsageHtml(
data.getOptionDefinitionFromName([MASK]), builder, HTML_ESCAPER, data, false, null);
return builder.toString();
}
private String getHtmlUsageWithTags(String [MASK]) {
StringBuilder builder = new StringBuilder();
OptionsUsage.getUsageHtml(
data.getOptionDefinitionFromName([MASK]), builder, HTML_ESCAPER, data, true, null);
return builder.toString();
}
private String getHtmlUsageWithCommandName(String [MASK], String commandName) {
StringBuilder builder = new StringBuilder();
OptionsUsage.getUsageHtml(
data.getOptionDefinitionFromName([MASK]),
builder,
HTML_ESCAPER,
data,
false,
commandName);
return builder.toString();
}
private String getTerminalUsageWithoutTags(String [MASK], HelpVerbosity verbosity) {
StringBuilder builder = new StringBuilder();
OptionsUsage.getUsage(
data.getOptionDefinitionFromName([MASK]), builder, verbosity, data, false);
return builder.toString();
}
private String getTerminalUsageWithTags(String [MASK], HelpVerbosity verbosity) {
StringBuilder builder = new StringBuilder();
OptionsUsage.getUsage(
data.getOptionDefinitionFromName([MASK]), builder, verbosity, data, true);
return builder.toString();
}
@Test
public void commandNameAnchorId_htmlOutput() {
assertThat(getHtmlUsageWithCommandName("test_string", "command_name"))
.isEqualTo(
"<dt id=\"command_name-flag--test_string\"><code id=\"test_string\"><a"
+ " href=\"#command_name-flag--test_string\">--test_string</a>=<a"
+ " string></code> default: \"test string default\"</dt>\n"
+ "<dd>\n"
+ "a string-valued option to test simple option operations\n"
+ "</dd>\n");
}
@Test
public void stringValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_string", HelpVerbosity.SHORT))
.isEqualTo(" --test_string\n");
assertThat(getTerminalUsageWithoutTags("test_string", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_string", HelpVerbosity.SHORT));
}
@Test
public void stringValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_string", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_string (a string; default: \"test string default\")\n");
assertThat(getTerminalUsageWithoutTags("test_string", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_string", HelpVerbosity.MEDIUM));
}
@Test
public void stringValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_string", HelpVerbosity.LONG))
.isEqualTo(
" --test_string (a string; default: \"test string default\")\n"
+ " a string-valued option to test simple option operations\n");
assertThat(getTerminalUsageWithTags("test_string", HelpVerbosity.LONG))
.isEqualTo(
" --test_string (a string; default: \"test string default\")\n"
+ " a string-valued option to test simple option operations\n"
+ " Tags: no_op\n");
}
@Test
public void stringValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_string"))
.isEqualTo(
"<dt id=\"flag--test_string\"><code><a href=\"#flag--test_string\">--test_string</a>"
+ "=<a string></code> default: \"test string default\"</dt>\n"
+ "<dd>\n"
+ "a string-valued option to test simple option operations\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_string"))
.isEqualTo(
"<dt id=\"flag--test_string\"><code><a href=\"#flag--test_string\">--test_string</a>"
+ "=<a string></code> default: \"test string default\"</dt>\n"
+ "<dd>\n"
+ "a string-valued option to test simple option operations\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
@Test
public void intValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_c", HelpVerbosity.SHORT))
.isEqualTo(" --expanded_c\n");
assertThat(getTerminalUsageWithoutTags("expanded_c", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("expanded_c", HelpVerbosity.SHORT));
}
@Test
public void intValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_c", HelpVerbosity.MEDIUM))
.isEqualTo(" --expanded_c (an integer; default: \"12\")\n");
assertThat(getTerminalUsageWithoutTags("expanded_c", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("expanded_c", HelpVerbosity.MEDIUM));
}
@Test
public void intValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_c", HelpVerbosity.LONG))
.isEqualTo(
" --expanded_c (an integer; default: \"12\")\n"
+ " an int-value'd flag used to test expansion logic\n");
assertThat(getTerminalUsageWithTags("expanded_c", HelpVerbosity.LONG))
.isEqualTo(
" --expanded_c (an integer; default: \"12\")\n"
+ " an int-value'd flag used to test expansion logic\n"
+ " Tags: no_op\n");
}
@Test
public void intValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("expanded_c"))
.isEqualTo(
"<dt id=\"flag--expanded_c\"><code>"
+ "<a href=\"#flag--expanded_c\">--expanded_c</a>"
+ "=<an integer></code> default: \"12\"</dt>\n"
+ "<dd>\n"
+ "an int-value'd flag used to test expansion logic\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("expanded_c"))
.isEqualTo(
"<dt id=\"flag--expanded_c\"><code>"
+ "<a href=\"#flag--expanded_c\">--expanded_c</a>"
+ "=<an integer></code> default: \"12\"</dt>\n"
+ "<dd>\n"
+ "an int-value'd flag used to test expansion logic\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
@Test
public void booleanValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.SHORT))
.isEqualTo(" --[no]expanded_a\n");
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("expanded_a", HelpVerbosity.SHORT));
}
@Test
public void booleanValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.MEDIUM))
.isEqualTo(" --[no]expanded_a (a boolean; default: \"true\")\n");
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("expanded_a", HelpVerbosity.MEDIUM));
}
@Test
public void booleanValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.LONG))
.isEqualTo(
" --[no]expanded_a (a boolean; default: \"true\")\n"
+ " A boolean flag with unknown effect to test tagless usage text.\n");
assertThat(getTerminalUsageWithoutTags("expanded_a", HelpVerbosity.LONG))
.isEqualTo(getTerminalUsageWithTags("expanded_a", HelpVerbosity.LONG));
}
@Test
public void booleanValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("expanded_a"))
.isEqualTo(
"<dt id=\"flag--expanded_a\"><code><a href=\"#flag--expanded_a\">"
+ "--[no]expanded_a</a></code> default: \"true\"</dt>\n"
+ "<dd>\n"
+ "A boolean flag with unknown effect to test tagless usage text.\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithoutTags("expanded_a")).isEqualTo(getHtmlUsageWithTags("expanded_a"));
}
@Test
public void multipleValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_multiple_string", HelpVerbosity.SHORT))
.isEqualTo(" --test_multiple_string\n");
assertThat(getTerminalUsageWithoutTags("test_multiple_string", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_multiple_string", HelpVerbosity.SHORT));
}
@Test
public void multipleValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_multiple_string", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_multiple_string (a string; may be used multiple times)\n");
assertThat(getTerminalUsageWithoutTags("test_multiple_string", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_multiple_string", HelpVerbosity.MEDIUM));
}
@Test
public void multipleValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_multiple_string", HelpVerbosity.LONG))
.isEqualTo(
" --test_multiple_string (a string; may be used multiple times)\n"
+ " a repeatable string-valued flag with its own unhelpful help text\n");
assertThat(getTerminalUsageWithTags("test_multiple_string", HelpVerbosity.LONG))
.isEqualTo(
" --test_multiple_string (a string; may be used multiple times)\n"
+ " a repeatable string-valued flag with its own unhelpful help text\n"
+ " Tags: no_op\n");
}
@Test
public void multipleValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_multiple_string"))
.isEqualTo(
"<dt id=\"flag--test_multiple_string\"><code>"
+ "<a href=\"#flag--test_multiple_string\">--test_multiple_string</a>"
+ "=<a string></code> "
+ "multiple uses are accumulated</dt>\n"
+ "<dd>\n"
+ "a repeatable string-valued flag with its own unhelpful help text\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_multiple_string"))
.isEqualTo(
"<dt id=\"flag--test_multiple_string\"><code>"
+ "<a href=\"#flag--test_multiple_string\">--test_multiple_string</a>"
+ "=<a string></code> "
+ "multiple uses are accumulated</dt>\n"
+ "<dd>\n"
+ "a repeatable string-valued flag with its own unhelpful help text\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
@Test
public void customConverterValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_list_converters", HelpVerbosity.SHORT))
.isEqualTo(" --test_list_converters\n");
assertThat(getTerminalUsageWithoutTags("test_list_converters", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_list_converters", HelpVerbosity.SHORT));
}
@Test
public void customConverterValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_list_converters", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_list_converters (a list of strings; may be used multiple times)\n");
assertThat(getTerminalUsageWithoutTags("test_list_converters", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_list_converters", HelpVerbosity.MEDIUM));
}
@Test
public void customConverterValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_list_converters", HelpVerbosity.LONG))
.isEqualTo(
" --test_list_converters (a list of strings; may be used multiple times)\n"
+ " a repeatable flag that accepts lists, but doesn't want to have lists of \n"
+ " lists as a final type\n");
assertThat(getTerminalUsageWithTags("test_list_converters", HelpVerbosity.LONG))
.isEqualTo(
" --test_list_converters (a list of strings; may be used multiple times)\n"
+ " a repeatable flag that accepts lists, but doesn't want to have lists of \n"
+ " lists as a final type\n"
+ " Tags: no_op\n");
}
@Test
public void customConverterValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_list_converters"))
.isEqualTo(
"<dt id=\"flag--test_list_converters\"><code>"
+ "<a href=\"#flag--test_list_converters\">--test_list_converters</a>"
+ "=<a list of strings></code> "
+ "multiple uses are accumulated</dt>\n"
+ "<dd>\n"
+ "a repeatable flag that accepts lists, but doesn't want to have lists of "
+ "lists as a final type\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_list_converters"))
.isEqualTo(
"<dt id=\"flag--test_list_converters\"><code>"
+ "<a href=\"#flag--test_list_converters\">--test_list_converters</a>"
+ "=<a list of strings></code> "
+ "multiple uses are accumulated</dt>\n"
+ "<dd>\n"
+ "a repeatable flag that accepts lists, but doesn't want to have lists of "
+ "lists as a final type\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
@Test
public void staticExpansionOption_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion", HelpVerbosity.SHORT))
.isEqualTo(" --test_expansion\n");
assertThat(getTerminalUsageWithoutTags("test_expansion", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_expansion", HelpVerbosity.SHORT));
}
@Test
public void staticExpansionOption_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_expansion\n");
assertThat(getTerminalUsageWithoutTags("test_expansion", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_expansion", HelpVerbosity.MEDIUM));
}
@Test
public void staticExpansionOption_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion", HelpVerbosity.LONG))
.isEqualTo(
" --test_expansion\n"
+ " this expands to an alphabet soup.\n"
+ " Expands to: --noexpanded_a --expanded_b=false --expanded_c 42 --\n"
+ " expanded_d bar \n");
assertThat(getTerminalUsageWithTags("test_expansion", HelpVerbosity.LONG))
.isEqualTo(
" --test_expansion\n"
+ " this expands to an alphabet soup.\n"
+ " Expands to: --noexpanded_a --expanded_b=false --expanded_c 42 --\n"
+ " expanded_d bar \n"
+ " Tags: no_op\n");
}
@Test
public void staticExpansionOption_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_expansion"))
.isEqualTo(
"<dt id=\"flag--test_expansion\"><code><a href=\"#flag--test_expansion\">"
+ "--test_expansion</a></code></dt>\n"
+ "<dd>\n"
+ "this expands to an alphabet soup.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code>"
+ "<a href=\"#flag--noexpanded_a\">--noexpanded_a</a></code><br/>\n"
+ " <code>"
+ "<a href=\"#flag--expanded_b\">--expanded_b=false</a></code><br/>\n"
+ " <code><a href=\"#flag--expanded_c\">--expanded_c</a></code><br/>\n"
+ " <code><a href=\"#flag42\">42</a></code><br/>\n"
+ " <code><a href=\"#flag--expanded_d\">--expanded_d</a></code><br/>\n"
+ " <code><a href=\"#flagbar\">bar</a></code><br/>\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_expansion"))
.isEqualTo(
"<dt id=\"flag--test_expansion\"><code><a href=\"#flag--test_expansion\">"
+ "--test_expansion</a></code></dt>\n"
+ "<dd>\n"
+ "this expands to an alphabet soup.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code>"
+ "<a href=\"#flag--noexpanded_a\">--noexpanded_a</a></code><br/>\n"
+ " <code>"
+ "<a href=\"#flag--expanded_b\">--expanded_b=false</a></code><br/>\n"
+ " <code><a href=\"#flag--expanded_c\">--expanded_c</a></code><br/>\n"
+ " <code><a href=\"#flag42\">42</a></code><br/>\n"
+ " <code><a href=\"#flag--expanded_d\">--expanded_d</a></code><br/>\n"
+ " <code><a href=\"#flagbar\">bar</a></code><br/>\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
@Test
public void recursiveExpansionOption_shortTerminalOutput() {
assertThat(
getTerminalUsageWithoutTags("test_recursive_expansion_top_level", HelpVerbosity.SHORT))
.isEqualTo(" --test_recursive_expansion_top_level\n");
assertThat(
getTerminalUsageWithoutTags("test_recursive_expansion_top_level", HelpVerbosity.SHORT))
.isEqualTo(
getTerminalUsageWithTags("test_recursive_expansion_top_level", HelpVerbosity.SHORT));
}
@Test
public void recursiveExpansionOption_mediumTerminalOutput() {
assertThat(
getTerminalUsageWithoutTags("test_recursive_expansion_top_level", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_recursive_expansion_top_level\n");
assertThat(
getTerminalUsageWithoutTags("test_recursive_expansion_top_level", HelpVerbosity.MEDIUM))
.isEqualTo(
getTerminalUsageWithTags("test_recursive_expansion_top_level", HelpVerbosity.MEDIUM));
}
@Test
public void recursiveExpansionOption_longTerminalOutput() {
assertThat(
getTerminalUsageWithoutTags("test_recursive_expansion_top_level", HelpVerbosity.LONG))
.isEqualTo(
" --test_recursive_expansion_top_level\n"
+ " Lets the children do all the work.\n"
+ " Expands to: --test_recursive_expansion_middle1 --\n"
+ " test_recursive_expansion_middle2 \n");
assertThat(getTerminalUsageWithTags("test_recursive_expansion_top_level", HelpVerbosity.LONG))
.isEqualTo(
" --test_recursive_expansion_top_level\n"
+ " Lets the children do all the work.\n"
+ " Expands to: --test_recursive_expansion_middle1 --\n"
+ " test_recursive_expansion_middle2 \n"
+ " Tags: no_op\n");
}
@Test
public void recursiveExpansionOption_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_recursive_expansion_top_level"))
.isEqualTo(
"<dt id=\"flag--test_recursive_expansion_top_level\"><code><a"
+ " href=\"#flag--test_recursive_expansion_top_level\">--test_recursive_expansion_top_level</a></code></dt>\n"
+ "<dd>\n"
+ "Lets the children do all the work.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code><a"
+ " href=\"#flag--test_recursive_expansion_middle1\">--test_recursive_expansion_middle1</a></code><br/>\n"
+ " <code><a"
+ " href=\"#flag--test_recursive_expansion_middle2\">--test_recursive_expansion_middle2</a></code><br/>\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_recursive_expansion_top_level"))
.isEqualTo(
"<dt id=\"flag--test_recursive_expansion_top_level\"><code><a"
+ " href=\"#flag--test_recursive_expansion_top_level\">--test_recursive_expansion_top_level</a></code></dt>\n"
+ "<dd>\n"
+ "Lets the children do all the work.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code><a"
+ " href=\"#flag--test_recursive_expansion_middle1\">--test_recursive_expansion_middle1</a></code><br/>\n"
+ " <code><a"
+ " href=\"#flag--test_recursive_expansion_middle2\">--test_recursive_expansion_middle2</a></code><br/>\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a></dd>\n");
}
@Test
public void expansionToMultipleValue_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion_to_repeatable", HelpVerbosity.SHORT))
.isEqualTo(" --test_expansion_to_repeatable\n");
assertThat(getTerminalUsageWithoutTags("test_expansion_to_repeatable", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_expansion_to_repeatable", HelpVerbosity.SHORT));
}
@Test
public void expansionToMultipleValue_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion_to_repeatable", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_expansion_to_repeatable\n");
assertThat(getTerminalUsageWithoutTags("test_expansion_to_repeatable", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_expansion_to_repeatable", HelpVerbosity.MEDIUM));
}
@Test
public void expansionToMultipleValue_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_expansion_to_repeatable", HelpVerbosity.LONG))
.isEqualTo(
" --test_expansion_to_repeatable\n"
+ " Go forth and multiply, they said.\n"
+ " Expands to: --test_multiple_string=expandedFirstValue --\n"
+ " test_multiple_string=expandedSecondValue \n");
assertThat(getTerminalUsageWithTags("test_expansion_to_repeatable", HelpVerbosity.LONG))
.isEqualTo(
" --test_expansion_to_repeatable\n"
+ " Go forth and multiply, they said.\n"
+ " Expands to: --test_multiple_string=expandedFirstValue --\n"
+ " test_multiple_string=expandedSecondValue \n"
+ " Tags: no_op\n");
}
@Test
public void expansionToMultipleValue_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_expansion_to_repeatable"))
.isEqualTo(
"<dt id=\"flag--test_expansion_to_repeatable\"><code><a"
+ " href=\"#flag--test_expansion_to_repeatable\">--test_expansion_to_repeatable</a></code></dt>\n"
+ "<dd>\n"
+ "Go forth and multiply, they said.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code><a"
+ " href=\"#flag--test_multiple_string\">--test_multiple_string=expandedFirstValue</a></code><br/>\n"
+ " <code><a"
+ " href=\"#flag--test_multiple_string\">--test_multiple_string=expandedSecondValue</a></code><br/>\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_expansion_to_repeatable"))
.isEqualTo(
"<dt id=\"flag--test_expansion_to_repeatable\"><code><a"
+ " href=\"#flag--test_expansion_to_repeatable\">--test_expansion_to_repeatable</a></code></dt>\n"
+ "<dd>\n"
+ "Go forth and multiply, they said.\n"
+ "<br/>\n"
+ "Expands to:<br/>\n"
+ " <code><a"
+ " href=\"#flag--test_multiple_string\">--test_multiple_string=expandedFirstValue</a></code><br/>\n"
+ " <code><a"
+ " href=\"#flag--test_multiple_string\">--test_multiple_string=expandedSecondValue</a></code><br/>\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a></dd>\n");
}
@Test
public void implicitRequirementOption_shortTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_implicit_requirement", HelpVerbosity.SHORT))
.isEqualTo(" --test_implicit_requirement\n");
assertThat(getTerminalUsageWithoutTags("test_implicit_requirement", HelpVerbosity.SHORT))
.isEqualTo(getTerminalUsageWithTags("test_implicit_requirement", HelpVerbosity.SHORT));
}
@Test
public void implicitRequirementOption_mediumTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_implicit_requirement", HelpVerbosity.MEDIUM))
.isEqualTo(" --test_implicit_requirement (a string; default: \"direct implicit\")\n");
assertThat(getTerminalUsageWithoutTags("test_implicit_requirement", HelpVerbosity.MEDIUM))
.isEqualTo(getTerminalUsageWithTags("test_implicit_requirement", HelpVerbosity.MEDIUM));
}
@Test
public void implicitRequirementOption_longTerminalOutput() {
assertThat(getTerminalUsageWithoutTags("test_implicit_requirement", HelpVerbosity.LONG))
.isEqualTo(
" --test_implicit_requirement (a string; default: \"direct implicit\")\n"
+ " this option really needs that other one, isolation of purpose has failed.\n"
+ " Using this option will also add: --implicit_requirement_a=implicit \n"
+ " requirement, required \n");
assertThat(getTerminalUsageWithTags("test_implicit_requirement", HelpVerbosity.LONG))
.isEqualTo(
" --test_implicit_requirement (a string; default: \"direct implicit\")\n"
+ " this option really needs that other one, isolation of purpose has failed.\n"
+ " Using this option will also add: --implicit_requirement_a=implicit \n"
+ " requirement, required \n"
+ " Tags: no_op\n");
}
@Test
public void implicitRequirementOption_htmlOutput() {
assertThat(getHtmlUsageWithoutTags("test_implicit_requirement"))
.isEqualTo(
"<dt id=\"flag--test_implicit_requirement\"><code>"
+ "<a href=\"#flag--test_implicit_requirement\">--test_implicit_requirement</a>"
+ "=<a string></code> "
+ "default: \"direct implicit\"</dt>\n"
+ "<dd>\n"
+ "this option really needs that other one, isolation of purpose has failed.\n"
+ "</dd>\n");
assertThat(getHtmlUsageWithTags("test_implicit_requirement"))
.isEqualTo(
"<dt id=\"flag--test_implicit_requirement\"><code>"
+ "<a href=\"#flag--test_implicit_requirement\">--test_implicit_requirement</a>"
+ "=<a string></code> "
+ "default: \"direct implicit\"</dt>\n"
+ "<dd>\n"
+ "this option really needs that other one, isolation of purpose has failed.\n"
+ "<br>Tags:\n"
+ "<a href=\"#effect_tag_NO_OP\"><code>no_op</code></a>"
+ "</dd>\n");
}
} | fieldName | java | bazel |
package org.springframework.cache.interceptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
import org.springframework.core.KotlinDetector;
public class SimpleKeyGenerator implements KeyGenerator {
@Override
public Object generate(Object [MASK], Method method, @Nullable Object... params) {
return generateKey((KotlinDetector.isSuspendingFunction(method) ?
Arrays.copyOf(params, params.length - 1) : params));
}
public static Object generateKey(@Nullable Object... params) {
if (params.length == 0) {
return SimpleKey.EMPTY;
}
if (params.length == 1) {
Object param = params[0];
if (param != null && !param.getClass().isArray()) {
return param;
}
}
return new SimpleKey(params);
}
} | target | java | spring-framework |
package org.elasticsearch.entitlement.bridge;
import java.util.Optional;
import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;
public class Util {
public static final Class<?> NO_CLASS = new Object() {
}.getClass();
@SuppressWarnings("unused")
public static Class<?> getCallerClass() {
Optional<Class<?>> [MASK] = StackWalker.getInstance(RETAIN_CLASS_REFERENCE)
.walk(
frames -> frames.skip(2)
.findFirst()
.map(StackWalker.StackFrame::getDeclaringClass)
);
return [MASK].orElse(NO_CLASS);
}
} | callerClassIfAny | java | elasticsearch |
package org.springframework.web.accept;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
public class SemanticApiVersionParserTests {
private final SemanticApiVersionParser parser = new SemanticApiVersionParser();
@Test
void parse() {
testParse("0", 0, 0, 0);
testParse("0.3", 0, 3, 0);
testParse("4.5", 4, 5, 0);
testParse("6.7.8", 6, 7, 8);
testParse("v01", 1, 0, 0);
testParse("version-1.2", 1, 2, 0);
}
private void testParse(String input, int major, int [MASK], int patch) {
SemanticApiVersionParser.Version actual = this.parser.parseVersion(input);
assertThat(actual.getMajor()).isEqualTo(major);
assertThat(actual.getMinor()).isEqualTo([MASK]);
assertThat(actual.getPatch()).isEqualTo(patch);
}
@ParameterizedTest
@ValueSource(strings = {"", "v", "1a", "1.0a", "1.0.0a", "1.0.0.", "1.0.0-"})
void parseInvalid(String input) {
testParseInvalid(input);
}
private void testParseInvalid(String input) {
assertThatIllegalStateException().isThrownBy(() -> this.parser.parseVersion(input))
.withMessage("Invalid API version format");
}
} | minor | java | spring-framework |
package com.google.devtools.build.lib.server;
import static com.google.common.truth.Truth.assertThat;
import static com.google.devtools.build.lib.testutil.TestUtils.WAIT_TIMEOUT_SECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.clock.JavaClock;
import com.google.devtools.build.lib.runtime.BlazeCommandResult;
import com.google.devtools.build.lib.runtime.CommandDispatcher;
import com.google.devtools.build.lib.runtime.proto.InvocationPolicyOuterClass.InvocationPolicy;
import com.google.devtools.build.lib.server.CommandProtos.CancelRequest;
import com.google.devtools.build.lib.server.CommandProtos.CancelResponse;
import com.google.devtools.build.lib.server.CommandProtos.EnvironmentVariable;
import com.google.devtools.build.lib.server.CommandProtos.RunRequest;
import com.google.devtools.build.lib.server.CommandProtos.RunResponse;
import com.google.devtools.build.lib.server.CommandServerGrpc.CommandServerStub;
import com.google.devtools.build.lib.server.FailureDetails.Command;
import com.google.devtools.build.lib.server.FailureDetails.FailureDetail;
import com.google.devtools.build.lib.server.FailureDetails.GrpcServer;
import com.google.devtools.build.lib.server.FailureDetails.Interrupted;
import com.google.devtools.build.lib.server.FailureDetails.Interrupted.Code;
import com.google.devtools.build.lib.server.GrpcServerImpl.BlockingStreamObserver;
import com.google.devtools.build.lib.testutil.TestUtils;
import com.google.devtools.build.lib.util.Pair;
import com.google.devtools.build.lib.util.io.CommandExtensionReporter;
import com.google.devtools.build.lib.util.io.OutErr;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import com.google.protobuf.BytesValue;
import com.google.protobuf.Int32Value;
import com.google.protobuf.StringValue;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.inprocess.InProcessChannelBuilder;
import io.grpc.inprocess.InProcessServerBuilder;
import io.grpc.stub.ServerCallStreamObserver;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public final class GrpcServerTest {
private static final int SERVER_PID = 42;
private static final String REQUEST_COOKIE = "request-cookie";
private final FileSystem fileSystem = new InMemoryFileSystem(DigestHashFunction.SHA256);
private Server server;
private ManagedChannel channel;
private void createServer(CommandDispatcher dispatcher) throws Exception {
Path serverDirectory = fileSystem.getPath("/bazel_server_directory");
serverDirectory.createDirectoryAndParents();
GrpcServerImpl serverImpl =
new GrpcServerImpl(
dispatcher,
ShutdownHooks.createUnregistered(),
new PidFileWatcher(fileSystem.getPath("/thread-not-running-dont-need"), SERVER_PID),
new JavaClock(),
-1,
REQUEST_COOKIE,
"response-cookie",
serverDirectory,
SERVER_PID,
1000,
false,
false,
"slow interrupt message suffix");
String uniqueName = InProcessServerBuilder.generateName();
server =
InProcessServerBuilder.forName(uniqueName)
.directExecutor()
.addService(serverImpl)
.build()
.start();
channel = InProcessChannelBuilder.forName(uniqueName).directExecutor().build();
}
private static RunRequest createRequest(String... args) {
return RunRequest.newBuilder()
.setCookie(REQUEST_COOKIE)
.setClientDescription("client-description")
.addAllArg(Arrays.stream(args).map(ByteString::copyFromUtf8).collect(Collectors.toList()))
.build();
}
private static RunRequest createPreemptibleRequest(String... args) {
return RunRequest.newBuilder()
.setCookie(REQUEST_COOKIE)
.setClientDescription("client-description")
.setPreemptible(true)
.addAllArg(Arrays.stream(args).map(ByteString::copyFromUtf8).collect(Collectors.toList()))
.build();
}
@Test
public void testSendingSimpleMessage() throws Exception {
Any commandExtension = Any.pack(EnvironmentVariable.getDefaultInstance());
AtomicReference<List<String>> argsReceived = new AtomicReference<>();
AtomicReference<List<Any>> commandExtensionsReceived = new AtomicReference<>();
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter) {
argsReceived.set(args);
commandExtensionsReceived.set(commandExtensions);
return BlazeCommandResult.success();
}
};
createServer(dispatcher);
CountDownLatch done = new CountDownLatch(1);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
stub.run(
createRequest("Foo").toBuilder().addCommandExtensions(commandExtension).build(),
createResponseObserver(responses, done));
done.await();
server.shutdown();
server.awaitTermination();
assertThat(argsReceived.get()).containsExactly("Foo");
assertThat(commandExtensionsReceived.get()).containsExactly(commandExtension);
assertThat(responses).hasSize(2);
assertThat(responses.get(0).getFinished()).isFalse();
assertThat(responses.get(0).getCookie()).isNotEmpty();
assertThat(responses.get(1).getFinished()).isTrue();
assertThat(responses.get(1).getExitCode()).isEqualTo(0);
assertThat(responses.get(1).hasFailureDetail()).isFalse();
}
@Test
public void testReceiveStreamingCommandExtensions() throws Exception {
Any commandExtension1 = Any.pack(Int32Value.of(4));
Any commandExtension2 = Any.pack(Int32Value.of(8));
Any commandExtension3 = Any.pack(Int32Value.of(15));
CountDownLatch afterFirstExtensionLatch = new CountDownLatch(1);
CountDownLatch beforeSecondExtensionLatch = new CountDownLatch(1);
CountDownLatch afterSecondExtensionLatch = new CountDownLatch(1);
CountDownLatch beforeThirdExtensionLatch = new CountDownLatch(1);
CountDownLatch afterThirdExtensionLatch = new CountDownLatch(1);
CommandDispatcher dispatcher =
(policy,
args,
outErr,
lockMode,
uiVerbosity,
clientDesc,
startMs,
startOpts,
cmdExts,
cmdExtOut) -> {
cmdExtOut.report(commandExtension1);
afterFirstExtensionLatch.countDown();
beforeSecondExtensionLatch.await(WAIT_TIMEOUT_SECONDS, SECONDS);
cmdExtOut.report(commandExtension2);
afterSecondExtensionLatch.countDown();
beforeThirdExtensionLatch.await(WAIT_TIMEOUT_SECONDS, SECONDS);
cmdExtOut.report(commandExtension3);
afterThirdExtensionLatch.countDown();
return BlazeCommandResult.success();
};
createServer(dispatcher);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
CountDownLatch done = new CountDownLatch(1);
stub.run(createRequest("Foo"), createResponseObserver(responses, done));
afterFirstExtensionLatch.await();
assertThat(Iterables.getLast(responses).getCommandExtensionsList())
.containsExactly(commandExtension1);
beforeSecondExtensionLatch.countDown();
afterSecondExtensionLatch.await();
assertThat(Iterables.getLast(responses).getCommandExtensionsList())
.containsExactly(commandExtension2);
beforeThirdExtensionLatch.countDown();
afterThirdExtensionLatch.await();
done.await();
assertThat(responses.get(responses.size() - 2).getCommandExtensionsList())
.containsExactly(commandExtension3);
server.shutdown();
server.awaitTermination();
}
@Test
public void testClosingClientShouldInterrupt() throws Exception {
CountDownLatch done = new CountDownLatch(1);
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter) {
synchronized (this) {
assertThrows(InterruptedException.class, this::wait);
}
done.countDown();
return BlazeCommandResult.failureDetail(
FailureDetail.newBuilder()
.setInterrupted(Interrupted.newBuilder().setCode(Code.INTERRUPTED_UNKNOWN))
.build());
}
};
createServer(dispatcher);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
createRequest("Foo"),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
server.shutdownNow();
done.countDown();
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
server.awaitTermination();
done.await();
}
@Test
public void testStream() throws Exception {
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter) {
OutputStream out = outErr.getOutputStream();
try {
commandExtensionReporter.report(Any.pack(Int32Value.of(23)));
for (int i = 0; i < 10; i++) {
out.write(new byte[1024]);
}
commandExtensionReporter.report(Any.pack(Int32Value.of(42)));
} catch (IOException e) {
throw new IllegalStateException(e);
}
return BlazeCommandResult.withResponseExtensions(
BlazeCommandResult.success(),
ImmutableList.of(
Any.pack(StringValue.of("foo")),
Any.pack(BytesValue.of(ByteString.copyFromUtf8("bar")))),
true);
}
};
createServer(dispatcher);
CountDownLatch done = new CountDownLatch(1);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
stub.run(createRequest("Foo"), createResponseObserver(responses, done));
done.await();
server.shutdown();
server.awaitTermination();
assertThat(responses).hasSize(14);
assertThat(responses.get(0).getFinished()).isFalse();
assertThat(responses.get(0).getCookie()).isNotEmpty();
assertThat(responses.get(1).getFinished()).isFalse();
assertThat(responses.get(1).getCookie()).isNotEmpty();
assertThat(responses.get(1).getCommandExtensionsList())
.containsExactly(Any.pack(Int32Value.of(23)));
for (int i = 2; i < 12; i++) {
assertThat(responses.get(i).getFinished()).isFalse();
assertThat(responses.get(i).getStandardOutput().toByteArray()).isEqualTo(new byte[1024]);
assertThat(responses.get(i).getCommandExtensionsList()).isEmpty();
}
assertThat(responses.get(12).getFinished()).isFalse();
assertThat(responses.get(12).getCookie()).isNotEmpty();
assertThat(responses.get(12).getCommandExtensionsList())
.containsExactly(Any.pack(Int32Value.of(42)));
assertThat(responses.get(13).getFinished()).isTrue();
assertThat(responses.get(13).getExitCode()).isEqualTo(0);
assertThat(responses.get(13).hasFailureDetail()).isFalse();
assertThat(responses.get(13).getCommandExtensionsList())
.containsExactly(
Any.pack(StringValue.of("foo")),
Any.pack(BytesValue.of(ByteString.copyFromUtf8("bar"))));
}
@Test
public void badCookie() throws Exception {
runBadCommandTest(
RunRequest.newBuilder().setCookie("bad-cookie").setClientDescription("client-description"),
FailureDetail.newBuilder()
.setMessage("Invalid RunRequest: bad cookie")
.setGrpcServer(GrpcServer.newBuilder().setCode(GrpcServer.Code.BAD_COOKIE))
.build());
}
@Test
public void emptyClientDescription() throws Exception {
runBadCommandTest(
RunRequest.newBuilder().setCookie(REQUEST_COOKIE).setClientDescription(""),
FailureDetail.newBuilder()
.setMessage("Invalid RunRequest: no client description")
.setGrpcServer(GrpcServer.newBuilder().setCode(GrpcServer.Code.NO_CLIENT_DESCRIPTION))
.build());
}
private void runBadCommandTest(RunRequest.Builder runRequestBuilder, FailureDetail failureDetail)
throws Exception {
createServer(throwingDispatcher());
CountDownLatch done = new CountDownLatch(1);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
stub.run(
runRequestBuilder.addArg(ByteString.copyFromUtf8("Foo")).build(),
createResponseObserver(responses, done));
done.await();
server.shutdown();
server.awaitTermination();
assertThat(responses).hasSize(1);
assertThat(responses.get(0).getFinished()).isTrue();
assertThat(responses.get(0).getExitCode()).isEqualTo(36);
assertThat(responses.get(0).hasFailureDetail()).isTrue();
assertThat(responses.get(0).getFailureDetail()).isEqualTo(failureDetail);
}
@Test
public void unparseableInvocationPolicy() throws Exception {
createServer(throwingDispatcher());
CountDownLatch done = new CountDownLatch(1);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
stub.run(
RunRequest.newBuilder()
.setCookie(REQUEST_COOKIE)
.setClientDescription("client-description")
.setInvocationPolicy("invalid-invocation-policy")
.addArg(ByteString.copyFromUtf8("Foo"))
.build(),
createResponseObserver(responses, done));
done.await();
server.shutdown();
server.awaitTermination();
assertThat(responses).hasSize(3);
assertThat(responses.get(2).getFinished()).isTrue();
assertThat(responses.get(2).getExitCode()).isEqualTo(2);
assertThat(responses.get(2).hasFailureDetail()).isTrue();
assertThat(responses.get(2).getFailureDetail())
.isEqualTo(
FailureDetail.newBuilder()
.setMessage(
"Invocation policy parsing failed: Malformed value of --invocation_policy: "
+ "invalid-invocation-policy")
.setCommand(
Command.newBuilder().setCode(Command.Code.INVOCATION_POLICY_PARSE_FAILURE))
.build());
}
@Test
public void testInterruptStream() throws Exception {
CountDownLatch done = new CountDownLatch(1);
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter) {
OutputStream out = outErr.getOutputStream();
try {
while (true) {
if (Thread.interrupted()) {
return BlazeCommandResult.failureDetail(
FailureDetail.newBuilder()
.setInterrupted(
Interrupted.newBuilder().setCode(Code.INTERRUPTED_UNKNOWN))
.build());
}
out.write(new byte[1024]);
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
};
createServer(dispatcher);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
List<RunResponse> responses = new ArrayList<>();
stub.run(
createRequest("Foo"),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
responses.add(value);
if (responses.size() == 10) {
server.shutdownNow();
}
}
@Override
public void onError(Throwable t) {
done.countDown();
}
@Override
public void onCompleted() {
done.countDown();
}
});
server.awaitTermination();
done.await();
}
@Test
public void testCancel() throws Exception {
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter)
throws InterruptedException {
synchronized (this) {
this.wait();
}
throw new IllegalStateException();
}
};
createServer(dispatcher);
AtomicReference<String> commandId = new AtomicReference<>();
CountDownLatch gotCommandId = new CountDownLatch(1);
AtomicReference<RunResponse> secondResponse = new AtomicReference<>();
CountDownLatch gotSecondResponse = new CountDownLatch(1);
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
createRequest("Foo"),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
String previousCommandId = commandId.getAndSet(value.getCommandId());
if (previousCommandId == null) {
gotCommandId.countDown();
} else {
secondResponse.set(value);
gotSecondResponse.countDown();
}
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
gotCommandId.await();
CountDownLatch cancelRequestComplete = new CountDownLatch(1);
CancelRequest [MASK] =
CancelRequest.newBuilder().setCookie(REQUEST_COOKIE).setCommandId(commandId.get()).build();
stub.cancel(
[MASK],
new StreamObserver<CancelResponse>() {
@Override
public void onNext(CancelResponse value) {}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {
cancelRequestComplete.countDown();
}
});
cancelRequestComplete.await();
gotSecondResponse.await();
server.shutdown();
server.awaitTermination();
assertThat(secondResponse.get().getFinished()).isTrue();
assertThat(secondResponse.get().getExitCode()).isEqualTo(8);
assertThat(secondResponse.get().hasFailureDetail()).isTrue();
assertThat(secondResponse.get().getFailureDetail().hasInterrupted()).isTrue();
assertThat(secondResponse.get().getFailureDetail().getInterrupted().getCode())
.isEqualTo(Code.INTERRUPTED);
}
@Test
public void testPreeempt() throws Exception {
String firstCommandArg = "Foo";
String secondCommandArg = "Bar";
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter) {
if (args.contains(firstCommandArg)) {
while (true) {
try {
Thread.sleep(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
} catch (InterruptedException e) {
return BlazeCommandResult.failureDetail(
FailureDetail.newBuilder()
.setInterrupted(Interrupted.newBuilder().setCode(Code.INTERRUPTED))
.build());
}
}
} else {
return BlazeCommandResult.success();
}
}
};
createServer(dispatcher);
CountDownLatch gotFoo = new CountDownLatch(1);
AtomicReference<RunResponse> lastFooResponse = new AtomicReference<>();
AtomicReference<RunResponse> lastBarResponse = new AtomicReference<>();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
createPreemptibleRequest(firstCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
gotFoo.countDown();
lastFooResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
gotFoo.await();
CountDownLatch gotBar = new CountDownLatch(1);
stub.run(
createRequest(secondCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
gotBar.countDown();
lastBarResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
gotBar.await();
server.shutdown();
server.awaitTermination();
assertThat(lastBarResponse.get().getFinished()).isTrue();
assertThat(lastBarResponse.get().getExitCode()).isEqualTo(0);
assertThat(lastFooResponse.get().getFinished()).isTrue();
assertThat(lastFooResponse.get().getExitCode()).isEqualTo(8);
assertThat(lastFooResponse.get().hasFailureDetail()).isTrue();
assertThat(lastFooResponse.get().getFailureDetail().hasInterrupted()).isTrue();
assertThat(lastFooResponse.get().getFailureDetail().getInterrupted().getCode())
.isEqualTo(Code.INTERRUPTED);
}
@Test
public void testMultiPreeempt() throws Exception {
String firstCommandArg = "Foo";
String secondCommandArg = "Bar";
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter)
throws InterruptedException {
if (args.contains(firstCommandArg)) {
while (true) {
try {
Thread.sleep(TestUtils.WAIT_TIMEOUT_MILLISECONDS);
} catch (InterruptedException e) {
return BlazeCommandResult.failureDetail(
FailureDetail.newBuilder()
.setInterrupted(Interrupted.newBuilder().setCode(Code.INTERRUPTED))
.build());
}
}
} else {
return BlazeCommandResult.success();
}
}
};
createServer(dispatcher);
CountDownLatch gotFoo = new CountDownLatch(1);
AtomicReference<RunResponse> lastFooResponse = new AtomicReference<>();
AtomicReference<RunResponse> lastBarResponse = new AtomicReference<>();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
createPreemptibleRequest(firstCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
gotFoo.countDown();
lastFooResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
gotFoo.await();
CountDownLatch gotBar = new CountDownLatch(1);
stub.run(
createPreemptibleRequest(secondCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
gotBar.countDown();
lastBarResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
gotBar.await();
server.shutdown();
server.awaitTermination();
assertThat(lastBarResponse.get().getFinished()).isTrue();
assertThat(lastBarResponse.get().getExitCode()).isEqualTo(0);
assertThat(lastFooResponse.get().getFinished()).isTrue();
assertThat(lastFooResponse.get().getExitCode()).isEqualTo(8);
assertThat(lastFooResponse.get().hasFailureDetail()).isTrue();
assertThat(lastFooResponse.get().getFailureDetail().hasInterrupted()).isTrue();
assertThat(lastFooResponse.get().getFailureDetail().getInterrupted().getCode())
.isEqualTo(Code.INTERRUPTED);
}
@Test
public void testNoPreeempt() throws Exception {
String firstCommandArg = "Foo";
String secondCommandArg = "Bar";
CountDownLatch fooBlocked = new CountDownLatch(1);
CountDownLatch fooProceed = new CountDownLatch(1);
CountDownLatch barBlocked = new CountDownLatch(1);
CountDownLatch barProceed = new CountDownLatch(1);
CommandDispatcher dispatcher =
new CommandDispatcher() {
@Override
public BlazeCommandResult exec(
InvocationPolicy invocationPolicy,
List<String> args,
OutErr outErr,
LockingMode lockingMode,
UiVerbosity uiVerbosity,
String clientDescription,
long firstContactTimeMillis,
Optional<List<Pair<String, String>>> startupOptionsTaggedWithBazelRc,
List<Any> commandExtensions,
CommandExtensionReporter commandExtensionReporter)
throws InterruptedException {
if (args.contains(firstCommandArg)) {
fooBlocked.countDown();
fooProceed.await();
} else {
barBlocked.countDown();
barProceed.await();
}
return BlazeCommandResult.success();
}
};
createServer(dispatcher);
AtomicReference<RunResponse> lastFooResponse = new AtomicReference<>();
AtomicReference<RunResponse> lastBarResponse = new AtomicReference<>();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
createRequest(firstCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
lastFooResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
fooBlocked.await();
stub.run(
createRequest(secondCommandArg),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
lastBarResponse.set(value);
}
@Override
public void onError(Throwable t) {}
@Override
public void onCompleted() {}
});
barBlocked.await();
fooProceed.countDown();
barProceed.countDown();
server.shutdown();
server.awaitTermination();
assertThat(lastFooResponse.get().getFinished()).isTrue();
assertThat(lastFooResponse.get().getExitCode()).isEqualTo(0);
assertThat(lastBarResponse.get().getFinished()).isTrue();
assertThat(lastBarResponse.get().getExitCode()).isEqualTo(0);
}
@Test
public void testFlowControl() throws Exception {
CountDownLatch serverDone = new CountDownLatch(1);
CountDownLatch clientBlocks = new CountDownLatch(1);
CountDownLatch clientUnblocks = new CountDownLatch(1);
CountDownLatch clientDone = new CountDownLatch(1);
AtomicInteger sentCount = new AtomicInteger();
AtomicInteger receiveCount = new AtomicInteger();
CommandServerGrpc.CommandServerImplBase serverImpl =
new CommandServerGrpc.CommandServerImplBase() {
@Override
public void run(RunRequest request, StreamObserver<RunResponse> observer) {
ServerCallStreamObserver<RunResponse> serverCallStreamObserver =
(ServerCallStreamObserver<RunResponse>) observer;
BlockingStreamObserver<RunResponse> blockingStreamObserver =
new BlockingStreamObserver<>(serverCallStreamObserver);
Thread t =
new Thread(
() -> {
RunResponse response =
RunResponse.newBuilder()
.setStandardOutput(ByteString.copyFrom(new byte[1024]))
.build();
for (int i = 0; i < 100; i++) {
blockingStreamObserver.onNext(response);
sentCount.incrementAndGet();
}
blockingStreamObserver.onCompleted();
serverDone.countDown();
});
t.start();
}
};
String uniqueName = InProcessServerBuilder.generateName();
server =
InProcessServerBuilder.forName(uniqueName)
.addService(serverImpl)
.executor(Executors.newFixedThreadPool(4))
.build()
.start();
channel =
InProcessChannelBuilder.forName(uniqueName)
.executor(Executors.newFixedThreadPool(4))
.build();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
RunRequest.getDefaultInstance(),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
if (sentCount.get() >= 3) {
clientBlocks.countDown();
try {
clientUnblocks.await();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
receiveCount.incrementAndGet();
}
@Override
public void onError(Throwable t) {
throw new IllegalStateException(t);
}
@Override
public void onCompleted() {
clientDone.countDown();
}
});
clientBlocks.await();
Thread.sleep(10);
assertThat(sentCount.get()).isLessThan(5);
clientUnblocks.countDown();
serverDone.await();
clientDone.await();
server.shutdown();
server.awaitTermination();
}
@Test
public void testFlowControlClientCancel() throws Exception {
CountDownLatch serverDone = new CountDownLatch(1);
CountDownLatch clientDone = new CountDownLatch(1);
AtomicInteger sentCount = new AtomicInteger();
AtomicInteger receiveCount = new AtomicInteger();
CommandServerGrpc.CommandServerImplBase serverImpl =
new CommandServerGrpc.CommandServerImplBase() {
@Override
public void run(RunRequest request, StreamObserver<RunResponse> observer) {
ServerCallStreamObserver<RunResponse> serverCallStreamObserver =
(ServerCallStreamObserver<RunResponse>) observer;
BlockingStreamObserver<RunResponse> blockingStreamObserver =
new BlockingStreamObserver<>(serverCallStreamObserver);
Thread t =
new Thread(
() -> {
RunResponse response =
RunResponse.newBuilder()
.setStandardOutput(ByteString.copyFrom(new byte[1024]))
.build();
for (int i = 0; i < 100; i++) {
blockingStreamObserver.onNext(response);
sentCount.incrementAndGet();
}
assertThat(Thread.currentThread().isInterrupted()).isTrue();
blockingStreamObserver.onCompleted();
serverDone.countDown();
});
t.start();
}
};
String uniqueName = InProcessServerBuilder.generateName();
server =
InProcessServerBuilder.forName(uniqueName)
.addService(serverImpl)
.executor(Executors.newFixedThreadPool(4))
.build()
.start();
channel =
InProcessChannelBuilder.forName(uniqueName)
.executor(Executors.newFixedThreadPool(4))
.build();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
RunRequest.getDefaultInstance(),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
if (receiveCount.get() > 3) {
channel.shutdownNow();
}
receiveCount.incrementAndGet();
}
@Override
public void onError(Throwable t) {
clientDone.countDown();
}
@Override
public void onCompleted() {
clientDone.countDown();
}
});
serverDone.await();
clientDone.await();
server.shutdown();
server.awaitTermination();
}
@Test
public void testInterruptFlowControl() throws Exception {
CountDownLatch serverDone = new CountDownLatch(1);
CountDownLatch clientDone = new CountDownLatch(1);
AtomicInteger sentCount = new AtomicInteger();
AtomicInteger receiveCount = new AtomicInteger();
CommandServerGrpc.CommandServerImplBase serverImpl =
new CommandServerGrpc.CommandServerImplBase() {
@Override
public void run(RunRequest request, StreamObserver<RunResponse> observer) {
ServerCallStreamObserver<RunResponse> serverCallStreamObserver =
(ServerCallStreamObserver<RunResponse>) observer;
BlockingStreamObserver<RunResponse> blockingStreamObserver =
new BlockingStreamObserver<>(serverCallStreamObserver);
Thread t =
new Thread(
() -> {
RunResponse response =
RunResponse.newBuilder()
.setStandardOutput(ByteString.copyFrom(new byte[1024]))
.build();
int sent = 0;
while (serverCallStreamObserver.isReady()) {
blockingStreamObserver.onNext(response);
sent++;
}
sentCount.set(sent);
Thread.currentThread().interrupt();
for (int i = 0; i < 10; i++) {
blockingStreamObserver.onNext(response);
sentCount.incrementAndGet();
}
blockingStreamObserver.onCompleted();
serverDone.countDown();
});
t.start();
}
};
String uniqueName = InProcessServerBuilder.generateName();
server =
InProcessServerBuilder.forName(uniqueName)
.addService(serverImpl)
.executor(Executors.newFixedThreadPool(4))
.build()
.start();
channel =
InProcessChannelBuilder.forName(uniqueName)
.executor(Executors.newFixedThreadPool(4))
.build();
CommandServerStub stub = CommandServerGrpc.newStub(channel);
stub.run(
RunRequest.getDefaultInstance(),
new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
if (sentCount.get() == 0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
receiveCount.incrementAndGet();
}
@Override
public void onError(Throwable t) {
throw new IllegalStateException(t);
}
@Override
public void onCompleted() {
clientDone.countDown();
}
});
serverDone.await();
clientDone.await();
assertThat(sentCount.get()).isEqualTo(receiveCount.get());
server.shutdown();
server.awaitTermination();
}
private static StreamObserver<RunResponse> createResponseObserver(
List<RunResponse> responses, CountDownLatch done) {
return new StreamObserver<RunResponse>() {
@Override
public void onNext(RunResponse value) {
responses.add(value);
}
@Override
public void onError(Throwable t) {
done.countDown();
}
@Override
public void onCompleted() {
done.countDown();
}
};
}
private static CommandDispatcher throwingDispatcher() {
return (invocationPolicy,
args,
outErr,
lockingMode,
uiVerbosity,
clientDescription,
firstContactTimeMillis,
startupOptionsTaggedWithBazelRc,
commandExtensions,
commandExtensionReporter) -> {
throw new IllegalStateException("Command exec not expected");
};
}
} | cancelRequest | java | bazel |
package org.elasticsearch.xpack.esql.core.expression.predicate;
import org.elasticsearch.xpack.esql.core.expression.Expression;
import org.elasticsearch.xpack.esql.core.expression.FoldContext;
import org.elasticsearch.xpack.esql.core.expression.function.scalar.BinaryScalarFunction;
import org.elasticsearch.xpack.esql.core.tree.Source;
import java.util.Objects;
public abstract class BinaryPredicate<T, U, R, F extends PredicateBiFunction<T, U, R>> extends BinaryScalarFunction {
private final F function;
protected BinaryPredicate(Source [MASK], Expression left, Expression right, F function) {
super([MASK], left, right);
this.function = function;
}
@SuppressWarnings("unchecked")
@Override
public R fold(FoldContext ctx) {
return function().apply((T) left().fold(ctx), (U) right().fold(ctx));
}
@Override
public int hashCode() {
return Objects.hash(left(), right(), function.symbol());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
BinaryPredicate<?, ?, ?, ?> other = (BinaryPredicate<?, ?, ?, ?>) obj;
return Objects.equals(symbol(), other.symbol()) && Objects.equals(left(), other.left()) && Objects.equals(right(), other.right());
}
public String symbol() {
return function.symbol();
}
public F function() {
return function;
}
@Override
public String nodeString() {
return left().nodeString() + " " + symbol() + " " + right().nodeString();
}
} | source | java | elasticsearch |
package org.elasticsearch.xpack.inference.services.ibmwatsonx.action;
import org.elasticsearch.xpack.inference.external.action.ExecutableAction;
import org.elasticsearch.xpack.inference.services.ibmwatsonx.embeddings.IbmWatsonxEmbeddingsModel;
import org.elasticsearch.xpack.inference.services.ibmwatsonx.rerank.IbmWatsonxRerankModel;
import java.util.Map;
public interface IbmWatsonxActionVisitor {
ExecutableAction create(IbmWatsonxEmbeddingsModel [MASK], Map<String, Object> taskSettings);
ExecutableAction create(IbmWatsonxRerankModel [MASK], Map<String, Object> taskSettings);
} | model | java | elasticsearch |
package org.springframework.boot.buildpack.platform.docker.configuration;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.boot.buildpack.platform.json.AbstractJsonTests;
import org.springframework.util.StreamUtils;
class DockerRegistryTokenAuthenticationTests extends AbstractJsonTests {
@Test
void createAuthHeaderReturnsEncodedHeader() throws IOException, JSONException {
DockerRegistryTokenAuthentication [MASK] = new DockerRegistryTokenAuthentication("tokenvalue");
String header = [MASK].getAuthHeader();
String expectedJson = StreamUtils.copyToString(getContent("[MASK]-token.json"), StandardCharsets.UTF_8);
JSONAssert.assertEquals(expectedJson, new String(Base64.getUrlDecoder().decode(header)), true);
}
} | auth | java | spring-boot |
package sun.nio.ch;
import java.nio.channels.*;
import java.util.concurrent.*;
import java.io.IOException;
import java.io.FileDescriptor;
import java.net.InetSocketAddress;
import java.util.concurrent.atomic.AtomicBoolean;
import java.security.AccessControlContext;
import dalvik.system.CloseGuard;
import libcore.io.OsConstants;
class UnixAsynchronousServerSocketChannelImpl
extends AsynchronousServerSocketChannelImpl
implements Port.PollableChannel
{
private final static NativeDispatcher nd = new SocketDispatcher();
private final Port port;
private final int fdVal;
private final AtomicBoolean accepting = new AtomicBoolean();
private void enableAccept() {
accepting.set(false);
}
private final Object updateLock = new Object();
private boolean acceptPending;
private CompletionHandler<AsynchronousSocketChannel,Object> acceptHandler;
private Object acceptAttachment;
private PendingFuture<AsynchronousSocketChannel,Object> acceptFuture;
private AccessControlContext acceptAcc;
private final CloseGuard guard = CloseGuard.get();
UnixAsynchronousServerSocketChannelImpl(Port port)
throws IOException
{
super(port);
try {
IOUtil.configureBlocking(fd, false);
} catch (IOException x) {
nd.close(fd);
throw x;
}
this.port = port;
this.fdVal = IOUtil.fdVal(fd);
port.register(fdVal, this);
guard.open("close");
}
@Override
void implClose() throws IOException {
guard.close();
port.unregister(fdVal);
nd.close(fd);
CompletionHandler<AsynchronousSocketChannel,Object> handler;
Object att;
PendingFuture<AsynchronousSocketChannel,Object> future;
synchronized (updateLock) {
if (!acceptPending)
return;
acceptPending = false;
handler = acceptHandler;
att = acceptAttachment;
future = acceptFuture;
}
AsynchronousCloseException x = new AsynchronousCloseException();
x.setStackTrace(new StackTraceElement[0]);
if (handler == null) {
future.setFailure(x);
} else {
Invoker.invokeIndirectly(this, handler, att, null, x);
}
}
protected void finalize() throws Throwable {
try {
if (guard != null) {
guard.warnIfOpen();
}
close();
} finally {
super.finalize();
}
}
@Override
public AsynchronousChannelGroupImpl group() {
return port;
}
@Override
public void onEvent(int events, boolean mayInvokeDirect) {
synchronized (updateLock) {
if (!acceptPending)
return;
acceptPending = false;
}
FileDescriptor newfd = new FileDescriptor();
InetSocketAddress[] [MASK] = new InetSocketAddress[1];
Throwable exc = null;
try {
begin();
int n = accept(this.fd, newfd, [MASK]);
if (n == IOStatus.UNAVAILABLE) {
synchronized (updateLock) {
acceptPending = true;
}
port.startPoll(fdVal, Net.POLLIN);
return;
}
} catch (Throwable x) {
if (x instanceof ClosedChannelException)
x = new AsynchronousCloseException();
exc = x;
} finally {
end();
}
AsynchronousSocketChannel child = null;
if (exc == null) {
try {
child = finishAccept(newfd, [MASK][0], acceptAcc);
} catch (Throwable x) {
if (!(x instanceof IOException) && !(x instanceof SecurityException))
x = new IOException(x);
exc = x;
}
}
CompletionHandler<AsynchronousSocketChannel,Object> handler = acceptHandler;
Object att = acceptAttachment;
PendingFuture<AsynchronousSocketChannel,Object> future = acceptFuture;
enableAccept();
if (handler == null) {
future.setResult(child, exc);
if (child != null && future.isCancelled()) {
try {
child.close();
} catch (IOException ignore) { }
}
} else {
Invoker.invoke(this, handler, att, child, exc);
}
}
private AsynchronousSocketChannel finishAccept(FileDescriptor newfd,
final InetSocketAddress remote,
AccessControlContext acc)
throws IOException, SecurityException
{
AsynchronousSocketChannel ch = null;
try {
ch = new UnixAsynchronousSocketChannelImpl(port, newfd, remote);
} catch (IOException x) {
nd.close(newfd);
throw x;
}
return ch;
}
@Override
Future<AsynchronousSocketChannel> implAccept(Object att,
CompletionHandler<AsynchronousSocketChannel,Object> handler)
{
if (!isOpen()) {
Throwable e = new ClosedChannelException();
if (handler == null) {
return CompletedFuture.withFailure(e);
} else {
Invoker.invoke(this, handler, att, null, e);
return null;
}
}
if (localAddress == null)
throw new NotYetBoundException();
if (isAcceptKilled())
throw new RuntimeException("Accept not allowed due cancellation");
if (!accepting.compareAndSet(false, true))
throw new AcceptPendingException();
FileDescriptor newfd = new FileDescriptor();
InetSocketAddress[] [MASK] = new InetSocketAddress[1];
Throwable exc = null;
try {
begin();
int n = accept(this.fd, newfd, [MASK]);
if (n == IOStatus.UNAVAILABLE) {
PendingFuture<AsynchronousSocketChannel,Object> result = null;
synchronized (updateLock) {
if (handler == null) {
this.acceptHandler = null;
result = new PendingFuture<AsynchronousSocketChannel,Object>(this);
this.acceptFuture = result;
} else {
this.acceptHandler = handler;
this.acceptAttachment = att;
}
this.acceptAcc = null;
this.acceptPending = true;
}
port.startPoll(fdVal, Net.POLLIN);
return result;
}
} catch (Throwable x) {
if (x instanceof ClosedChannelException)
x = new AsynchronousCloseException();
exc = x;
} finally {
end();
}
AsynchronousSocketChannel child = null;
if (exc == null) {
try {
child = finishAccept(newfd, [MASK][0], null);
} catch (Throwable x) {
exc = x;
}
}
enableAccept();
if (handler == null) {
return CompletedFuture.withResult(child, exc);
} else {
Invoker.invokeIndirectly(this, handler, att, child, exc);
return null;
}
}
private int accept(FileDescriptor ssfd, FileDescriptor newfd,
InetSocketAddress[] [MASK])
throws IOException
{
return accept0(ssfd, newfd, [MASK]);
}
private static native void initIDs();
private native int accept0(FileDescriptor ssfd, FileDescriptor newfd,
InetSocketAddress[] [MASK])
throws IOException;
static {
initIDs();
}
} | isaa | java | j2objc |
package proguard.configuration;
import proguard.*;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.attribute.visitor.*;
import proguard.classfile.editor.*;
import proguard.classfile.[MASK].Instruction;
import proguard.classfile.[MASK].visitor.InstructionVisitor;
import proguard.classfile.util.*;
import proguard.classfile.visitor.*;
import proguard.io.*;
import proguard.optimize.peephole.*;
import proguard.util.MultiValueMap;
import java.io.IOException;
import static proguard.classfile.util.ClassUtil.internalClassName;
public class ConfigurationLoggingAdder
extends SimplifiedVisitor
implements
InstructionVisitor
{
private final Configuration configuration;
private MultiValueMap<String, String> injectedClassMap;
public ConfigurationLoggingAdder(Configuration configuration)
{
this.configuration = configuration;
}
public void execute(ClassPool programClassPool,
ClassPool libraryClassPool,
MultiValueMap<String, String> injectedClassMap )
{
ClassReader classReader =
new ClassReader(false, false, false, null,
new MultiClassVisitor(
new ClassPoolFiller(programClassPool),
new ClassReferenceInitializer(programClassPool, libraryClassPool),
new ClassSubHierarchyInitializer()
));
try
{
classReader.read(new ClassPathDataEntry(ConfigurationLogger.MethodSignature.class));
classReader.read(new ClassPathDataEntry(ConfigurationLogger.class));
}
catch (IOException e)
{
throw new RuntimeException(e);
}
ConfigurationLoggingInstructionSequenceConstants constants =
new ConfigurationLoggingInstructionSequenceConstants(programClassPool,
libraryClassPool);
BranchTargetFinder branchTargetFinder = new BranchTargetFinder();
CodeAttributeEditor codeAttributeEditor = new CodeAttributeEditor();
this.injectedClassMap = injectedClassMap;
programClassPool.classesAccept(
new ClassNameFilter("!proguard/**",
new AllMethodVisitor(
new AllAttributeVisitor(
new PeepholeOptimizer(branchTargetFinder, codeAttributeEditor,
new ConfigurationLoggingInstructionSequencesReplacer(constants.CONSTANTS,
constants.RESOURCE,
branchTargetFinder,
codeAttributeEditor,
this))))));
}
public void visitAnyInstruction(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, Instruction [MASK])
{
injectedClassMap.put(clazz.getName(), internalClassName(ConfigurationLogger.class.getName()));
injectedClassMap.put(clazz.getName(), internalClassName(ConfigurationLogger.MethodSignature.class.getName()));
}
} | instruction | java | bazel |
package com.google.devtools.j2objc.translate;
import com.google.common.collect.ImmutableSet;
import com.google.devtools.j2objc.ast.AnnotationTypeDeclaration;
import com.google.devtools.j2objc.ast.ClassInstanceCreation;
import com.google.devtools.j2objc.ast.CompilationUnit;
import com.google.devtools.j2objc.ast.ConstructorInvocation;
import com.google.devtools.j2objc.ast.CreationReference;
import com.google.devtools.j2objc.ast.EnumDeclaration;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.ExpressionMethodReference;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.FunctionalExpression;
import com.google.devtools.j2objc.ast.LambdaExpression;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.MethodInvocation;
import com.google.devtools.j2objc.ast.Name;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.RecordDeclaration;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SingleVariableDeclaration;
import com.google.devtools.j2objc.ast.SuperConstructorInvocation;
import com.google.devtools.j2objc.ast.SuperFieldAccess;
import com.google.devtools.j2objc.ast.SuperMethodInvocation;
import com.google.devtools.j2objc.ast.SuperMethodReference;
import com.google.devtools.j2objc.ast.ThisExpression;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.Type;
import com.google.devtools.j2objc.ast.TypeDeclaration;
import com.google.devtools.j2objc.ast.UnitTreeVisitor;
import com.google.devtools.j2objc.ast.VariableDeclaration;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.util.CaptureInfo;
import com.google.devtools.j2objc.util.ElementUtil;
import com.google.devtools.j2objc.util.TypeUtil;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
@SuppressWarnings("UngroupedOverloads")
public class OuterReferenceResolver extends UnitTreeVisitor {
private final CaptureInfo captureInfo;
private Scope topScope = null;
public OuterReferenceResolver(CompilationUnit unit) {
super(unit);
this.captureInfo = unit.getEnv().captureInfo();
}
private enum ScopeKind { CLASS, LAMBDA, METHOD }
private class Scope {
private final ScopeKind kind;
private final Scope outer;
private final Scope outerClass;
private final TypeElement type;
private final Set<Element> inheritedScope;
private final boolean initializingContext;
private final Set<VariableElement> declaredVars = new HashSet<>();
private List<Runnable> onExit = new ArrayList<>();
private final Queue<Runnable> onOuterParam;
private int constructorCount = 0;
private int constructorsNotNeedingSuperOuterScope = 0;
private Scope(Scope outer, TypeElement type) {
kind = ElementUtil.isLambda(type) ? ScopeKind.LAMBDA : ScopeKind.CLASS;
this.outer = outer;
outerClass = firstClassScope(outer);
this.type = type;
ImmutableSet.Builder<Element> inheritedScopeBuilder = ImmutableSet.builder();
if (kind == ScopeKind.CLASS) {
typeUtil.visitTypeHierarchy(type.asType(), inheritedType -> {
inheritedScopeBuilder.add(inheritedType.asElement());
return true;
});
}
this.inheritedScope = inheritedScopeBuilder.build();
this.initializingContext = kind == ScopeKind.CLASS;
this.onOuterParam = new LinkedList<>();
}
private Scope(Scope outer, ExecutableElement method) {
kind = ScopeKind.METHOD;
this.outer = outer;
outerClass = outer.outerClass;
type = outer.type;
inheritedScope = outer.inheritedScope;
initializingContext = ElementUtil.isConstructor(method);
onOuterParam = outer.onOuterParam;
}
private boolean isInitializing() {
return initializingContext && this == peekScope();
}
}
private Scope peekScope() {
assert topScope != null;
return topScope;
}
private static Scope firstClassScope(Scope scope) {
while (scope != null && scope.kind != ScopeKind.CLASS) {
scope = scope.outer;
}
return scope;
}
private Scope findScopeForType(TypeElement type) {
Scope scope = peekScope();
while (scope != null) {
if (scope.kind != ScopeKind.METHOD && type.equals(scope.type)) {
return scope;
}
scope = scope.outer;
}
return null;
}
private Runnable captureCurrentScope(Runnable runnable) {
Scope capturedScope = peekScope();
return new Runnable() {
@Override
public void run() {
Scope saved = topScope;
topScope = capturedScope;
runnable.run();
topScope = saved;
}
};
}
private void onExitScope(TypeElement type, Runnable runnable) {
Scope scope = findScopeForType(type);
if (scope != null) {
scope.onExit.add(captureCurrentScope(runnable));
} else {
runnable.run();
}
}
private void whenNeedsOuterParam(TypeElement type, Runnable runnable) {
if (captureInfo.needsOuterParam(type)) {
runnable.run();
} else if (ElementUtil.isLocal(type)) {
Scope scope = findScopeForType(type);
if (scope != null) {
scope.onOuterParam.add(captureCurrentScope(runnable));
}
}
}
private VariableElement getOrCreateOuterVar(Scope scope) {
while (!scope.onOuterParam.isEmpty()) {
scope.onOuterParam.remove().run();
}
return scope.isInitializing() ? captureInfo.getOrCreateOuterParam(scope.type)
: captureInfo.getOrCreateOuterField(scope.type);
}
private VariableElement getOrCreateCaptureVar(VariableElement var, Scope scope) {
return scope.isInitializing() ? captureInfo.getOrCreateCaptureParam(var, scope.type)
: captureInfo.getOrCreateCaptureField(var, scope.type);
}
private Name getOuterPath(TypeElement type) {
Name path = null;
for (Scope scope = peekScope(); !type.equals(scope.type); scope = scope.outerClass) {
path = Name.newName(path, getOrCreateOuterVar(scope));
}
return path;
}
private Name getOuterPathInherited(TypeElement type) {
Name path = null;
for (Scope scope = peekScope(); !scope.inheritedScope.contains(type);
scope = scope.outerClass) {
path = Name.newName(path, getOrCreateOuterVar(scope));
}
return path;
}
private Name getPathForField(VariableElement var, TypeMirror type) {
Name path = getOuterPathInherited((TypeElement) var.getEnclosingElement());
if (path != null) {
path = Name.newName(path, var, type);
}
return path;
}
private Expression getPathForLocalVar(VariableElement var) {
Name path = null;
Scope scope = peekScope();
if (scope.declaredVars.contains(var)) {
return path;
}
if (var.getConstantValue() != null) {
return TreeUtil.newLiteral(var.getConstantValue(), typeUtil);
}
Scope lastScope = scope;
while (!(scope = scope.outer).declaredVars.contains(var)) {
if (scope == lastScope.outerClass) {
path = Name.newName(path, getOrCreateOuterVar(lastScope));
lastScope = scope;
}
}
return Name.newName(path, getOrCreateCaptureVar(var, lastScope));
}
private void pushType(TypeElement type) {
topScope = new Scope(topScope, type);
}
private void popType() {
Scope [MASK] = peekScope();
topScope = [MASK].outer;
for (Runnable runnable : [MASK].onExit) {
runnable.run();
}
}
private void addSuperOuterPath(TypeDeclaration node) {
TypeElement superclass = ElementUtil.getSuperclass(node.getTypeElement());
if (superclass != null && captureInfo.needsOuterParam(superclass)) {
node.setSuperOuter(getOuterPathInherited(ElementUtil.getDeclaringClass(superclass)));
}
}
private void addCaptureArgs(TypeElement type, List<Expression> args) {
for (VariableElement var : captureInfo.getCapturedVars(type)) {
Expression path = getPathForLocalVar(var);
if (path == null) {
path = new SimpleName(var);
}
args.add(path);
}
}
@Override
public boolean visit(TypeDeclaration node) {
pushType(node.getTypeElement());
return true;
}
@Override
public void endVisit(TypeDeclaration node) {
Scope [MASK] = peekScope();
if ([MASK].constructorCount == 0) {
[MASK].constructorCount++;
}
if ([MASK].constructorCount > [MASK].constructorsNotNeedingSuperOuterScope) {
addSuperOuterPath(node);
}
addCaptureArgs(ElementUtil.getSuperclass(node.getTypeElement()), node.getSuperCaptureArgs());
popType();
}
@Override
public boolean visit(EnumDeclaration node) {
pushType(node.getTypeElement());
return true;
}
@Override
public void endVisit(EnumDeclaration node) {
popType();
}
@Override
public boolean visit(AnnotationTypeDeclaration node) {
pushType(node.getTypeElement());
return true;
}
@Override
public void endVisit(AnnotationTypeDeclaration node) {
popType();
}
@Override
public boolean visit(RecordDeclaration node) {
pushType(node.getTypeElement());
return true;
}
@Override
public void endVisit(RecordDeclaration node) {
popType();
}
private void endVisitFunctionalExpression(FunctionalExpression node) {
TypeElement typeElement = node.getTypeElement();
if (captureInfo.needsOuterParam(typeElement)) {
node.setLambdaOuterArg(getOuterPathInherited(ElementUtil.getDeclaringClass(typeElement)));
}
addCaptureArgs(typeElement, node.getLambdaCaptureArgs());
}
@Override
public boolean visit(LambdaExpression node) {
pushType(node.getTypeElement());
return true;
}
@Override
public void endVisit(LambdaExpression node) {
popType();
endVisitFunctionalExpression(node);
}
@Override
public void endVisit(ExpressionMethodReference node) {
Expression target = node.getExpression();
if (!ElementUtil.isStatic(node.getExecutableElement()) && isValue(target)) {
captureInfo.addMethodReferenceReceiver(node.getTypeElement(), target.getTypeMirror());
}
}
private static boolean isValue(Expression expr) {
return !(expr instanceof Name) || ElementUtil.isVariable(((Name) expr).getElement());
}
@Override
public boolean visit(FieldAccess node) {
node.getExpression().accept(this);
return false;
}
@Override
public boolean visit(SuperFieldAccess node) {
VariableElement var = node.getVariableElement();
Name path = getPathForField(var, node.getTypeMirror());
if (path != null) {
node.replaceWith(path);
}
return false;
}
@Override
public boolean visit(QualifiedName node) {
node.getQualifier().accept(this);
return false;
}
@Override
public boolean visit(SimpleName node) {
VariableElement var = TreeUtil.getVariableElement(node);
if (var != null) {
Expression path = null;
if (ElementUtil.isInstanceVar(var)) {
path = getPathForField(var, node.getTypeMirror());
} else if (!var.getKind().isField()) {
path = getPathForLocalVar(var);
}
if (path != null) {
node.replaceWith(path);
}
}
return true;
}
@Override
public boolean visit(ThisExpression node) {
Name qualifier = TreeUtil.remove(node.getQualifier());
if (qualifier != null) {
Name path = getOuterPath((TypeElement) qualifier.getElement());
if (path != null) {
node.replaceWith(path);
}
} else {
Scope [MASK] = peekScope();
if (ElementUtil.isLambda([MASK].type)) {
Name path = getOuterPath(ElementUtil.getDeclaringClass([MASK].type));
assert path != null : "this keyword within a lambda should have a non-empty path";
node.replaceWith(path);
}
}
return true;
}
@Override
public void endVisit(MethodInvocation node) {
ExecutableElement method = node.getExecutableElement();
if (node.getExpression() == null && !ElementUtil.isStatic(method)) {
node.setExpression(getOuterPathInherited(ElementUtil.getDeclaringClass(method)));
}
}
private Name getSuperPath(Name qualifier, ExecutableElement executableElement) {
if (ElementUtil.isDefault(executableElement)) {
qualifier = null;
}
if (qualifier != null) {
return getOuterPath((TypeElement) qualifier.getElement());
} else {
Scope [MASK] = peekScope();
if (ElementUtil.isLambda([MASK].type)) {
return getOuterPath(ElementUtil.getDeclaringClass([MASK].type));
}
}
return null;
}
@Override
public void endVisit(SuperMethodInvocation node) {
node.setReceiver(getSuperPath(node.getQualifier(), node.getExecutableElement()));
node.setQualifier(null);
}
@Override
public void endVisit(SuperMethodReference node) {
TypeElement lambdaType = node.getTypeElement();
pushType(lambdaType);
Name qualifier = TreeUtil.remove(node.getQualifier());
node.setReceiver(getSuperPath(qualifier, node.getExecutableElement()));
popType();
endVisitFunctionalExpression(node);
}
@Override
public void endVisit(ClassInstanceCreation node) {
TypeElement typeElement = (TypeElement) node.getExecutableElement().getEnclosingElement();
if (node.getExpression() == null) {
whenNeedsOuterParam(typeElement, () -> {
node.setExpression(getOuterPathInherited(ElementUtil.getDeclaringClass(typeElement)));
});
}
if (ElementUtil.isLocal(typeElement)) {
onExitScope(typeElement, () -> {
addCaptureArgs(typeElement, node.getCaptureArgs());
});
}
}
@Override
public void endVisit(CreationReference node) {
Type typeNode = node.getType();
TypeMirror creationType = typeNode.getTypeMirror();
if (TypeUtil.isArray(creationType)) {
return;
}
TypeElement lambdaType = node.getTypeElement();
pushType(lambdaType);
TypeElement creationElement = TypeUtil.asTypeElement(creationType);
whenNeedsOuterParam(creationElement, () -> {
TypeElement enclosingTypeElement = ElementUtil.getDeclaringClass(creationElement);
node.setCreationOuterArg(getOuterPathInherited(enclosingTypeElement));
});
if (ElementUtil.isLocal(creationElement)) {
onExitScope(creationElement, () -> {
addCaptureArgs(creationElement, node.getCreationCaptureArgs());
});
}
popType();
endVisitFunctionalExpression(node);
}
private boolean visitVariableDeclaration(VariableDeclaration node) {
peekScope().declaredVars.add(node.getVariableElement());
return true;
}
@Override
public boolean visit(VariableDeclarationFragment node) {
return visitVariableDeclaration(node);
}
@Override
public boolean visit(SingleVariableDeclaration node) {
return visitVariableDeclaration(node);
}
@Override
public boolean visit(MethodDeclaration node) {
Scope [MASK] = peekScope();
ExecutableElement elem = node.getExecutableElement();
if (ElementUtil.isConstructor(elem)) {
[MASK].constructorCount++;
}
topScope = new Scope([MASK], elem);
return true;
}
@Override
public void endVisit(MethodDeclaration node) {
topScope = topScope.outer;
}
@Override
public void endVisit(ConstructorInvocation node) {
firstClassScope(peekScope()).constructorsNotNeedingSuperOuterScope++;
}
@Override
public void endVisit(SuperConstructorInvocation node) {
if (node.getExpression() != null) {
firstClassScope(peekScope()).constructorsNotNeedingSuperOuterScope++;
}
}
} | currentScope | java | j2objc |
package org.elasticsearch.xpack.spatial.datageneration;
import org.elasticsearch.geo.GeometryTestUtils;
import org.elasticsearch.[MASK].Geometry;
import org.elasticsearch.[MASK].ShapeType;
import org.elasticsearch.logsdb.datageneration.datasource.DataSourceHandler;
import org.elasticsearch.logsdb.datageneration.datasource.DataSourceRequest;
import org.elasticsearch.logsdb.datageneration.datasource.DataSourceResponse;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.spatial.util.GeoTestUtils;
import java.util.HashMap;
public class ShapeDataSourceHandler implements DataSourceHandler {
@Override
public DataSourceResponse.ShapeGenerator handle(DataSourceRequest.ShapeGenerator request) {
return new DataSourceResponse.ShapeGenerator(this::generateValidShape);
}
@Override
public DataSourceResponse.LeafMappingParametersGenerator handle(DataSourceRequest.LeafMappingParametersGenerator request) {
if (request.fieldType().equals("shape") == false) {
return null;
}
return new DataSourceResponse.LeafMappingParametersGenerator(() -> {
var map = new HashMap<String, Object>();
map.put("index", ESTestCase.randomBoolean());
map.put("doc_values", ESTestCase.randomBoolean());
if (ESTestCase.randomBoolean()) {
map.put("ignore_malformed", ESTestCase.randomBoolean());
}
return map;
});
}
@Override
public DataSourceResponse.FieldDataGenerator handle(DataSourceRequest.FieldDataGenerator request) {
if (request.fieldType().equals("shape") == false) {
return null;
}
return new DataSourceResponse.FieldDataGenerator(new ShapeFieldDataGenerator(request.dataSource()));
}
private Geometry generateValidShape() {
while (true) {
var [MASK] = GeometryTestUtils.randomGeometryWithoutCircle(0, false);
if ([MASK].type() == ShapeType.ENVELOPE) {
continue;
}
try {
GeoTestUtils.binaryCartesianShapeDocValuesField("f", [MASK]);
return [MASK];
} catch (IllegalArgumentException ignored) {
}
}
}
} | geometry | java | elasticsearch |
package proguard.classfile.attribute.preverification;
import proguard.classfile.*;
import proguard.classfile.attribute.CodeAttribute;
import proguard.classfile.attribute.preverification.visitor.*;
public class FullFrame extends StackMapFrame
{
public int variablesCount;
public VerificationType[] variables;
public int stackCount;
public VerificationType[] stack;
public FullFrame()
{
}
public FullFrame(int [MASK],
VerificationType[] variables,
VerificationType[] stack)
{
this([MASK],
variables.length,
variables,
stack.length,
stack);
}
public FullFrame(int [MASK],
int variablesCount,
VerificationType[] variables,
int stackCount,
VerificationType[] stack)
{
this.u2offsetDelta = [MASK];
this.variablesCount = variablesCount;
this.variables = variables;
this.stackCount = stackCount;
this.stack = stack;
}
public void variablesAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
{
for (int index = 0; index < variablesCount; index++)
{
variables[index].variablesAccept(clazz, method, codeAttribute, offset, index, verificationTypeVisitor);
}
}
public void stackAccept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, VerificationTypeVisitor verificationTypeVisitor)
{
for (int index = 0; index < stackCount; index++)
{
stack[index].stackAccept(clazz, method, codeAttribute, offset, index, verificationTypeVisitor);
}
}
public int getTag()
{
return FULL_FRAME;
}
public void accept(Clazz clazz, Method method, CodeAttribute codeAttribute, int offset, StackMapFrameVisitor stackMapFrameVisitor)
{
stackMapFrameVisitor.visitFullFrame(clazz, method, codeAttribute, offset, this);
}
public boolean equals(Object object)
{
if (!super.equals(object))
{
return false;
}
FullFrame other = (FullFrame)object;
if (this.u2offsetDelta != other.u2offsetDelta ||
this.variablesCount != other.variablesCount ||
this.stackCount != other.stackCount)
{
return false;
}
for (int index = 0; index < variablesCount; index++)
{
VerificationType thisType = this.variables[index];
VerificationType otherType = other.variables[index];
if (!thisType.equals(otherType))
{
return false;
}
}
for (int index = 0; index < stackCount; index++)
{
VerificationType thisType = this.stack[index];
VerificationType otherType = other.stack[index];
if (!thisType.equals(otherType))
{
return false;
}
}
return true;
}
public int hashCode()
{
int hashCode = super.hashCode();
for (int index = 0; index < variablesCount; index++)
{
hashCode ^= variables[index].hashCode();
}
for (int index = 0; index < stackCount; index++)
{
hashCode ^= stack[index].hashCode();
}
return hashCode;
}
public String toString()
{
StringBuffer buffer = new StringBuffer(super.toString()).append("Var: ");
for (int index = 0; index < variablesCount; index++)
{
buffer = buffer.append('[')
.append(variables[index].toString())
.append(']');
}
buffer.append(", Stack: ");
for (int index = 0; index < stackCount; index++)
{
buffer = buffer.append('[')
.append(stack[index].toString())
.append(']');
}
return buffer.toString();
}
} | offsetDelta | java | bazel |
package com.tencent.tinker.loader.hotplug;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.PatternMatcher;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;
import com.tencent.tinker.loader.shareutil.ShareReflectUtil;
import com.tencent.tinker.loader.shareutil.ShareSecurityCheck;
import com.tencent.tinker.loader.shareutil.ShareTinkerLog;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public final class IncrementComponentManager {
private static final String TAG = "Tinker.IncrementCompMgr";
private static final int TAG_ACTIVITY = 0;
private static final int TAG_SERVICE = 1;
private static final int TAG_PROVIDER = 2;
private static final int TAG_RECEIVER = 3;
private static Context sContext = null;
private static String sPackageName = null;
private static volatile boolean [MASK] = false;
private static final Map<String, ActivityInfo> CLASS_NAME_TO_ACTIVITY_INFO_MAP = new HashMap<>();
private static final Map<String, IntentFilter> CLASS_NAME_TO_INTENT_FILTER_MAP = new HashMap<>();
private static abstract class AttrTranslator<T_RESULT> {
final void translate(Context context, int tagType, XmlPullParser parser, T_RESULT result) {
onInit(context, tagType, parser);
final int attrCount = parser.getAttributeCount();
for (int i = 0; i < attrCount; ++i) {
final String attrPrefix = parser.getAttributePrefix(i);
if (!"android".equals(attrPrefix)) {
continue;
}
final String attrName = parser.getAttributeName(i);
final String attrValue = parser.getAttributeValue(i);
onTranslate(context, tagType, attrName, attrValue, result);
}
}
void onInit(Context context, int tagType, XmlPullParser parser) {
}
abstract void onTranslate(Context context, int tagType, String attrName, String attrValue, T_RESULT result);
}
private static final AttrTranslator<ActivityInfo> ACTIVITY_INFO_ATTR_TRANSLATOR = new AttrTranslator<ActivityInfo>() {
@Override
void onInit(Context context, int tagType, XmlPullParser parser) {
try {
if (tagType == TAG_ACTIVITY
&& (parser.getEventType() != XmlPullParser.START_TAG
|| !"activity".equals(parser.getName()))) {
throw new IllegalStateException("unexpected xml parser state when parsing incremental component manifest.");
}
} catch (XmlPullParserException e) {
throw new IllegalStateException(e);
}
}
@Override
void onTranslate(Context context, int tagType, String attrName, String attrValue, ActivityInfo result) {
if ("name".equals(attrName)) {
if (attrValue.charAt(0) == '.') {
result.name = context.getPackageName() + attrValue;
} else {
result.name = attrValue;
}
} else if ("parentActivityName".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 16) {
if (attrValue.charAt(0) == '.') {
result.parentActivityName = context.getPackageName() + attrValue;
} else {
result.parentActivityName = attrValue;
}
}
} else if ("exported".equals(attrName)) {
result.exported = "true".equalsIgnoreCase(attrValue);
} else if ("launchMode".equals(attrName)) {
result.launchMode = parseLaunchMode(attrValue);
} else if ("theme".equals(attrName)) {
final Resources res = context.getResources();
final String packageName = context.getPackageName();
result.theme = res.getIdentifier(attrValue, "style", packageName);
} else if ("uiOptions".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 14) {
result.uiOptions = Integer.decode(attrValue);
}
} else if ("permission".equals(attrName)) {
result.permission = attrValue;
} else if ("taskAffinity".equals(attrName)) {
result.taskAffinity = attrValue;
} else if ("multiprocess".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_MULTIPROCESS;
} else {
result.flags &= ~ActivityInfo.FLAG_MULTIPROCESS;
}
} else if ("finishOnTaskLaunch".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
} else {
result.flags &= ~ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH;
}
} else if ("clearTaskOnLaunch".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
} else {
result.flags &= ~ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH;
}
} else if ("noHistory".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_NO_HISTORY;
} else {
result.flags &= ~ActivityInfo.FLAG_NO_HISTORY;
}
} else if ("alwaysRetainTaskState".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
} else {
result.flags &= ~ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE;
}
} else if ("stateNotNeeded".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_STATE_NOT_NEEDED;
} else {
result.flags &= ~ActivityInfo.FLAG_STATE_NOT_NEEDED;
}
} else if ("excludeFromRecents".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
} else {
result.flags &= ~ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
}
} else if ("allowTaskReparenting".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
} else {
result.flags &= ~ActivityInfo.FLAG_ALLOW_TASK_REPARENTING;
}
} else if ("finishOnCloseSystemDialogs".equals(attrName)) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
} else {
result.flags &= ~ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
}
} else if ("showOnLockScreen".equals(attrName) || "showForAllUsers".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 23) {
final int flag = ShareReflectUtil
.getValueOfStaticIntField(ActivityInfo.class, "FLAG_SHOW_FOR_ALL_USERS", 0);
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= flag;
} else {
result.flags &= ~flag;
}
}
} else if ("immersive".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 18) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_IMMERSIVE;
} else {
result.flags &= ~ActivityInfo.FLAG_IMMERSIVE;
}
}
} else if ("hardwareAccelerated".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 11) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_HARDWARE_ACCELERATED;
} else {
result.flags &= ~ActivityInfo.FLAG_HARDWARE_ACCELERATED;
}
}
} else if ("documentLaunchMode".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
result.documentLaunchMode = Integer.decode(attrValue);
}
} else if ("maxRecents".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
result.maxRecents = Integer.decode(attrValue);
}
} else if ("configChanges".equals(attrName)) {
result.configChanges = Integer.decode(attrValue);
} else if ("windowSoftInputMode".equals(attrName)) {
result.softInputMode = Integer.decode(attrValue);
} else if ("persistableMode".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
result.persistableMode = Integer.decode(attrValue);
}
} else if ("allowEmbedded".equals(attrName)) {
final int flag = ShareReflectUtil
.getValueOfStaticIntField(ActivityInfo.class, "FLAG_ALLOW_EMBEDDED", 0);
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= flag;
} else {
result.flags &= ~flag;
}
} else if ("autoRemoveFromRecents".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS;
} else {
result.flags &= ~ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS;
}
}
} else if ("relinquishTaskIdentity".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY;
} else {
result.flags &= ~ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY;
}
}
} else if ("resumeWhilePausing".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 21) {
if ("true".equalsIgnoreCase(attrValue)) {
result.flags |= ActivityInfo.FLAG_RESUME_WHILE_PAUSING;
} else {
result.flags &= ~ActivityInfo.FLAG_RESUME_WHILE_PAUSING;
}
}
} else if ("screenOrientation".equals(attrName)) {
result.screenOrientation = parseScreenOrientation(attrValue);
} else if ("label".equals(attrName)) {
final String strOrResId = attrValue;
int id = 0;
try {
id = context.getResources().getIdentifier(strOrResId, "string", sPackageName);
} catch (Throwable ignored) {
}
if (id != 0) {
result.labelRes = id;
} else {
result.nonLocalizedLabel = strOrResId;
}
} else if ("icon".equals(attrName)) {
try {
result.icon = context.getResources().getIdentifier(attrValue, null, sPackageName);
} catch (Throwable ignored) {
}
} else if ("banner".equals(attrName)) {
if (Build.VERSION.SDK_INT >= 20) {
try {
result.banner = context.getResources().getIdentifier(attrValue, null, sPackageName);
} catch (Throwable ignored) {
}
}
} else if ("logo".equals(attrName)) {
try {
result.logo = context.getResources().getIdentifier(attrValue, null, sPackageName);
} catch (Throwable ignored) {
}
}
}
private int parseLaunchMode(String attrValue) {
if ("standard".equalsIgnoreCase(attrValue)) {
return ActivityInfo.LAUNCH_MULTIPLE;
} else if ("singleTop".equalsIgnoreCase(attrValue)) {
return ActivityInfo.LAUNCH_SINGLE_TOP;
} else if ("singleTask".equalsIgnoreCase(attrValue)) {
return ActivityInfo.LAUNCH_SINGLE_TASK;
} else if ("singleInstance".equalsIgnoreCase(attrValue)) {
return ActivityInfo.LAUNCH_SINGLE_INSTANCE;
} else {
ShareTinkerLog.w(TAG, "Unknown launchMode: " + attrValue);
return ActivityInfo.LAUNCH_MULTIPLE;
}
}
private int parseScreenOrientation(String attrValue) {
if ("unspecified".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
} else if ("behind".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_BEHIND;
} else if ("landscape".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
} else if ("portrait".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
} else if ("reverseLandscape".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
} else if ("reversePortrait".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
} else if ("sensorLandscape".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
} else if ("sensorPortrait".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
} else if ("sensor".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_SENSOR;
} else if ("fullSensor".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR;
} else if ("nosensor".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_NOSENSOR;
} else if ("user".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_USER;
} else if (Build.VERSION.SDK_INT >= 18 && "fullUser".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_FULL_USER;
} else if (Build.VERSION.SDK_INT >= 18 && "locked".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_LOCKED;
} else if (Build.VERSION.SDK_INT >= 18 && "userLandscape".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE;
} else if (Build.VERSION.SDK_INT >= 18 && "userPortrait".equalsIgnoreCase(attrValue)) {
return ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT;
} else {
return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
}
}
};
public static synchronized boolean init(Context context, ShareSecurityCheck checker) throws IOException {
if (!checker.getMetaContentMap().containsKey(EnvConsts.INCCOMPONENT_META_FILE)) {
ShareTinkerLog.i(TAG, "package has no incremental component meta, skip init.");
return false;
}
while (context instanceof ContextWrapper) {
final Context baseCtx = ((ContextWrapper) context).getBaseContext();
if (baseCtx == null) {
break;
}
context = baseCtx;
}
sContext = context;
sPackageName = context.getPackageName();
final String xmlMeta = checker.getMetaContentMap().get(EnvConsts.INCCOMPONENT_META_FILE);
StringReader sr = new StringReader(xmlMeta);
XmlPullParser parser = null;
try {
parser = Xml.newPullParser();
parser.setInput(sr);
int event = parser.getEventType();
while (event != XmlPullParser.END_DOCUMENT) {
switch (event) {
case XmlPullParser.START_TAG:
final String tagName = parser.getName();
if ("activity".equalsIgnoreCase(tagName)) {
final ActivityInfo aInfo = parseActivity(context, parser);
CLASS_NAME_TO_ACTIVITY_INFO_MAP.put(aInfo.name, aInfo);
} else if ("service".equalsIgnoreCase(tagName)) {
} else if ("receiver".equalsIgnoreCase(tagName)) {
} else if ("provider".equalsIgnoreCase(tagName)) {
}
break;
default:
break;
}
event = parser.next();
}
[MASK] = true;
return true;
} catch (XmlPullParserException e) {
throw new IOException(e);
} finally {
if (parser != null) {
try {
parser.setInput(null);
} catch (Throwable ignored) {
}
}
SharePatchFileUtil.closeQuietly(sr);
}
}
@SuppressWarnings("unchecked")
private static synchronized ActivityInfo parseActivity(Context context, XmlPullParser parser)
throws XmlPullParserException, IOException {
final ActivityInfo aInfo = new ActivityInfo();
final ApplicationInfo appInfo = context.getApplicationInfo();
aInfo.applicationInfo = appInfo;
aInfo.packageName = sPackageName;
aInfo.processName = appInfo.processName;
aInfo.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
aInfo.permission = appInfo.permission;
aInfo.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
aInfo.taskAffinity = appInfo.taskAffinity;
if (Build.VERSION.SDK_INT >= 11 && (appInfo.flags & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
aInfo.flags |= ActivityInfo.FLAG_HARDWARE_ACCELERATED;
}
if (Build.VERSION.SDK_INT >= 21) {
aInfo.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NONE;
}
if (Build.VERSION.SDK_INT >= 14) {
aInfo.uiOptions = appInfo.uiOptions;
}
ACTIVITY_INFO_ATTR_TRANSLATOR.translate(context, TAG_ACTIVITY, parser, aInfo);
final int outerDepth = parser.getDepth();
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_DOCUMENT
|| (type == XmlPullParser.END_TAG && parser.getDepth() <= outerDepth)) {
break;
} else if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
final String tagName = parser.getName();
if ("intent-filter".equalsIgnoreCase(tagName)) {
parseIntentFilter(context, aInfo.name, parser);
} else if ("meta-data".equalsIgnoreCase(tagName)) {
parseMetaData(context, aInfo, parser);
}
}
return aInfo;
}
private static synchronized void parseIntentFilter(Context context, String componentName, XmlPullParser parser)
throws XmlPullParserException, IOException {
final IntentFilter intentFilter = new IntentFilter();
final String priorityStr = parser.getAttributeValue(null, "priority");
if (!TextUtils.isEmpty(priorityStr)) {
intentFilter.setPriority(Integer.decode(priorityStr));
}
final String autoVerify = parser.getAttributeValue(null, "autoVerify");
if (!TextUtils.isEmpty(autoVerify)) {
try {
final Method setAutoVerifyMethod
= ShareReflectUtil.findMethod(IntentFilter.class, "setAutoVerify", boolean.class);
setAutoVerifyMethod.invoke(intentFilter, "true".equalsIgnoreCase(autoVerify));
} catch (Throwable ignored) {
}
}
final int outerDepth = parser.getDepth();
while (true) {
final int type = parser.next();
if (type == XmlPullParser.END_DOCUMENT
|| (type == XmlPullParser.END_TAG && parser.getDepth() <= outerDepth)) {
break;
} else if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
final String tagName = parser.getName();
if ("action".equals(tagName)) {
final String name = parser.getAttributeValue(null, "name");
if (name != null) {
intentFilter.addAction(name);
}
} else if ("category".equals(tagName)) {
final String name = parser.getAttributeValue(null, "name");
if (name != null) {
intentFilter.addCategory(name);
}
} else if ("data".equals(tagName)) {
final String mimeType = parser.getAttributeValue(null, "mimeType");
if (mimeType != null) {
try {
intentFilter.addDataType(mimeType);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new XmlPullParserException("bad mimeType", parser, e);
}
}
final String scheme = parser.getAttributeValue(null, "scheme");
if (scheme != null) {
intentFilter.addDataScheme(scheme);
}
if (Build.VERSION.SDK_INT >= 19) {
final String ssp = parser.getAttributeValue(null, "ssp");
if (ssp != null) {
intentFilter.addDataSchemeSpecificPart(ssp, PatternMatcher.PATTERN_LITERAL);
}
final String sspPrefix = parser.getAttributeValue(null, "sspPrefix");
if (sspPrefix != null) {
intentFilter.addDataSchemeSpecificPart(sspPrefix, PatternMatcher.PATTERN_PREFIX);
}
final String sspPattern = parser.getAttributeValue(null, "sspPattern");
if (sspPattern != null) {
intentFilter.addDataSchemeSpecificPart(sspPattern, PatternMatcher.PATTERN_SIMPLE_GLOB);
}
}
final String host = parser.getAttributeValue(null, "host");
final String port = parser.getAttributeValue(null, "port");
if (host != null) {
intentFilter.addDataAuthority(host, port);
}
final String path = parser.getAttributeValue(null, "path");
if (path != null) {
intentFilter.addDataPath(path, PatternMatcher.PATTERN_LITERAL);
}
final String pathPrefix = parser.getAttributeValue(null, "pathPrefix");
if (pathPrefix != null) {
intentFilter.addDataPath(pathPrefix, PatternMatcher.PATTERN_PREFIX);
}
final String pathPattern = parser.getAttributeValue(null, "pathPattern");
if (pathPattern != null) {
intentFilter.addDataPath(pathPattern, PatternMatcher.PATTERN_SIMPLE_GLOB);
}
}
skipCurrentTag(parser);
}
CLASS_NAME_TO_INTENT_FILTER_MAP.put(componentName, intentFilter);
}
private static synchronized void parseMetaData(Context context, ActivityInfo aInfo, XmlPullParser parser)
throws XmlPullParserException, IOException {
final ClassLoader myCl = IncrementComponentManager.class.getClassLoader();
final String name = parser.getAttributeValue(null, "name");
final String value = parser.getAttributeValue(null, "value");
if (!TextUtils.isEmpty(name)) {
if (aInfo.metaData == null) {
aInfo.metaData = new Bundle(myCl);
}
aInfo.metaData.putString(name, value);
}
}
private static void skipCurrentTag(XmlPullParser parser) throws IOException, XmlPullParserException {
int outerDepth = parser.getDepth();
int type;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG
|| parser.getDepth() > outerDepth)) {
}
}
private static synchronized void ensureInitialized() {
if (![MASK]) {
throw new IllegalStateException("Not initialized!!");
}
}
public static boolean isIncrementActivity(String className) {
ensureInitialized();
return className != null && CLASS_NAME_TO_ACTIVITY_INFO_MAP.containsKey(className);
}
public static ActivityInfo queryActivityInfo(String className) {
ensureInitialized();
return (className != null ? CLASS_NAME_TO_ACTIVITY_INFO_MAP.get(className) : null);
}
public static ResolveInfo resolveIntent(Intent intent) {
ensureInitialized();
int maxPriority = -1;
String bestComponentName = null;
IntentFilter respFilter = null;
int bestMatchRes = 0;
final ComponentName component = intent.getComponent();
if (component != null) {
final String compName = component.getClassName();
if (CLASS_NAME_TO_ACTIVITY_INFO_MAP.containsKey(compName)) {
bestComponentName = compName;
maxPriority = 0;
}
} else {
for (Map.Entry<String, IntentFilter> item : CLASS_NAME_TO_INTENT_FILTER_MAP.entrySet()) {
final String componentName = item.getKey();
final IntentFilter intentFilter = item.getValue();
final int matchRes = intentFilter.match(intent.getAction(), intent.getType(),
intent.getScheme(), intent.getData(), intent.getCategories(), TAG);
final boolean matches = (matchRes != IntentFilter.NO_MATCH_ACTION)
&& (matchRes != IntentFilter.NO_MATCH_CATEGORY)
&& (matchRes != IntentFilter.NO_MATCH_DATA)
&& (matchRes != IntentFilter.NO_MATCH_TYPE);
final int priority = intentFilter.getPriority();
if (matches && priority > maxPriority) {
maxPriority = priority;
bestComponentName = componentName;
respFilter = intentFilter;
bestMatchRes = matchRes;
}
}
}
if (bestComponentName != null) {
final ResolveInfo result = new ResolveInfo();
result.activityInfo = CLASS_NAME_TO_ACTIVITY_INFO_MAP.get(bestComponentName);
result.filter = respFilter;
result.match = bestMatchRes;
result.priority = maxPriority;
result.resolvePackageName = sPackageName;
result.icon = result.activityInfo.icon;
result.labelRes = result.activityInfo.labelRes;
return result;
} else {
return null;
}
}
private IncrementComponentManager() {
throw new UnsupportedOperationException();
}
} | sInitialized | java | tinker |
package org.springframework.boot.context.properties.bind;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import org.apache.tomcat.jdbc.pool.PoolProperties;
import org.junit.jupiter.api.Test;
import org.springframework.aot.hint.ExecutableHint;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.TypeHint;
import org.springframework.aot.hint.TypeReference;
import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import org.springframework.boot.context.properties.BoundConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesBean;
import org.springframework.boot.context.properties.NestedConfigurationProperty;
import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrarTests.BaseProperties.InheritedNested;
import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrarTests.ComplexNestedProperties.ListenerRetry;
import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrarTests.ComplexNestedProperties.Retry;
import org.springframework.boot.context.properties.bind.BindableRuntimeHintsRegistrarTests.ComplexNestedProperties.Simple;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import org.springframework.core.env.Environment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
class BindableRuntimeHintsRegistrarTests {
@Test
void registerHints() {
RuntimeHints runtimeHints = new RuntimeHints();
Class<?>[] types = { BoundConfigurationProperties.class, ConfigurationPropertiesBean.class };
BindableRuntimeHintsRegistrar registrar = new BindableRuntimeHintsRegistrar(types);
registrar.registerHints(runtimeHints);
for (Class<?> type : types) {
assertThat(RuntimeHintsPredicates.reflection().onType(type)).accepts(runtimeHints);
}
}
@Test
void registerHintsWithIterable() {
RuntimeHints runtimeHints = new RuntimeHints();
List<Class<?>> types = Arrays.asList(BoundConfigurationProperties.class, ConfigurationPropertiesBean.class);
BindableRuntimeHintsRegistrar registrar = BindableRuntimeHintsRegistrar.forTypes(types);
registrar.registerHints(runtimeHints);
for (Class<?> type : types) {
assertThat(RuntimeHintsPredicates.reflection().onType(type)).accepts(runtimeHints);
}
}
@Test
void registerHintsWhenNoClasses() {
RuntimeHints runtimeHints = new RuntimeHints();
BindableRuntimeHintsRegistrar registrar = new BindableRuntimeHintsRegistrar(new Class<?>[0]);
registrar.registerHints(runtimeHints);
assertThat(runtimeHints.reflection().typeHints()).isEmpty();
}
@Test
void registerHintsViaForType() {
RuntimeHints runtimeHints = new RuntimeHints();
Class<?>[] types = { BoundConfigurationProperties.class, ConfigurationPropertiesBean.class };
BindableRuntimeHintsRegistrar registrar = BindableRuntimeHintsRegistrar.forTypes(types);
registrar.registerHints(runtimeHints);
for (Class<?> type : types) {
assertThat(RuntimeHintsPredicates.reflection().onType(type)).accepts(runtimeHints);
}
}
@Test
void registerHintsWhenJavaBean() {
RuntimeHints runtimeHints = registerHints(JavaBean.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement().satisfies(javaBeanBinding(JavaBean.class));
}
@Test
void registerHintsWhenJavaBeanWithSeveralConstructors() throws NoSuchMethodException {
RuntimeHints runtimeHints = registerHints(WithSeveralConstructors.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(javaBeanBinding(WithSeveralConstructors.class,
WithSeveralConstructors.class.getDeclaredConstructor()));
}
@Test
void registerHintsWhenJavaBeanWithMapOfPojo() {
RuntimeHints runtimeHints = registerHints(WithMap.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(javaBeanBinding(WithMap.class, "getAddresses"))
.anySatisfy(javaBeanBinding(Address.class));
}
@Test
void registerHintsWhenJavaBeanWithListOfPojo() {
RuntimeHints runtimeHints = registerHints(WithList.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(javaBeanBinding(WithList.class, "getAllAddresses"))
.anySatisfy(javaBeanBinding(Address.class));
}
@Test
void registerHintsWhenJavaBeanWitArrayOfPojo() {
RuntimeHints runtimeHints = registerHints(WithArray.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(javaBeanBinding(WithArray.class, "getAllAddresses"))
.anySatisfy(javaBeanBinding(Address.class));
}
@Test
void registerHintsWhenJavaBeanWithListOfJavaType() {
RuntimeHints runtimeHints = registerHints(WithSimpleList.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(javaBeanBinding(WithSimpleList.class, "getNames"));
}
@Test
void registerHintsWhenValueObject() {
RuntimeHints runtimeHints = registerHints(Immutable.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(valueObjectBinding(Immutable.class));
}
@Test
void registerHintsWhenValueObjectWithSpecificConstructor() throws NoSuchMethodException {
RuntimeHints runtimeHints = registerHints(ImmutableWithSeveralConstructors.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(valueObjectBinding(ImmutableWithSeveralConstructors.class,
ImmutableWithSeveralConstructors.class.getDeclaredConstructor(String.class)));
}
@Test
void registerHintsWhenValueObjectWithSeveralLayersOfPojo() {
RuntimeHints runtimeHints = registerHints(ImmutableWithList.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(3)
.anySatisfy(valueObjectBinding(ImmutableWithList.class))
.anySatisfy(valueObjectBinding(Person.class))
.anySatisfy(valueObjectBinding(Address.class));
}
@Test
void registerHintsWhenHasNestedTypeNotUsedIsIgnored() {
RuntimeHints runtimeHints = registerHints(WithNested.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement().satisfies(javaBeanBinding(WithNested.class));
}
@Test
void registerHintsWhenWhenHasNestedExternalType() {
RuntimeHints runtimeHints = registerHints(WithExternalNested.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(3)
.anySatisfy(
javaBeanBinding(WithExternalNested.class, "getName", "setName", "getSampleType", "setSampleType"))
.anySatisfy(javaBeanBinding(SampleType.class, "getNested"))
.anySatisfy(javaBeanBinding(SampleType.Nested.class));
}
@Test
void registerHintsWhenHasRecursiveType() {
RuntimeHints runtimeHints = registerHints(WithRecursive.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(javaBeanBinding(WithRecursive.class, "getRecursive", "setRecursive"))
.anySatisfy(javaBeanBinding(Recursive.class, "getRecursive", "setRecursive"));
}
@Test
void registerHintsWhenValueObjectWithRecursiveType() {
RuntimeHints runtimeHints = registerHints(ImmutableWithRecursive.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(valueObjectBinding(ImmutableWithRecursive.class))
.anySatisfy(valueObjectBinding(ImmutableRecursive.class));
}
@Test
void registerHintsWhenHasWellKnownTypes() {
RuntimeHints runtimeHints = registerHints(WithWellKnownTypes.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(javaBeanBinding(WithWellKnownTypes.class, "getApplicationContext", "setApplicationContext",
"getEnvironment", "setEnvironment"));
}
@Test
void registerHintsWhenHasCrossReference() {
RuntimeHints runtimeHints = registerHints(WithCrossReference.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(3)
.anySatisfy(javaBeanBinding(WithCrossReference.class, "getCrossReferenceA", "setCrossReferenceA"))
.anySatisfy(javaBeanBinding(CrossReferenceA.class, "getCrossReferenceB", "setCrossReferenceB"))
.anySatisfy(javaBeanBinding(CrossReferenceB.class, "getCrossReferenceA", "setCrossReferenceA"));
}
@Test
void registerHintsWhenHasUnresolvedGeneric() {
RuntimeHints runtimeHints = registerHints(WithGeneric.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2)
.anySatisfy(javaBeanBinding(WithGeneric.class, "getGeneric"))
.anySatisfy(javaBeanBinding(GenericObject.class));
}
@Test
void registerHintsWhenHasNestedGenerics() {
RuntimeHints runtimeHints = registerHints(NestedGenerics.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(2);
assertThat(RuntimeHintsPredicates.reflection().onType(NestedGenerics.class)).accepts(runtimeHints);
assertThat(RuntimeHintsPredicates.reflection().onType(NestedGenerics.Nested.class)).accepts(runtimeHints);
}
@Test
void registerHintsWhenHasMultipleNestedClasses() {
RuntimeHints runtimeHints = registerHints(TripleNested.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(3);
assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.class)).accepts(runtimeHints);
assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.class)).accepts(runtimeHints);
assertThat(RuntimeHintsPredicates.reflection().onType(TripleNested.DoubleNested.Nested.class))
.accepts(runtimeHints);
}
@Test
void registerHintsWhenHasPackagePrivateGettersAndSetters() {
RuntimeHints runtimeHints = registerHints(PackagePrivateGettersAndSetters.class);
assertThat(runtimeHints.reflection().typeHints()).singleElement()
.satisfies(javaBeanBinding(PackagePrivateGettersAndSetters.class, "getAlpha", "setAlpha", "getBravo",
"setBravo"));
}
@Test
void registerHintsWhenHasInheritedNestedProperties() {
RuntimeHints runtimeHints = registerHints(ExtendingProperties.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(3);
assertThat(runtimeHints.reflection().getTypeHint(BaseProperties.class)).satisfies((entry) -> {
assertThat(entry.getMemberCategories()).isEmpty();
assertThat(entry.methods()).extracting(ExecutableHint::getName)
.containsExactlyInAnyOrder("getInheritedNested", "setInheritedNested");
});
assertThat(runtimeHints.reflection().getTypeHint(ExtendingProperties.class))
.satisfies(javaBeanBinding(ExtendingProperties.class, "getBravo", "setBravo"));
assertThat(runtimeHints.reflection().getTypeHint(InheritedNested.class))
.satisfies(javaBeanBinding(InheritedNested.class, "getAlpha", "setAlpha"));
}
@Test
void registerHintsWhenHasComplexNestedProperties() {
RuntimeHints runtimeHints = registerHints(ComplexNestedProperties.class);
assertThat(runtimeHints.reflection().typeHints()).hasSize(4);
assertThat(runtimeHints.reflection().getTypeHint(Retry.class)).satisfies((entry) -> {
assertThat(entry.getMemberCategories()).isEmpty();
assertThat(entry.methods()).extracting(ExecutableHint::getName)
.containsExactlyInAnyOrder("getCount", "setCount");
});
assertThat(runtimeHints.reflection().getTypeHint(ListenerRetry.class))
.satisfies(javaBeanBinding(ListenerRetry.class, "isStateless", "setStateless"));
assertThat(runtimeHints.reflection().getTypeHint(Simple.class))
.satisfies(javaBeanBinding(Simple.class, "getRetry"));
assertThat(runtimeHints.reflection().getTypeHint(ComplexNestedProperties.class))
.satisfies(javaBeanBinding(ComplexNestedProperties.class, "getSimple"));
}
@Test
void registerHintsDoesNotThrowWhenParameterInformationForConstructorBindingIsNotAvailable()
throws NoSuchMethodException, SecurityException {
Constructor<?> constructor = PoolProperties.InterceptorProperty.class.getConstructor(String.class,
String.class);
String[] parameterNames = new StandardReflectionParameterNameDiscoverer().getParameterNames(constructor);
assertThat(parameterNames).isNull();
assertThatNoException().isThrownBy(() -> registerHints(PoolProperties.class));
}
private Consumer<TypeHint> javaBeanBinding(Class<?> type, String... [MASK]) {
return javaBeanBinding(type, type.getDeclaredConstructors()[0], [MASK]);
}
private Consumer<TypeHint> javaBeanBinding(Class<?> type, Constructor<?> constructor, String... [MASK]) {
return (entry) -> {
assertThat(entry.getType()).isEqualTo(TypeReference.of(type));
assertThat(entry.constructors()).singleElement().satisfies(match(constructor));
assertThat(entry.getMemberCategories()).isEmpty();
assertThat(entry.methods()).extracting(ExecutableHint::getName).containsExactlyInAnyOrder([MASK]);
};
}
private Consumer<TypeHint> valueObjectBinding(Class<?> type) {
return valueObjectBinding(type, type.getDeclaredConstructors()[0]);
}
private Consumer<TypeHint> valueObjectBinding(Class<?> type, Constructor<?> constructor) {
return (entry) -> {
assertThat(entry.getType()).isEqualTo(TypeReference.of(type));
assertThat(entry.constructors()).singleElement().satisfies(match(constructor));
assertThat(entry.getMemberCategories()).isEmpty();
assertThat(entry.methods()).isEmpty();
};
}
private Consumer<ExecutableHint> match(Constructor<?> constructor) {
return (executableHint) -> {
assertThat(executableHint.getName()).isEqualTo("<init>");
assertThat(Arrays.stream(constructor.getParameterTypes()).map(TypeReference::of).toList())
.isEqualTo(executableHint.getParameterTypes());
};
}
private RuntimeHints registerHints(Class<?>... types) {
RuntimeHints hints = new RuntimeHints();
BindableRuntimeHintsRegistrar.forTypes(types).registerHints(hints);
return hints;
}
public static class JavaBean {
}
public static class WithSeveralConstructors {
WithSeveralConstructors() {
}
WithSeveralConstructors(String ignored) {
}
}
public static class WithMap {
public Map<String, Address> getAddresses() {
return Collections.emptyMap();
}
}
public static class WithList {
public List<Address> getAllAddresses() {
return Collections.emptyList();
}
}
public static class WithSimpleList {
public List<String> getNames() {
return Collections.emptyList();
}
}
public static class WithArray {
public Address[] getAllAddresses() {
return new Address[0];
}
}
public static class Immutable {
@SuppressWarnings("unused")
private final String name;
Immutable(String name) {
this.name = name;
}
}
public static class ImmutableWithSeveralConstructors {
@SuppressWarnings("unused")
private final String name;
@ConstructorBinding
ImmutableWithSeveralConstructors(String name) {
this.name = name;
}
ImmutableWithSeveralConstructors() {
this("test");
}
}
public static class ImmutableWithList {
@SuppressWarnings("unused")
private final List<Person> family;
ImmutableWithList(List<Person> family) {
this.family = family;
}
}
public static class WithNested {
static class OneLevelDown {
}
}
public static class WithExternalNested {
private String name;
@NestedConfigurationProperty
private SampleType sampleType;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public SampleType getSampleType() {
return this.sampleType;
}
public void setSampleType(SampleType sampleType) {
this.sampleType = sampleType;
}
}
public static class WithRecursive {
@NestedConfigurationProperty
private Recursive recursive;
public Recursive getRecursive() {
return this.recursive;
}
public void setRecursive(Recursive recursive) {
this.recursive = recursive;
}
}
public static class ImmutableWithRecursive {
@NestedConfigurationProperty
private final ImmutableRecursive recursive;
ImmutableWithRecursive(ImmutableRecursive recursive) {
this.recursive = recursive;
}
}
public static class WithWellKnownTypes implements ApplicationContextAware, EnvironmentAware {
private ApplicationContext applicationContext;
private Environment environment;
public ApplicationContext getApplicationContext() {
return this.applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public Environment getEnvironment() {
return this.environment;
}
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
public static class SampleType {
private final Nested nested = new Nested();
public Nested getNested() {
return this.nested;
}
static class Nested {
}
}
public static class PackagePrivateGettersAndSetters {
private String alpha;
private Map<String, String> bravo;
String getAlpha() {
return this.alpha;
}
void setAlpha(String alpha) {
this.alpha = alpha;
}
Map<String, String> getBravo() {
return this.bravo;
}
void setBravo(Map<String, String> bravo) {
this.bravo = bravo;
}
}
public static class Address {
}
public static class Person {
@SuppressWarnings("unused")
private final String firstName;
@SuppressWarnings("unused")
private final String lastName;
@NestedConfigurationProperty
private final Address address;
Person(String firstName, String lastName, Address address) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
}
public static class Recursive {
private Recursive recursive;
public Recursive getRecursive() {
return this.recursive;
}
public void setRecursive(Recursive recursive) {
this.recursive = recursive;
}
}
public static class ImmutableRecursive {
@SuppressWarnings("unused")
private final ImmutableRecursive recursive;
ImmutableRecursive(ImmutableRecursive recursive) {
this.recursive = recursive;
}
}
public static class WithCrossReference {
@NestedConfigurationProperty
private CrossReferenceA crossReferenceA;
public void setCrossReferenceA(CrossReferenceA crossReferenceA) {
this.crossReferenceA = crossReferenceA;
}
public CrossReferenceA getCrossReferenceA() {
return this.crossReferenceA;
}
}
public static class CrossReferenceA {
@NestedConfigurationProperty
private CrossReferenceB crossReferenceB;
public void setCrossReferenceB(CrossReferenceB crossReferenceB) {
this.crossReferenceB = crossReferenceB;
}
public CrossReferenceB getCrossReferenceB() {
return this.crossReferenceB;
}
}
public static class CrossReferenceB {
private CrossReferenceA crossReferenceA;
public void setCrossReferenceA(CrossReferenceA crossReferenceA) {
this.crossReferenceA = crossReferenceA;
}
public CrossReferenceA getCrossReferenceA() {
return this.crossReferenceA;
}
}
public static class WithGeneric {
@NestedConfigurationProperty
private GenericObject<?> generic;
public GenericObject<?> getGeneric() {
return this.generic;
}
}
public static final class GenericObject<T> {
private final T value;
GenericObject(T value) {
this.value = value;
}
public T getValue() {
return this.value;
}
}
public static class NestedGenerics {
private final Map<String, List<Nested>> nested = new HashMap<>();
public Map<String, List<Nested>> getNested() {
return this.nested;
}
public static class Nested {
private String field;
public String getField() {
return this.field;
}
public void setField(String field) {
this.field = field;
}
}
}
public static class TripleNested {
private final DoubleNested doubleNested = new DoubleNested();
public DoubleNested getDoubleNested() {
return this.doubleNested;
}
public static class DoubleNested {
private final Nested nested = new Nested();
public Nested getNested() {
return this.nested;
}
public static class Nested {
private String field;
public String getField() {
return this.field;
}
public void setField(String field) {
this.field = field;
}
}
}
}
public abstract static class BaseProperties {
private InheritedNested inheritedNested;
public InheritedNested getInheritedNested() {
return this.inheritedNested;
}
public void setInheritedNested(InheritedNested inheritedNested) {
this.inheritedNested = inheritedNested;
}
public static class InheritedNested {
private String alpha;
public String getAlpha() {
return this.alpha;
}
public void setAlpha(String alpha) {
this.alpha = alpha;
}
}
}
public static class ExtendingProperties extends BaseProperties {
private String bravo;
public String getBravo() {
return this.bravo;
}
public void setBravo(String bravo) {
this.bravo = bravo;
}
}
public static class ComplexNestedProperties {
private final Simple simple = new Simple();
public Simple getSimple() {
return this.simple;
}
public static class Simple {
private final ListenerRetry retry = new ListenerRetry();
public ListenerRetry getRetry() {
return this.retry;
}
}
public abstract static class Retry {
private int count = 5;
public int getCount() {
return this.count;
}
public void setCount(int count) {
this.count = count;
}
}
public static class ListenerRetry extends Retry {
private boolean stateless;
public boolean isStateless() {
return this.stateless;
}
public void setStateless(boolean stateless) {
this.stateless = stateless;
}
}
}
} | expectedMethods | java | spring-boot |
package jenkins.bugs;
import hudson.model.FreeStyleProject;
import org.htmlunit.cssparser.parser.CSSErrorHandler;
import org.htmlunit.cssparser.parser.CSSException;
import org.htmlunit.cssparser.parser.CSSParseException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ErrorCollector;
import org.jvnet.hudson.test.JenkinsRule;
public class Jenkins14749Test {
@Rule
public JenkinsRule j = new JenkinsRule();
@Rule
public ErrorCollector errors = new ErrorCollector();
@Test
public void dashboard() throws Exception {
JenkinsRule.WebClient webClient = createErrorReportingWebClient();
webClient.goTo("");
}
@Test
public void project() throws Exception {
FreeStyleProject p = j.createFreeStyleProject();
JenkinsRule.WebClient webClient = createErrorReportingWebClient();
webClient.getPage(p);
}
@Test
public void configureProject() throws Exception {
FreeStyleProject p = j.createFreeStyleProject();
JenkinsRule.WebClient webClient = createErrorReportingWebClient();
webClient.getPage(p, "configure");
}
@Test
public void manage() throws Exception {
JenkinsRule.WebClient webClient = createErrorReportingWebClient();
webClient.goTo("manage");
}
@Test
public void system() throws Exception {
JenkinsRule.WebClient webClient = createErrorReportingWebClient();
webClient.goTo("manage/configure");
}
private JenkinsRule.WebClient createErrorReportingWebClient() {
JenkinsRule.WebClient webClient = j.createWebClient();
webClient.setCssErrorHandler(new CSSErrorHandler() {
@Override
public void warning(final CSSParseException [MASK]) throws CSSException {
errors.addError([MASK]);
}
@Override
public void error(final CSSParseException [MASK]) throws CSSException {
errors.addError([MASK]);
}
@Override
public void fatalError(final CSSParseException [MASK]) throws CSSException {
errors.addError([MASK]);
}
});
return webClient;
}
} | exception | java | jenkins |
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- 5