language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/invocation/mockref/MockWeakReference.java
{ "start": 1039, "end": 1582 }
class ____ strong reference to the mock object " + "and it prevents getting the mock collected. Mockito internally needs " + "to keep weak references to mock objects to avoid memory leaks for " + "certain types of MockMaker implementations. If you see this exception " + "using Mockito public API, please file a bug. For more information see " + "issue #1313."); } return ref; } }
keeps
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleMethodBuildItem.java
{ "start": 1557, "end": 3073 }
enum ____ message keys. * * @return the method or {@code null} if there is no corresponding method declared on the message bundle interface */ public MethodInfo getMethod() { return method; } /** * * @return {@code true} if there is a corresponding method declared on the message bundle interface * @see #getMethod() */ public boolean hasMethod() { return method != null; } public String getTemplate() { return template; } /** * A bundle method that does not need to be validated has {@code null} template id. * * @return {@code true} if the template needs to be validated */ public boolean isValidatable() { return templateId != null; } /** * * @return {@code true} if the message comes from the default bundle */ public boolean isDefaultBundle() { return isDefaultBundle; } /** * * @return {@code true} if the template was generated, e.g. a message bundle method for an enum */ public boolean hasGeneratedTemplate() { return hasGeneratedTemplate; } /** * * @return the path * @see TemplateAnalysis#path */ public String getPathForAnalysis() { if (method != null) { return method.declaringClass().name() + "#" + method.name(); } if (templateId != null) { return templateId; } return bundleName + "_" + key; } }
constant
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/conf/ReconfigurationServlet.java
{ "start": 1470, "end": 8946 }
class ____ extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(ReconfigurationServlet.class); // the prefix used to fing the attribute holding the reconfigurable // for a given request // // we get the attribute prefix + servlet path public static final String CONF_SERVLET_RECONFIGURABLE_PREFIX = "conf.servlet.reconfigurable."; @Override public void init() throws ServletException { super.init(); } private Reconfigurable getReconfigurable(HttpServletRequest req) { LOG.info("servlet path: " + req.getServletPath()); LOG.info("getting attribute: " + CONF_SERVLET_RECONFIGURABLE_PREFIX + req.getServletPath()); return (Reconfigurable) this.getServletContext().getAttribute(CONF_SERVLET_RECONFIGURABLE_PREFIX + req.getServletPath()); } private void printHeader(PrintWriter out, String nodeName) { out.print("<html><head>"); out.printf("<title>%s Reconfiguration Utility</title>%n", StringEscapeUtils.escapeHtml4(nodeName)); out.print("</head><body>\n"); out.printf("<h1>%s Reconfiguration Utility</h1>%n", StringEscapeUtils.escapeHtml4(nodeName)); } private void printFooter(PrintWriter out) { out.print("</body></html>\n"); } /** * Print configuration options that can be changed. */ private void printConf(PrintWriter out, Reconfigurable reconf) { Configuration oldConf = reconf.getConf(); Configuration newConf = new Configuration(); Collection<ReconfigurationUtil.PropertyChange> changes = ReconfigurationUtil.getChangedProperties(newConf, oldConf); boolean changeOK = true; out.println("<form action=\"\" method=\"post\">"); out.println("<table border=\"1\">"); out.println("<tr><th>Property</th><th>Old value</th>"); out.println("<th>New value </th><th></th></tr>"); for (ReconfigurationUtil.PropertyChange c: changes) { out.print("<tr><td>"); if (!reconf.isPropertyReconfigurable(c.prop)) { out.print("<font color=\"red\">" + StringEscapeUtils.escapeHtml4(c.prop) + "</font>"); changeOK = false; } else { out.print(StringEscapeUtils.escapeHtml4(c.prop)); out.print("<input type=\"hidden\" name=\"" + StringEscapeUtils.escapeHtml4(c.prop) + "\" value=\"" + StringEscapeUtils.escapeHtml4(c.newVal) + "\"/>"); } out.print("</td><td>" + (c.oldVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml4(c.oldVal)) + "</td><td>" + (c.newVal == null ? "<it>default</it>" : StringEscapeUtils.escapeHtml4(c.newVal)) + "</td>"); out.print("</tr>\n"); } out.println("</table>"); if (!changeOK) { out.println("<p><font color=\"red\">WARNING: properties marked red" + " will not be changed until the next restart.</font></p>"); } out.println("<input type=\"submit\" value=\"Apply\" />"); out.println("</form>"); } @SuppressWarnings("unchecked") private Enumeration<String> getParams(HttpServletRequest req) { return req.getParameterNames(); } /** * Apply configuratio changes after admin has approved them. */ private void applyChanges(PrintWriter out, Reconfigurable reconf, HttpServletRequest req) throws ReconfigurationException { Configuration oldConf = reconf.getConf(); Configuration newConf = new Configuration(); Enumeration<String> params = getParams(req); synchronized(oldConf) { while (params.hasMoreElements()) { String rawParam = params.nextElement(); String param = StringEscapeUtils.unescapeHtml4(rawParam); String value = StringEscapeUtils.unescapeHtml4(req.getParameter(rawParam)); if (value != null) { if (value.equals(newConf.getRaw(param)) || value.equals("default") || value.equals("null") || value.isEmpty()) { if ((value.equals("default") || value.equals("null") || value.isEmpty()) && oldConf.getRaw(param) != null) { out.println("<p>Changed \"" + StringEscapeUtils.escapeHtml4(param) + "\" from \"" + StringEscapeUtils.escapeHtml4(oldConf.getRaw(param)) + "\" to default</p>"); reconf.reconfigureProperty(param, null); } else if (!value.equals("default") && !value.equals("null") && !value.isEmpty() && (oldConf.getRaw(param) == null || !oldConf.getRaw(param).equals(value))) { // change from default or value to different value if (oldConf.getRaw(param) == null) { out.println("<p>Changed \"" + StringEscapeUtils.escapeHtml4(param) + "\" from default to \"" + StringEscapeUtils.escapeHtml4(value) + "\"</p>"); } else { out.println("<p>Changed \"" + StringEscapeUtils.escapeHtml4(param) + "\" from \"" + StringEscapeUtils.escapeHtml4(oldConf. getRaw(param)) + "\" to \"" + StringEscapeUtils.escapeHtml4(value) + "\"</p>"); } reconf.reconfigureProperty(param, value); } else { LOG.info("property " + param + " unchanged"); } } else { // parameter value != newConf value out.println("<p>\"" + StringEscapeUtils.escapeHtml4(param) + "\" not changed because value has changed from \"" + StringEscapeUtils.escapeHtml4(value) + "\" to \"" + StringEscapeUtils.escapeHtml4(newConf.getRaw(param)) + "\" since approval</p>"); } } } } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOG.info("GET"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Reconfigurable reconf = getReconfigurable(req); String nodeName = reconf.getClass().getCanonicalName(); printHeader(out, nodeName); printConf(out, reconf); printFooter(out); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { LOG.info("POST"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); Reconfigurable reconf = getReconfigurable(req); String nodeName = reconf.getClass().getCanonicalName(); printHeader(out, nodeName); try { applyChanges(out, reconf, req); } catch (ReconfigurationException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, StringUtils.stringifyException(e)); return; } out.println("<p><a href=\"" + req.getServletPath() + "\">back</a></p>"); printFooter(out); } }
ReconfigurationServlet
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/changelog/inmemory/InMemoryStateChangelogStorage.java
{ "start": 1266, "end": 1805 }
class ____ implements StateChangelogStorage<InMemoryChangelogStateHandle> { @Override public InMemoryStateChangelogWriter createWriter( String operatorID, KeyGroupRange keyGroupRange, MailboxExecutor mailboxExecutor) { return new InMemoryStateChangelogWriter(keyGroupRange); } @Override public StateChangelogHandleReader<InMemoryChangelogStateHandle> createReader() { return handle -> CloseableIterator.fromList(handle.getChanges(), change -> {}); } }
InMemoryStateChangelogStorage
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/service/AbstractService.java
{ "start": 1373, "end": 1431 }
class ____ services. */ @Public @Evolving public abstract
for
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/builder/BuilderWithCreatorTest.java
{ "start": 1982, "end": 2350 }
class ____ { private final boolean value; @JsonCreator public BooleanCreatorBuilder(boolean v) { value = v; } public BooleanCreatorValue build() { return new BooleanCreatorValue(value); } } // With Int @JsonDeserialize(builder=IntCreatorBuilder.class) static
BooleanCreatorBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/NullNeedsCastForVarargsTest.java
{ "start": 2362, "end": 2741 }
class ____ { void test() { assertThat(ImmutableList.of("a")).containsExactly((Object[]) null); } } """) .addOutputLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; import com.google.common.collect.ImmutableList;
Test
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/EntryPointAssertions_setPrintAssertionsDescription_Test.java
{ "start": 1037, "end": 2285 }
class ____ extends EntryPointAssertionsBaseTest { private static final boolean DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS = AbstractAssert.printAssertionsDescription; @AfterEach void afterEachTest() { // reset to the default value to avoid side effects on the other tests AbstractAssert.printAssertionsDescription = DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS; } @ParameterizedTest @MethodSource("setPrintAssertionsDescriptionMethodsFunctions") void should_set_printAssertionsDescription_value(Consumer<Boolean> setPrintAssertionsDescriptionMethodsFunction) { // GIVEN boolean printAssertionsDescription = !DEFAULT_EXTRACTING_BARE_NAME_PROPERTY_METHODS; // WHEN setPrintAssertionsDescriptionMethodsFunction.accept(printAssertionsDescription); // THEN then(AbstractAssert.printAssertionsDescription).isEqualTo(printAssertionsDescription); } private static Stream<Consumer<Boolean>> setPrintAssertionsDescriptionMethodsFunctions() { return Stream.of(Assertions::setPrintAssertionsDescription, BDDAssertions::setPrintAssertionsDescription, WithAssertions::setPrintAssertionsDescription); } }
EntryPointAssertions_setPrintAssertionsDescription_Test
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/CustomConsumerExceptionHandlerTest.java
{ "start": 1234, "end": 2680 }
class ____ extends ContextTestSupport { private static final CountDownLatch LATCH = new CountDownLatch(1); @Override protected Registry createCamelRegistry() throws Exception { Registry jndi = super.createCamelRegistry(); jndi.bind("myHandler", new MyExceptionHandler()); return jndi; } @Test public void testDeadLetterChannelAlwaysHandled() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(1); getMockEndpoint("mock:bar").expectedMessageCount(1); getMockEndpoint("mock:result").expectedMessageCount(0); template.sendBody("seda:foo", "Hello World"); assertMockEndpointsSatisfied(); assertTrue(LATCH.await(5, TimeUnit.SECONDS), "Should have been called"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("seda:foo?exceptionHandler=#myHandler").routeId("foo").to("mock:foo").to("direct:bar") .to("mock:result"); from("direct:bar").routeId("bar").onException(IllegalArgumentException.class).maximumRedeliveries(3) .redeliveryDelay(0).end().to("mock:bar") .throwException(new IllegalArgumentException("Forced")); } }; } private static final
CustomConsumerExceptionHandlerTest
java
google__error-prone
check_api/src/main/java/com/google/errorprone/matchers/method/MethodInvocationMatcher.java
{ "start": 5140, "end": 6804 }
interface ____ { /** The category of properties that this value falls into. */ TokenType type(); /** * The value to compare with {@link TokenType#extract(Context, VisitorState)} to determine * whether this property matches. */ Object comparisonKey(); /** A token limiting the {@link Kind} of invocation to match. */ public record Kind(MethodKind kind) implements Token { public static Kind create(MethodKind kind) { return new Kind(kind); } @Override public MethodKind comparisonKey() { return kind(); } @Override public TokenType type() { return TokenType.KIND; } } /** A token limiting the name of the method being invoked. */ public record MethodName(String methodName) implements Token { @Override public Object comparisonKey() { return methodName(); } @Override public TokenType type() { return TokenType.METHOD_NAME; } public static MethodName create(String methodName) { return new MethodName(methodName); } } /** A token limiting the types of the formal parameters of the method being invoked. */ public record ParameterTypes(ImmutableList<String> parameterTypes) implements Token { @Override public TokenType type() { return TokenType.PARAMETER_TYPES; } @Override public Object comparisonKey() { return parameterTypes(); } public static ParameterTypes create(ImmutableList<String> types) { return new ParameterTypes(types); } } /** A token specifying the
Token
java
apache__camel
components/camel-nitrite/src/generated/java/org/apache/camel/component/nitrite/NitriteTypeConvertersLoader.java
{ "start": 883, "end": 2635 }
class ____ implements TypeConverterLoader, CamelContextAware { private CamelContext camelContext; public NitriteTypeConvertersLoader() { } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException { registerConverters(registry); } private void registerConverters(TypeConverterRegistry registry) { addTypeConverter(registry, java.util.List.class, org.dizitart.no2.Cursor.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.nitrite.NitriteTypeConverters.fromCursorToList((org.dizitart.no2.Cursor) value); if (false && answer == null) { answer = Void.class; } return answer; }); addTypeConverter(registry, org.dizitart.no2.Document.class, java.util.Map.class, false, (type, exchange, value) -> { Object answer = org.apache.camel.component.nitrite.NitriteTypeConverters.fromMapToDocument((java.util.Map) value); if (false && answer == null) { answer = Void.class; } return answer; }); } private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) { registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method)); } }
NitriteTypeConvertersLoader
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/plugins/MapperPlugin.java
{ "start": 846, "end": 3357 }
interface ____ { /** * Returns additional mapper implementations added by this plugin. * <p> * The key of the returned {@link Map} is the unique name for the mapper which will be used * as the mapping {@code type}, and the value is a {@link Mapper.TypeParser} to parse the * mapper settings into a {@link Mapper}. */ default Map<String, Mapper.TypeParser> getMappers() { return Collections.emptyMap(); } /** * Returns the runtime field implementations added by this plugin. * <p> * The key of the returned {@link Map} is the unique name for the field type which will be used * as the mapping {@code type}, and the value is a {@link RuntimeField.Parser} to parse the * field type settings into a {@link RuntimeField}. */ default Map<String, RuntimeField.Parser> getRuntimeFields() { return Collections.emptyMap(); } /** * Returns additional metadata mapper implementations added by this plugin. * <p> * The key of the returned {@link Map} is the unique name for the metadata mapper, which * is used in the mapping json to configure the metadata mapper, and the value is a * {@link MetadataFieldMapper.TypeParser} to parse the mapper settings into a * {@link MetadataFieldMapper}. */ default Map<String, MetadataFieldMapper.TypeParser> getMetadataMappers() { return Collections.emptyMap(); } /** * Returns a function that given an index name returns a predicate which fields must match in order to be returned by get mappings, * get index, get field mappings and field capabilities API. Useful to filter the fields that such API return. The predicate receives * the field name as input argument and should return true to show the field and false to hide it. */ default Function<String, FieldPredicate> getFieldFilter() { return NOOP_FIELD_FILTER; } /** * The default field filter applied, which doesn't filter anything. That means that by default get mappings, get index * get field mappings and field capabilities API will return every field that's present in the mappings. */ Function<String, FieldPredicate> NOOP_FIELD_FILTER = new Function<>() { @Override public FieldPredicate apply(String index) { return FieldPredicate.ACCEPT_ALL; } @Override public String toString() { return "accept all"; } }; }
MapperPlugin
java
grpc__grpc-java
okhttp/src/main/java/io/grpc/okhttp/ExceptionHandlingFrameWriter.java
{ "start": 1542, "end": 7159 }
class ____ implements FrameWriter { private static final Logger log = Logger.getLogger(OkHttpClientTransport.class.getName()); private final TransportExceptionHandler transportExceptionHandler; private final FrameWriter frameWriter; private final OkHttpFrameLogger frameLogger = new OkHttpFrameLogger(Level.FINE, OkHttpClientTransport.class); ExceptionHandlingFrameWriter( TransportExceptionHandler transportExceptionHandler, FrameWriter frameWriter) { this.transportExceptionHandler = checkNotNull(transportExceptionHandler, "transportExceptionHandler"); this.frameWriter = Preconditions.checkNotNull(frameWriter, "frameWriter"); } @Override public void connectionPreface() { try { frameWriter.connectionPreface(); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void ackSettings(Settings peerSettings) { frameLogger.logSettingsAck(OkHttpFrameLogger.Direction.OUTBOUND); try { frameWriter.ackSettings(peerSettings); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void pushPromise(int streamId, int promisedStreamId, List<Header> requestHeaders) { frameLogger.logPushPromise(OkHttpFrameLogger.Direction.OUTBOUND, streamId, promisedStreamId, requestHeaders); try { frameWriter.pushPromise(streamId, promisedStreamId, requestHeaders); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void flush() { try { frameWriter.flush(); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void synStream( boolean outFinished, boolean inFinished, int streamId, int associatedStreamId, List<Header> headerBlock) { try { frameWriter.synStream(outFinished, inFinished, streamId, associatedStreamId, headerBlock); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void synReply(boolean outFinished, int streamId, List<Header> headerBlock) { try { frameWriter.synReply(outFinished, streamId, headerBlock); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void headers(int streamId, List<Header> headerBlock) { frameLogger.logHeaders(OkHttpFrameLogger.Direction.OUTBOUND, streamId, headerBlock, false); try { frameWriter.headers(streamId, headerBlock); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void rstStream(int streamId, ErrorCode errorCode) { frameLogger.logRstStream(OkHttpFrameLogger.Direction.OUTBOUND, streamId, errorCode); try { frameWriter.rstStream(streamId, errorCode); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public int maxDataLength() { return frameWriter.maxDataLength(); } @Override public void data(boolean outFinished, int streamId, Buffer source, int byteCount) { frameLogger.logData(OkHttpFrameLogger.Direction.OUTBOUND, streamId, source.buffer(), byteCount, outFinished); try { frameWriter.data(outFinished, streamId, source, byteCount); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void settings(Settings okHttpSettings) { frameLogger.logSettings(OkHttpFrameLogger.Direction.OUTBOUND, okHttpSettings); try { frameWriter.settings(okHttpSettings); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void ping(boolean ack, int payload1, int payload2) { if (ack) { frameLogger.logPingAck(OkHttpFrameLogger.Direction.OUTBOUND, ((long) payload1 << 32) | (payload2 & 0xFFFFFFFFL)); } else { frameLogger.logPing(OkHttpFrameLogger.Direction.OUTBOUND, ((long) payload1 << 32) | (payload2 & 0xFFFFFFFFL)); } try { frameWriter.ping(ack, payload1, payload2); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void goAway(int lastGoodStreamId, ErrorCode errorCode, byte[] debugData) { frameLogger.logGoAway(OkHttpFrameLogger.Direction.OUTBOUND, lastGoodStreamId, errorCode, ByteString.of(debugData)); try { frameWriter.goAway(lastGoodStreamId, errorCode, debugData); // Flush it since after goAway, we are likely to close this writer. frameWriter.flush(); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void windowUpdate(int streamId, long windowSizeIncrement) { frameLogger.logWindowsUpdate(OkHttpFrameLogger.Direction.OUTBOUND, streamId, windowSizeIncrement); try { frameWriter.windowUpdate(streamId, windowSizeIncrement); } catch (IOException e) { transportExceptionHandler.onException(e); } } @Override public void close() { try { frameWriter.close(); } catch (IOException e) { log.log(getLogLevel(e), "Failed closing connection", e); } } /** * Accepts a throwable and returns the appropriate logging level. Uninteresting exceptions * should not clutter the log. */ @VisibleForTesting static Level getLogLevel(Throwable t) { if (t.getClass().equals(IOException.class)) { return Level.FINE; } return Level.INFO; } /** A
ExceptionHandlingFrameWriter
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/SystemUtils.java
{ "start": 42559, "end": 43079 }
class ____ loaded. * </p> * * @since 3.13.0 */ public static final boolean IS_JAVA_17 = getJavaVersionMatches("17"); /** * The constant {@code true} if this is Java version 18 (also 18.x versions). * <p> * The result depends on the value of the {@link #JAVA_SPECIFICATION_VERSION} constant. * </p> * <p> * The field will return {@code false} if {@link #JAVA_SPECIFICATION_VERSION} is {@code null}. * </p> * <p> * This value is initialized when the
is
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/main/java/io/quarkus/resteasy/reactive/jackson/deployment/processor/JacksonDeserializerFactory.java
{ "start": 5806, "end": 7363 }
class ____$quarkusjacksondeserializer extends StdDeserializer implements ContextualDeserializer { * private JavaType[] valueTypesmvn clean install; * * public DataItem$quarkusjacksondeserializer() { * super(DataItem.class); * } * * public Object deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JacksonException { * DataItem dataItem = new DataItem(); * Iterator iterator = ((JsonNode) jsonParser.getCodec().readTree(jsonParser)).fields(); * * while (iterator.hasNext()) { * Map.Entry entry = (Map.iterator) var3.next(); * String field = (String) entry.getKey(); * JsonNode jsonNode = (JsonNode) entry.getValue(); * if (jsonNode.isNull()) { * continue; * } * switch (field) { * case "content": * dataItem.setContent(context.readTreeAsValue(jsonNode, this.valueTypes[0])); * break; * } * } * * return dataItem; * } * * public JsonDeserializer createContextual(DeserializationContext context, BeanProperty beanProperty) { * JavaType[] valueTypes = JacksonMapperUtil.getGenericsJavaTypes(context, beanProperty); * DataItem$quarkusjacksondeserializer deserializer = new DataItem$quarkusjacksondeserializer(); * deserializer.valueTypes = valueTypes; * return (JsonDeserializer) deserializer; * } * } * }</pre> */ public
DataItem
java
apache__camel
components/camel-mina/src/test/java/org/apache/camel/component/mina/MinaVMTransferExchangeOptionTest.java
{ "start": 1454, "end": 5143 }
class ____ extends BaseMinaTest { @Test public void testMinaTransferExchangeOptionWithoutException() throws Exception { Exchange exchange = sendExchange(false); assertExchange(exchange, false); } @Test public void testMinaTransferExchangeOptionWithException() throws Exception { Exchange exchange = sendExchange(true); assertExchange(exchange, true); } private Exchange sendExchange(boolean setException) throws Exception { Endpoint endpoint = context.getEndpoint( String.format("mina:vm://localhost:%1$s?sync=true&encoding=UTF-8&transferExchange=true&objectCodecPattern=*", getPort())); Exchange exchange = endpoint.createExchange(); Message message = exchange.getIn(); message.setBody("Hello!"); message.setHeader("cheese", "feta"); exchange.setProperty("ham", "old"); exchange.setProperty("setException", setException); Producer producer = endpoint.createProducer(); producer.start(); producer.process(exchange); return exchange; } private void assertExchange(Exchange exchange, boolean hasException) { if (!hasException) { Message out = exchange.getMessage(); assertNotNull(out); assertEquals("Goodbye!", out.getBody()); assertEquals("cheddar", out.getHeader("cheese")); } else { Message fault = exchange.getMessage(); assertNotNull(fault); assertNotNull(fault.getBody()); assertTrue(fault.getBody() instanceof InterruptedException, "Should get the InterruptedException exception"); assertEquals("nihao", fault.getHeader("hello")); } // in should stay the same Message in = exchange.getIn(); assertNotNull(in); assertEquals("Hello!", in.getBody()); assertEquals("feta", in.getHeader("cheese")); // however the shared properties have changed assertEquals("fresh", exchange.getProperty("salami")); assertNull(exchange.getProperty("Charset")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { fromF("mina:vm://localhost:%1$s?sync=true&encoding=UTF-8&transferExchange=true&objectCodecPattern=*", getPort()) .process(e -> { assertNotNull(e.getIn().getBody()); assertNotNull(e.getIn().getHeaders()); assertNotNull(e.getProperties()); assertEquals("Hello!", e.getIn().getBody()); assertEquals("feta", e.getIn().getHeader("cheese")); assertEquals("old", e.getProperty("ham")); assertEquals(ExchangePattern.InOut, e.getPattern()); Boolean setException = (Boolean) e.getProperty("setException"); if (setException) { e.getOut().setBody(new InterruptedException()); e.getOut().setHeader("hello", "nihao"); } else { e.getOut().setBody("Goodbye!"); e.getOut().setHeader("cheese", "cheddar"); } e.setProperty("salami", "fresh"); e.setProperty("Charset", Charset.defaultCharset()); }); } }; } }
MinaVMTransferExchangeOptionTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JdkObsoleteTest.java
{ "start": 5758, "end": 6021 }
class ____ { String f() { var sb = new StringBuffer(); return sb.append(42).toString(); } } """) .addOutputLines( "out/Test.java", """
Test
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/constraint/processor/BatchedRequests.java
{ "start": 1887, "end": 2422 }
class ____ implements ConstraintPlacementAlgorithmInput, Iterable<SchedulingRequest> { // PlacementAlgorithmOutput attempt - the number of times the requests in this // batch has been placed but was rejected by the scheduler. private final int placementAttempt; private final ApplicationId applicationId; private final Collection<SchedulingRequest> requests; private final Map<String, Set<NodeId>> blacklist = new HashMap<>(); private IteratorType iteratorType; /** * Iterator Type. */ public
BatchedRequests
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/outlierdetection/PrecisionTests.java
{ "start": 950, "end": 3142 }
class ____ extends AbstractXContentSerializingTestCase<Precision> { @Override protected Precision doParseInstance(XContentParser parser) throws IOException { return Precision.fromXContent(parser); } @Override protected Precision createTestInstance() { return createRandom(); } @Override protected Precision mutateInstance(Precision instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Precision> instanceReader() { return Precision::new; } public static Precision createRandom() { int thresholdsSize = randomIntBetween(1, 3); List<Double> thresholds = new ArrayList<>(thresholdsSize); for (int i = 0; i < thresholdsSize; i++) { thresholds.add(randomDouble()); } return new Precision(thresholds); } public void testEvaluate() { InternalAggregations aggs = InternalAggregations.from( Arrays.asList( mockFilter("precision_at_0.25_TP", 1L), mockFilter("precision_at_0.25_FP", 4L), mockFilter("precision_at_0.5_TP", 3L), mockFilter("precision_at_0.5_FP", 1L), mockFilter("precision_at_0.75_TP", 5L), mockFilter("precision_at_0.75_FP", 0L) ) ); Precision precision = new Precision(Arrays.asList(0.25, 0.5, 0.75)); EvaluationMetricResult result = precision.evaluate(aggs); String expected = """ {"0.25":0.2,"0.5":0.75,"0.75":1.0}"""; assertThat(Strings.toString(result), equalTo(expected)); } public void testEvaluate_GivenZeroTpAndFp() { InternalAggregations aggs = InternalAggregations.from( Arrays.asList(mockFilter("precision_at_1.0_TP", 0L), mockFilter("precision_at_1.0_FP", 0L)) ); Precision precision = new Precision(Arrays.asList(1.0)); EvaluationMetricResult result = precision.evaluate(aggs); String expected = "{\"1.0\":0.0}"; assertThat(Strings.toString(result), equalTo(expected)); } }
PrecisionTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/id/AndFormulaTest.java
{ "start": 1807, "end": 1900 }
class ____ { @Id @Formula( value = "VALUE" ) public Integer id; } }
EntityWithIdAndFormula
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/UnwrapSingleArrayScalarsTest.java
{ "start": 518, "end": 19068 }
class ____ { boolean _v; void setV(boolean v) { _v = v; } } private final ObjectMapper MAPPER = newJsonMapper(); private final ObjectReader NO_UNWRAPPING_READER = MAPPER.reader(); private final ObjectReader UNWRAPPING_READER = MAPPER.reader() .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS); /* /********************************************************** /* Tests for boolean /********************************************************** */ @Test public void testBooleanPrimitiveArrayUnwrap() throws Exception { // [databind#381] ObjectMapper mapper = jsonMapperBuilder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES) .build(); BooleanBean result = mapper.readValue(new StringReader("{\"v\":[true]}"), BooleanBean.class); assertTrue(result._v); _verifyMultiValueArrayFail("[{\"v\":[true,true]}]", BooleanBean.class); result = mapper.readValue("{\"v\":[null]}", BooleanBean.class); assertNotNull(result); assertFalse(result._v); result = mapper.readValue("[{\"v\":[null]}]", BooleanBean.class); assertNotNull(result); assertFalse(result._v); boolean[] array = mapper.readValue(new StringReader("[ [ null ] ]"), boolean[].class); assertNotNull(array); assertEquals(1, array.length); assertFalse(array[0]); } /* /********************************************************** /* Single-element as array tests, numbers /********************************************************** */ // [databind#381] @Test public void testSingleElementScalarArrays() throws Exception { final int intTest = 932832; final double doubleTest = 32.3234; final long longTest = 2374237428374293423L; final short shortTest = (short) intTest; final float floatTest = 84.3743f; final byte byteTest = (byte) 43; final char charTest = 'c'; ObjectMapper mapper = jsonMapperBuilder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); final int intValue = mapper.readValue(asArray(intTest), Integer.TYPE); assertEquals(intTest, intValue); final Integer integerWrapperValue = mapper.readValue(asArray(Integer.valueOf(intTest)), Integer.class); assertEquals(Integer.valueOf(intTest), integerWrapperValue); final double doubleValue = mapper.readValue(asArray(doubleTest), Double.class); assertEquals(doubleTest, doubleValue); final Double doubleWrapperValue = mapper.readValue(asArray(Double.valueOf(doubleTest)), Double.class); assertEquals(Double.valueOf(doubleTest), doubleWrapperValue); final long longValue = mapper.readValue(asArray(longTest), Long.TYPE); assertEquals(longTest, longValue); final Long longWrapperValue = mapper.readValue(asArray(Long.valueOf(longTest)), Long.class); assertEquals(Long.valueOf(longTest), longWrapperValue); final short shortValue = mapper.readValue(asArray(shortTest), Short.TYPE); assertEquals(shortTest, shortValue); final Short shortWrapperValue = mapper.readValue(asArray(Short.valueOf(shortTest)), Short.class); assertEquals(Short.valueOf(shortTest), shortWrapperValue); final float floatValue = mapper.readValue(asArray(floatTest), Float.TYPE); assertEquals(floatTest, floatValue); final Float floatWrapperValue = mapper.readValue(asArray(Float.valueOf(floatTest)), Float.class); assertEquals(Float.valueOf(floatTest), floatWrapperValue); final byte byteValue = mapper.readValue(asArray(byteTest), Byte.TYPE); assertEquals(byteTest, byteValue); final Byte byteWrapperValue = mapper.readValue(asArray(Byte.valueOf(byteTest)), Byte.class); assertEquals(Byte.valueOf(byteTest), byteWrapperValue); final char charValue = mapper.readValue(asArray(q(String.valueOf(charTest))), Character.TYPE); assertEquals(charTest, charValue); final Character charWrapperValue = mapper.readValue(asArray(q(String.valueOf(charTest))), Character.class); assertEquals(Character.valueOf(charTest), charWrapperValue); final boolean booleanTrueValue = mapper.readValue(asArray(true), Boolean.TYPE); assertTrue(booleanTrueValue); final boolean booleanFalseValue = mapper.readValue(asArray(false), Boolean.TYPE); assertFalse(booleanFalseValue); final Boolean booleanWrapperTrueValue = mapper.readValue(asArray(Boolean.valueOf(true)), Boolean.class); assertEquals(Boolean.TRUE, booleanWrapperTrueValue); } @Test public void testSingleElementArrayDisabled() throws Exception { final ObjectMapper mapper = jsonMapperBuilder() .disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); try { mapper.readValue("[42]", Integer.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Integer.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342]", Long.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[42342342342342342]", Long.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[42]", Short.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[327.2323]", Float.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[82.81902]", Float.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[22]", Byte.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("['d']", Character.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.class); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } try { mapper.readValue("[true]", Boolean.TYPE); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException exp) { //Exception was thrown correctly } } @Test public void testMultiValueArrayException() throws IOException { _verifyMultiValueArrayFail("[42,42]", Integer.class); _verifyMultiValueArrayFail("[42,42]", Integer.TYPE); _verifyMultiValueArrayFail("[42342342342342,42342342342342]", Long.class); _verifyMultiValueArrayFail("[42342342342342342,42342342342342]", Long.TYPE); _verifyMultiValueArrayFail("[42,42]", Short.class); _verifyMultiValueArrayFail("[42,42]", Short.TYPE); _verifyMultiValueArrayFail("[22,23]", Byte.class); _verifyMultiValueArrayFail("[22,23]", Byte.TYPE); _verifyMultiValueArrayFail("[327.2323,327.2323]", Float.class); _verifyMultiValueArrayFail("[82.81902,327.2323]", Float.TYPE); _verifyMultiValueArrayFail("[42.273,42.273]", Double.class); _verifyMultiValueArrayFail("[42.2723,42.273]", Double.TYPE); _verifyMultiValueArrayFail(asArray(q("c") + "," + q("d")), Character.class); _verifyMultiValueArrayFail(asArray(q("c") + "," + q("d")), Character.TYPE); _verifyMultiValueArrayFail("[true,false]", Boolean.class); _verifyMultiValueArrayFail("[true,false]", Boolean.TYPE); } /* /********************************************************** /* Simple non-primitive types /********************************************************** */ @Test public void testSingleString() throws Exception { String value = "FOO!"; String result = MAPPER.readValue("\""+value+"\"", String.class); assertEquals(value, result); } @Test public void testSingleStringWrapped() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); String value = "FOO!"; try { mapper.readValue("[\""+value+"\"]", String.class); fail("Exception not thrown when attempting to unwrap a single value 'String' array into a simple String"); } catch (MismatchedInputException exp) { _verifyNoDeserFromArray(exp); } mapper = jsonMapperBuilder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); try { mapper.readValue("[\""+value+"\",\""+value+"\"]", String.class); fail("Exception not thrown when attempting to unwrap a single value 'String' array that contained more than one value into a simple String"); } catch (MismatchedInputException exp) { verifyException(exp, "Attempted to unwrap"); } String result = mapper.readValue("[\""+value+"\"]", String.class); assertEquals(value, result); } @Test public void testBigDecimal() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); BigDecimal value = new BigDecimal("0.001"); BigDecimal result = mapper.readValue(value.toString(), BigDecimal.class); assertEquals(value, result); try { mapper.readValue("[" + value.toString() + "]", BigDecimal.class); fail("Exception was not thrown when attempting to read a single value array of BigDecimal when UNWRAP_SINGLE_VALUE_ARRAYS feature is disabled"); } catch (MismatchedInputException exp) { _verifyNoDeserFromArray(exp); } mapper = jsonMapperBuilder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); result = mapper.readValue("[" + value.toString() + "]", BigDecimal.class); assertEquals(value, result); try { mapper.readValue("[" + value.toString() + "," + value.toString() + "]", BigDecimal.class); fail("Exception was not thrown when attempting to read a muti value array of BigDecimal when UNWRAP_SINGLE_VALUE_ARRAYS feature is enabled"); } catch (MismatchedInputException exp) { verifyException(exp, "Attempted to unwrap"); } } @Test public void testBigInteger() throws Exception { ObjectMapper mapper = jsonMapperBuilder() .disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); BigInteger value = new BigInteger("-1234567890123456789012345567809"); BigInteger result = mapper.readValue(value.toString(), BigInteger.class); assertEquals(value, result); try { mapper.readValue("[" + value.toString() + "]", BigInteger.class); fail("Exception was not thrown when attempting to read a single value array of BigInteger when UNWRAP_SINGLE_VALUE_ARRAYS feature is disabled"); } catch (MismatchedInputException exp) { _verifyNoDeserFromArray(exp); } mapper = jsonMapperBuilder() .enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .build(); result = mapper.readValue("[" + value.toString() + "]", BigInteger.class); assertEquals(value, result); try { mapper.readValue("[" + value.toString() + "," + value.toString() + "]", BigInteger.class); fail("Exception was not thrown when attempting to read a multi-value array of BigInteger when UNWRAP_SINGLE_VALUE_ARRAYS feature is enabled"); } catch (MismatchedInputException exp) { verifyException(exp, "Attempted to unwrap"); } } @Test public void testClassAsArray() throws Exception { Class<?> result = MAPPER .readerFor(Class.class) .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue(q(String.class.getName())); assertEquals(String.class, result); try { MAPPER.readerFor(Class.class) .without(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[" + q(String.class.getName()) + "]"); fail("Did not throw exception when UNWRAP_SINGLE_VALUE_ARRAYS feature was disabled and attempted to read a Class array containing one element"); } catch (MismatchedInputException e) { _verifyNoDeserFromArray(e); } _verifyMultiValueArrayFail("[" + q(Object.class.getName()) + "," + q(Object.class.getName()) +"]", Class.class); result = MAPPER.readerFor(Class.class) .with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[" + q(String.class.getName()) + "]"); assertEquals(String.class, result); } @Test public void testURIAsArray() throws Exception { final ObjectReader reader = MAPPER.readerFor(URI.class); final URI value = new URI("http://foo.com"); try { reader.without(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[\""+value.toString()+"\"]"); fail("Did not throw exception for single value array when UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException e) { _verifyNoDeserFromArray(e); } _verifyMultiValueArrayFail("[\""+value.toString()+"\",\""+value.toString()+"\"]", URI.class); } @Test public void testUUIDAsArray() throws Exception { final ObjectReader reader = MAPPER.readerFor(UUID.class); final String uuidStr = "76e6d183-5f68-4afa-b94a-922c1fdb83f8"; UUID uuid = UUID.fromString(uuidStr); try { NO_UNWRAPPING_READER.forType(UUID.class) .readValue("[" + q(uuidStr) + "]"); fail("Exception was not thrown when UNWRAP_SINGLE_VALUE_ARRAYS is disabled and attempted to read a single value array as a single element"); } catch (MismatchedInputException e) { _verifyNoDeserFromArray(e); } assertEquals(uuid, reader.with(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS) .readValue("[" + q(uuidStr) + "]")); _verifyMultiValueArrayFail("[" + q(uuidStr) + "," + q(uuidStr) + "]", UUID.class); } /* /********************************************************** /* Helper methods /********************************************************** */ private void _verifyNoDeserFromArray(Exception e) { verifyException(e, "Cannot deserialize"); verifyException(e, "from Array value"); verifyException(e, "JsonToken.START_ARRAY"); } private void _verifyMultiValueArrayFail(String input, Class<?> type) throws IOException { try { UNWRAPPING_READER.forType(type).readValue(input); fail("Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled"); } catch (MismatchedInputException e) { verifyException(e, "Attempted to unwrap"); } } private static String asArray(Object value) { return "["+value+"]"; } }
BooleanBean
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/jdk8/LocalTimeTest2.java
{ "start": 167, "end": 529 }
class ____ extends TestCase { public void test_for_issue() throws Exception { VO vo1 = JSON.parseObject("{\"date\":\"20:30:55\"}", VO.class); Assert.assertEquals(20, vo1.date.getHour()); Assert.assertEquals(30, vo1.date.getMinute()); Assert.assertEquals(55, vo1.date.getSecond()); } public static
LocalTimeTest2
java
elastic__elasticsearch
libs/core/src/main/java/org/elasticsearch/core/internal/provider/EmbeddedImplClassLoader.java
{ "start": 20573, "end": 21418 }
class ____<E> implements Enumeration<E> { private final Enumeration<E>[] enumerations; private int index; CompoundEnumeration(Enumeration<E>[] enumerations) { this.enumerations = enumerations; } private boolean next() { while (index < enumerations.length) { if (enumerations[index] != null && enumerations[index].hasMoreElements()) { return true; } index++; } return false; } public boolean hasMoreElements() { return next(); } public E nextElement() { if (next() == false) { throw new NoSuchElementException(); } return enumerations[index].nextElement(); } } }
CompoundEnumeration
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/rest/ESRestTestFeatureService.java
{ "start": 1313, "end": 4889 }
class ____ implements TestFeatureService { /** * In order to migrate from version checks to cluster feature checks, * we provide synthetic features derived from versions, e.g. "gte_v8.0.0". */ private static final Pattern VERSION_FEATURE_PATTERN = Pattern.compile("gte_v(\\d+\\.\\d+\\.\\d+)"); private final ESRestTestCase.VersionFeaturesPredicate versionFeaturesPredicate; private final Collection<Set<String>> nodeFeatures; ESRestTestFeatureService(ESRestTestCase.VersionFeaturesPredicate versionFeaturesPredicate, Collection<Set<String>> nodeFeatures) { this.versionFeaturesPredicate = versionFeaturesPredicate; this.nodeFeatures = nodeFeatures; } private static <T> boolean checkCollection(Collection<T> coll, Predicate<T> pred, boolean any) { return any ? coll.stream().anyMatch(pred) : coll.isEmpty() == false && coll.stream().allMatch(pred); } @Override public boolean clusterHasFeature(String featureId, boolean canMatchAnyNode) { if (checkCollection(nodeFeatures, s -> s.contains(featureId), canMatchAnyNode)) { return true; } if (MetadataHolder.FEATURE_NAMES.contains(featureId)) { return false; // feature known but not present } // check synthetic version features (used to migrate from version checks to feature checks) Matcher matcher = VERSION_FEATURE_PATTERN.matcher(featureId); if (matcher.matches()) { Version extractedVersion = Version.fromString(matcher.group(1)); if (extractedVersion.after(Version.CURRENT)) { throw new IllegalArgumentException( Strings.format( "Cannot use a synthetic feature [%s] for a version after the current version [%s]", featureId, Version.CURRENT ) ); } if (extractedVersion.equals(Version.CURRENT)) { throw new IllegalArgumentException( Strings.format( "Cannot use a synthetic feature [%s] for the current version [%s]; " + "please define a test cluster feature alongside the corresponding code change instead", featureId, Version.CURRENT ) ); } return versionFeaturesPredicate.test(extractedVersion, canMatchAnyNode); } if (hasFeatureMetadata()) { if (isRestApiCompatibilityTest()) { // assume this is a feature that has been assumed, then removed in this version // the feature is therefore logically present, but not specified by the cluster return true; } throw new IllegalArgumentException( Strings.format( "Unknown feature %s: check the respective FeatureSpecification is provided both in module-info.java " + "as well as in META-INF/services and verify the module is loaded during tests.", featureId ) ); } return false; } private static boolean isRestApiCompatibilityTest() { return Booleans.parseBoolean(System.getProperty("tests.restCompat", "false")); } public static boolean hasFeatureMetadata() { return MetadataHolder.FEATURE_NAMES.isEmpty() == false; } private static
ESRestTestFeatureService
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/calcite/sql2rel/RelDecorrelator.java
{ "start": 122661, "end": 124055 }
class ____ implements Comparable<CorRef> { public final int uniqueKey; public final CorrelationId corr; public final int field; CorRef(CorrelationId corr, int field, int uniqueKey) { this.corr = corr; this.field = field; this.uniqueKey = uniqueKey; } @Override public String toString() { return corr.getName() + '.' + field; } @Override public int hashCode() { return Objects.hash(uniqueKey, corr, field); } @Override public boolean equals(@Nullable Object o) { return this == o || o instanceof CorRef && uniqueKey == ((CorRef) o).uniqueKey && corr == ((CorRef) o).corr && field == ((CorRef) o).field; } @Override public int compareTo(CorRef o) { int c = corr.compareTo(o.corr); if (c != 0) { return c; } c = Integer.compare(field, o.field); if (c != 0) { return c; } return Integer.compare(uniqueKey, o.uniqueKey); } public CorDef def() { return new CorDef(corr, field); } } /** A correlation and a field. */ static
CorRef
java
square__retrofit
samples/src/main/java/com/example/retrofit/JsonQueryParameters.java
{ "start": 2823, "end": 2933 }
class ____ { final String userId; Filter(String userId) { this.userId = userId; } }
Filter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-globalpolicygenerator/src/test/java/org/apache/hadoop/yarn/server/globalpolicygenerator/TestGPGPolicyFacade.java
{ "start": 3223, "end": 16270 }
class ____ { private Configuration conf; private FederationStateStore stateStore; private FederationStateStoreFacade facade; private GPGPolicyFacade policyFacade; private Set<SubClusterId> subClusterIds; private SubClusterPolicyConfiguration testConf; private static final String TEST_QUEUE = "test-queue"; public TestGPGPolicyFacade() { conf = new Configuration(); conf.setInt(YarnConfiguration.FEDERATION_CACHE_TIME_TO_LIVE_SECS, 0); subClusterIds = new HashSet<>(); subClusterIds.add(SubClusterId.newInstance("sc0")); subClusterIds.add(SubClusterId.newInstance("sc1")); subClusterIds.add(SubClusterId.newInstance("sc2")); facade = FederationStateStoreFacade.getInstance(conf); } @BeforeEach public void setUp() throws YarnException { stateStore = new MemoryFederationStateStore(); stateStore.init(conf); facade.reinitialize(stateStore, conf); policyFacade = new GPGPolicyFacade(facade, conf); WeightedLocalityPolicyManager manager = new WeightedLocalityPolicyManager(); // Add a test policy for test queue manager.setQueue(TEST_QUEUE); manager.getWeightedPolicyInfo().setAMRMPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); manager.getWeightedPolicyInfo().setRouterPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); testConf = manager.serializeConf(); stateStore.setPolicyConfiguration(SetSubClusterPolicyConfigurationRequest .newInstance(testConf)); } @AfterEach public void tearDown() throws Exception { stateStore.close(); stateStore = null; } @Test public void testGetPolicy() throws YarnException { WeightedLocalityPolicyManager manager = (WeightedLocalityPolicyManager) policyFacade .getPolicyManager(TEST_QUEUE); Assertions.assertEquals(testConf, manager.serializeConf()); } /** * Test that new policies are written into the state store. */ @Test public void testSetNewPolicy() throws YarnException { WeightedLocalityPolicyManager manager = new WeightedLocalityPolicyManager(); manager.setQueue(TEST_QUEUE + 0); manager.getWeightedPolicyInfo().setAMRMPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); manager.getWeightedPolicyInfo().setRouterPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); SubClusterPolicyConfiguration policyConf = manager.serializeConf(); policyFacade.setPolicyManager(manager); manager = (WeightedLocalityPolicyManager) policyFacade .getPolicyManager(TEST_QUEUE + 0); Assertions.assertEquals(policyConf, manager.serializeConf()); } /** * Test that overwriting policies are updated in the state store. */ @Test public void testOverwritePolicy() throws YarnException { subClusterIds.add(SubClusterId.newInstance("sc3")); WeightedLocalityPolicyManager manager = new WeightedLocalityPolicyManager(); manager.setQueue(TEST_QUEUE); manager.getWeightedPolicyInfo().setAMRMPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); manager.getWeightedPolicyInfo().setRouterPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); SubClusterPolicyConfiguration policyConf = manager.serializeConf(); policyFacade.setPolicyManager(manager); manager = (WeightedLocalityPolicyManager) policyFacade .getPolicyManager(TEST_QUEUE); Assertions.assertEquals(policyConf, manager.serializeConf()); } /** * Test that the write through cache works. */ @Test public void testWriteCache() throws YarnException { stateStore = mock(MemoryFederationStateStore.class); facade.reinitialize(stateStore, conf); when(stateStore.getPolicyConfiguration(any( GetSubClusterPolicyConfigurationRequest.class))).thenReturn( GetSubClusterPolicyConfigurationResponse.newInstance(testConf)); policyFacade = new GPGPolicyFacade(facade, conf); // Query once to fill the cache FederationPolicyManager manager = policyFacade.getPolicyManager(TEST_QUEUE); // State store should be contacted once verify(stateStore, times(1)).getPolicyConfiguration( any(GetSubClusterPolicyConfigurationRequest.class)); // If we set the same policy, the state store should be untouched policyFacade.setPolicyManager(manager); verify(stateStore, times(0)).setPolicyConfiguration( any(SetSubClusterPolicyConfigurationRequest.class)); } /** * Test that when read only is enabled, the state store is not changed. */ @Test public void testReadOnly() throws YarnException { conf.setBoolean(YarnConfiguration.GPG_POLICY_GENERATOR_READONLY, true); stateStore = mock(MemoryFederationStateStore.class); facade.reinitialize(stateStore, conf); when(stateStore.getPolicyConfiguration(any( GetSubClusterPolicyConfigurationRequest.class))).thenReturn( GetSubClusterPolicyConfigurationResponse.newInstance(testConf)); policyFacade = new GPGPolicyFacade(facade, conf); // If we set a policy, the state store should be untouched WeightedLocalityPolicyManager manager = new WeightedLocalityPolicyManager(); // Add a test policy for test queue manager.setQueue(TEST_QUEUE); manager.getWeightedPolicyInfo().setAMRMPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); manager.getWeightedPolicyInfo().setRouterPolicyWeights( GPGUtils.createUniformWeights(subClusterIds)); policyFacade.setPolicyManager(manager); verify(stateStore, times(0)).setPolicyConfiguration( any(SetSubClusterPolicyConfigurationRequest.class)); } @Test public void testGetWeightedLocalityPolicyManager() throws YarnException { stateStore = new MemoryFederationStateStore(); stateStore.init(new Configuration()); // root.a uses WeightedLocalityPolicyManager. // Step1. Prepare amRMPolicyWeights and routerPolicyWeights Map<SubClusterIdInfo, Float> amrmPolicyWeights = new HashMap<>(); amrmPolicyWeights.put(new SubClusterIdInfo("SC-1"), 0.7f); amrmPolicyWeights.put(new SubClusterIdInfo("SC-2"), 0.3f); Map<SubClusterIdInfo, Float> routerPolicyWeights = new HashMap<>(); routerPolicyWeights.put(new SubClusterIdInfo("SC-1"), 0.6f); routerPolicyWeights.put(new SubClusterIdInfo("SC-2"), 0.4f); WeightedPolicyInfo weightedPolicyInfo = new WeightedPolicyInfo(); weightedPolicyInfo.setHeadroomAlpha(1); weightedPolicyInfo.setAMRMPolicyWeights(amrmPolicyWeights); weightedPolicyInfo.setRouterPolicyWeights(routerPolicyWeights); // Step2. Set PolicyConfiguration. String policyManagerType = WeightedLocalityPolicyManager.class.getName(); SubClusterPolicyConfiguration config = SubClusterPolicyConfiguration.newInstance("root.a", policyManagerType, weightedPolicyInfo.toByteBuffer()); SetSubClusterPolicyConfigurationRequest request = SetSubClusterPolicyConfigurationRequest.newInstance(config); stateStore.setPolicyConfiguration(request); // Step3. Get FederationPolicyManager using policyFacade. facade.reinitialize(stateStore, conf); policyFacade = new GPGPolicyFacade(facade, conf); FederationPolicyManager policyManager = policyFacade.getPolicyManager("root.a"); Assertions.assertNotNull(policyManager); Assertions.assertTrue(policyManager.isSupportWeightedPolicyInfo()); WeightedPolicyInfo weightedPolicyInfo1 = policyManager.getWeightedPolicyInfo(); Assertions.assertNotNull(weightedPolicyInfo1); Assertions.assertTrue(policyManager instanceof WeightedLocalityPolicyManager); // Step4. Confirm amrmPolicyWeight is accurate. Map<SubClusterIdInfo, Float> amrmPolicyWeights1 = weightedPolicyInfo1.getAMRMPolicyWeights(); Assertions.assertNotNull(amrmPolicyWeights1); Float sc1Float = amrmPolicyWeights1.get(new SubClusterIdInfo("SC-1")); Float sc2Float = amrmPolicyWeights1.get(new SubClusterIdInfo("SC-2")); Assertions.assertEquals(0.7, sc1Float, 0.001); Assertions.assertEquals(0.3, sc2Float, 0.001); // Step5. Confirm amrmPolicyWeight is accurate. Map<SubClusterIdInfo, Float> routerPolicyWeights1 = weightedPolicyInfo1.getRouterPolicyWeights(); Assertions.assertNotNull(routerPolicyWeights1); Float sc1Float1 = routerPolicyWeights1.get(new SubClusterIdInfo("SC-1")); Float sc2Float2 = routerPolicyWeights1.get(new SubClusterIdInfo("SC-2")); Assertions.assertEquals(0.6, sc1Float1, 0.001); Assertions.assertEquals(0.4, sc2Float2, 0.001); } @Test public void testGetWeightedHomePolicyManager() throws YarnException { stateStore = new MemoryFederationStateStore(); stateStore.init(new Configuration()); // root.b uses WeightedHomePolicyManager. // Step1. Prepare routerPolicyWeights. Map<SubClusterIdInfo, Float> routerPolicyWeights = new HashMap<>(); routerPolicyWeights.put(new SubClusterIdInfo("SC-1"), 0.8f); routerPolicyWeights.put(new SubClusterIdInfo("SC-2"), 0.2f); WeightedPolicyInfo weightedPolicyInfo = new WeightedPolicyInfo(); weightedPolicyInfo.setHeadroomAlpha(1); weightedPolicyInfo.setRouterPolicyWeights(routerPolicyWeights); // Step2. Set PolicyConfiguration. String policyManagerType = WeightedHomePolicyManager.class.getName(); SubClusterPolicyConfiguration config = SubClusterPolicyConfiguration.newInstance("root.b", policyManagerType, weightedPolicyInfo.toByteBuffer()); SetSubClusterPolicyConfigurationRequest request = SetSubClusterPolicyConfigurationRequest.newInstance(config); stateStore.setPolicyConfiguration(request); // Step3. Get FederationPolicyManager using policyFacade. facade.reinitialize(stateStore, conf); policyFacade = new GPGPolicyFacade(facade, conf); FederationPolicyManager policyManager = policyFacade.getPolicyManager("root.b"); Assertions.assertNotNull(policyManager); Assertions.assertTrue(policyManager.isSupportWeightedPolicyInfo()); WeightedPolicyInfo weightedPolicyInfo1 = policyManager.getWeightedPolicyInfo(); Assertions.assertNotNull(weightedPolicyInfo1); // Step4. Confirm amrmPolicyWeight is accurate. Map<SubClusterIdInfo, Float> amrmPolicyWeights1 = weightedPolicyInfo1.getAMRMPolicyWeights(); Assertions.assertNotNull(amrmPolicyWeights1); Assertions.assertEquals(0, amrmPolicyWeights1.size()); // Step5. Confirm amrmPolicyWeight is accurate. Map<SubClusterIdInfo, Float> routerPolicyWeights1 = weightedPolicyInfo1.getRouterPolicyWeights(); Assertions.assertNotNull(routerPolicyWeights1); Float sc1Float1 = routerPolicyWeights1.get(new SubClusterIdInfo("SC-1")); Float sc2Float2 = routerPolicyWeights1.get(new SubClusterIdInfo("SC-2")); Assertions.assertEquals(0.8, sc1Float1, 0.001); Assertions.assertEquals(0.2, sc2Float2, 0.001); } @Test public void testGetUniformBroadcastPolicyManager() throws Exception { stateStore = new MemoryFederationStateStore(); stateStore.init(new Configuration()); List<String> notSupportWeightedPolicyInfos = new ArrayList<>(); notSupportWeightedPolicyInfos.add(HashBroadcastPolicyManager.class.getName()); notSupportWeightedPolicyInfos.add(UniformBroadcastPolicyManager.class.getName()); notSupportWeightedPolicyInfos.add(HomePolicyManager.class.getName()); notSupportWeightedPolicyInfos.add(RejectAllPolicyManager.class.getName()); String prefix = "org.apache.hadoop.yarn.server.federation.policies.manager."; for (String policyManagerType : notSupportWeightedPolicyInfos) { // root.c uses UniformBroadcastPolicyManager. // Step1. Prepare routerPolicyWeights. WeightedPolicyInfo weightedPolicyInfo = new WeightedPolicyInfo(); weightedPolicyInfo.setHeadroomAlpha(1); // Step2. Set PolicyConfiguration. SubClusterPolicyConfiguration config = SubClusterPolicyConfiguration.newInstance("root.c", policyManagerType, weightedPolicyInfo.toByteBuffer()); SetSubClusterPolicyConfigurationRequest request = SetSubClusterPolicyConfigurationRequest.newInstance(config); stateStore.setPolicyConfiguration(request); // Step3. Get FederationPolicyManager using policyFacade. facade.reinitialize(stateStore, conf); policyFacade = new GPGPolicyFacade(facade, conf); FederationPolicyManager policyManager = policyFacade.getPolicyManager("root.c"); Assertions.assertNotNull(policyManager); Assertions.assertFalse(policyManager.isSupportWeightedPolicyInfo()); String policyManagerTypeSimple = policyManagerType.replace(prefix, ""); // Verify that PolicyManager is initialized successfully, // but getWeightedPolicyInfo is not supported. LambdaTestUtils.intercept(NotImplementedException.class, policyManagerTypeSimple + " does not implement getWeightedPolicyInfo.", () -> policyManager.getWeightedPolicyInfo()); } } }
TestGPGPolicyFacade
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/GrpcXdsTransportFactory.java
{ "start": 1703, "end": 3291 }
class ____ implements XdsTransport { private final ManagedChannel channel; private final CallCredentials callCredentials; public GrpcXdsTransport(Bootstrapper.ServerInfo serverInfo) { this(serverInfo, null); } @VisibleForTesting public GrpcXdsTransport(ManagedChannel channel) { this(channel, null); } public GrpcXdsTransport(Bootstrapper.ServerInfo serverInfo, CallCredentials callCredentials) { String target = serverInfo.target(); ChannelCredentials channelCredentials = (ChannelCredentials) serverInfo.implSpecificConfig(); this.channel = Grpc.newChannelBuilder(target, channelCredentials) .keepAliveTime(5, TimeUnit.MINUTES) .build(); this.callCredentials = callCredentials; } @VisibleForTesting public GrpcXdsTransport(ManagedChannel channel, CallCredentials callCredentials) { this.channel = checkNotNull(channel, "channel"); this.callCredentials = callCredentials; } @Override public <ReqT, RespT> StreamingCall<ReqT, RespT> createStreamingCall( String fullMethodName, MethodDescriptor.Marshaller<ReqT> reqMarshaller, MethodDescriptor.Marshaller<RespT> respMarshaller) { Context prevContext = Context.ROOT.attach(); try { return new XdsStreamingCall<>( fullMethodName, reqMarshaller, respMarshaller, callCredentials); } finally { Context.ROOT.detach(prevContext); } } @Override public void shutdown() { channel.shutdown(); } private
GrpcXdsTransport
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_3100/Issue3150.java
{ "start": 735, "end": 1081 }
class ____ extends AfterFilter { private Category category = new Category("afterFilterCategory"); @Override public void writeAfter(Object object) { if(object instanceof Item){ this.writeKeyValue("afterFilterCategory", category); } } } public static
MyRefAfterFilter
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2300/Issue2346.java
{ "start": 1116, "end": 1692 }
class ____{ private TestEntity2 testEntity2 = new TestEntity2(); public TestEntity2 build(){ return testEntity2; } public TestEntity2Builder wwwAge(int age) { testEntity2.age = age; return this; } public TestEntity2Builder wwwName(String name) { testEntity2.name = name; return this; } } } @JSONType(builder = TestEntity3.TestEntity3Builder.class) @Getter public static
TestEntity2Builder
java
netty__netty
transport/src/main/java/io/netty/channel/socket/nio/NioServerDomainSocketChannel.java
{ "start": 6868, "end": 9591 }
class ____ extends DefaultChannelConfig { private volatile int backlog = NetUtil.SOMAXCONN; private NioDomainServerSocketChannelConfig(NioServerDomainSocketChannel channel) { super(channel, new ServerChannelRecvByteBufAllocator()); } @Override protected void autoReadCleared() { clearReadPending(); } @Override public Map<ChannelOption<?>, Object> getOptions() { List<ChannelOption<?>> options = new ArrayList<ChannelOption<?>>(); options.add(SO_BACKLOG); for (ChannelOption<?> opt : NioChannelOption.getOptions(jdkChannel())) { options.add(opt); } return getOptions(super.getOptions(), options.toArray(new ChannelOption[0])); } @SuppressWarnings("unchecked") @Override public <T> T getOption(ChannelOption<T> option) { if (option == SO_BACKLOG) { return (T) Integer.valueOf(getBacklog()); } if (option instanceof NioChannelOption) { return NioChannelOption.getOption(jdkChannel(), (NioChannelOption<T>) option); } return super.getOption(option); } @Override public <T> boolean setOption(ChannelOption<T> option, T value) { if (option == SO_BACKLOG) { validate(option, value); setBacklog((Integer) value); } else if (option instanceof NioChannelOption) { return NioChannelOption.setOption(jdkChannel(), (NioChannelOption<T>) option, value); } else { return super.setOption(option, value); } return true; } private int getBacklog() { return backlog; } private NioDomainServerSocketChannelConfig setBacklog(int backlog) { checkPositiveOrZero(backlog, "backlog"); this.backlog = backlog; return this; } private ServerSocketChannel jdkChannel() { return ((NioServerDomainSocketChannel) channel).javaChannel(); } } // Override just to to be able to call directly via unit tests. @Override protected boolean closeOnReadError(Throwable cause) { return super.closeOnReadError(cause); } @Override protected boolean doConnect( SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { throw new UnsupportedOperationException(); } @Override protected void doFinishConnect() throws Exception { throw new UnsupportedOperationException(); } }
NioDomainServerSocketChannelConfig
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
{ "start": 35535, "end": 36007 }
class ____ extends RecursiveAction { // protected abstract void realCompute() throws Throwable; // public final void compute() { // try { // realCompute(); // } catch (Throwable t) { // threadUnexpectedException(t); // } // } // } // /** // * Analog of CheckedCallable for RecursiveTask // */ // public abstract
CheckedRecursiveAction
java
apache__camel
components/camel-xmlsecurity/src/main/java/org/apache/camel/component/xmlsecurity/processor/XmlVerifierConfiguration.java
{ "start": 5373, "end": 6067 }
class ____ XmlSignatureInvalidException. If the signature value validation fails, a * XmlSignatureInvalidValueException is thrown. If a reference validation fails, a * XmlSignatureInvalidContentHashException is thrown. For more detailed information, see the JavaDoc. */ public void setValidationFailedHandler(ValidationFailedHandler validationFailedHandler) { this.validationFailedHandler = validationFailedHandler; } public Object getOutputNodeSearch() { return outputNodeSearch; } /** * Sets the output node search value for determining the node from the XML signature document which shall be set to * the output message body. The
of
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/RssComponentBuilderFactory.java
{ "start": 1337, "end": 1733 }
interface ____ { /** * RSS (camel-rss) * Poll RSS feeds. * * Category: document * Since: 2.0 * Maven coordinates: org.apache.camel:camel-rss * * @return the dsl builder */ static RssComponentBuilder rss() { return new RssComponentBuilderImpl(); } /** * Builder for the RSS component. */
RssComponentBuilderFactory
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/AuditReader.java
{ "start": 3171, "end": 4249 }
class ____ not audited. * @throws RevisionDoesNotExistException If the given date is before the first revision. * @throws IllegalStateException If the associated entity manager is closed. */ <T> T find(Class<T> cls, Object primaryKey, Date date) throws IllegalArgumentException, NotAuditedException, RevisionDoesNotExistException, IllegalStateException; /** * Find an entity by primary key on the given datetime. The datetime specifies * restricting the result to any entity created on or before the date with the highest * revision number. * * @param cls Class of the entity. * @param primaryKey Primary key of the entity. * @param datetime Datetime for which to get entity revision. * * @return The found entity instance at created on or before the specified date with the highest * revision number or null, if an entity with the id had not been created on or before the * specified date. * * @throws IllegalArgumentException if cls, primaryKey, or date is null. * @throws NotAuditedException When entities of the given
are
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/security/HttpSecurityRecorder.java
{ "start": 14400, "end": 22826 }
class ____ implements Handler<RoutingContext> { volatile HttpAuthenticator authenticator; private final boolean proactiveAuthentication; private final boolean propagateRoutingContext; private AbstractPathMatchingHttpSecurityPolicy pathMatchingPolicy; private RolesMapping rolesMapping; AuthenticationHandler(boolean proactiveAuthentication, boolean propagateRoutingContext) { this.proactiveAuthentication = proactiveAuthentication; this.propagateRoutingContext = propagateRoutingContext; } public AuthenticationHandler(boolean proactiveAuthentication) { this(proactiveAuthentication, false); } @Override public void handle(RoutingContext event) { if (authenticator == null) { // this needs to be lazily initialized as the way some identity providers are created requires that // all the build items are finished before this is called (for example Elytron identity providers use // SecurityDomain that is not ready when identity providers are ready; it's racy) authenticator = CDI.current().select(HttpAuthenticator.class).get(); } if (propagateRoutingContext) { Context context = Vertx.currentContext(); if (context != null && VertxContext.isDuplicatedContext(context)) { context.putLocal(HttpSecurityUtils.ROUTING_CONTEXT_ATTRIBUTE, event); } } //we put the authenticator into the routing context so it can be used by other systems event.put(HttpAuthenticator.class.getName(), authenticator); if (pathMatchingPolicy != null) { event.put(AbstractPathMatchingHttpSecurityPolicy.class.getName(), pathMatchingPolicy); } if (rolesMapping != null) { event.put(ROLES_MAPPING_KEY, rolesMapping); } //register the default auth failure handler if (proactiveAuthentication) { //if proactive auth is used this is the only one event.put(QuarkusHttpUser.AUTH_FAILURE_HANDLER, new DefaultAuthFailureHandler() { @Override protected void proceed(Throwable throwable) { if (!event.failed()) { //failing event makes it possible to customize response via failure handlers //QuarkusErrorHandler will send response if no other failure handler did event.fail(throwable); } } }); } else { //if using lazy auth this can be modified downstream, to control authentication behaviour event.put(QuarkusHttpUser.AUTH_FAILURE_HANDLER, new DefaultAuthFailureHandler() { @Override protected void proceed(Throwable throwable) { //we can't fail event here as request processing has already begun (e.g. in RESTEasy Reactive) //and extensions may have their ways to handle failures if (throwable instanceof AuthenticationCompletionException && throwable.getMessage() != null && LaunchMode.current() == LaunchMode.DEVELOPMENT) { event.end(throwable.getMessage()); } else { event.end(); } } }); } if (proactiveAuthentication) { authenticator .attemptAuthentication(event) .onItem().ifNull().switchTo(new Supplier<Uni<? extends SecurityIdentity>>() { @Override public Uni<? extends SecurityIdentity> get() { return authenticator.getIdentityProviderManager() .authenticate(setRoutingContextAttribute(new AnonymousAuthenticationRequest(), event)); } }) .invoke(new Consumer<SecurityIdentity>() { @Override public void accept(SecurityIdentity identity) { QuarkusHttpUser.setIdentity(identity, event); } }) .subscribe().with( new Consumer<SecurityIdentity>() { @Override public void accept(SecurityIdentity ignored) { if (event.response().ended()) { return; } event.next(); } }, new Consumer<Throwable>() { @Override public void accept(Throwable failure) { //this can be customised BiConsumer<RoutingContext, Throwable> handler = event .get(QuarkusHttpUser.AUTH_FAILURE_HANDLER); if (handler != null) { handler.accept(event, failure); } } }); } else { Uni<SecurityIdentity> lazyUser = Uni .createFrom() .nullItem() // Only attempt to authenticate if required .flatMap(n -> authenticator.attemptAuthentication(event)) .memoize() .indefinitely() .flatMap(new Function<SecurityIdentity, Uni<? extends SecurityIdentity>>() { @Override public Uni<? extends SecurityIdentity> apply(SecurityIdentity securityIdentity) { //if it is null we use the anonymous identity if (securityIdentity == null) { return authenticator.getIdentityProviderManager() .authenticate( setRoutingContextAttribute(new AnonymousAuthenticationRequest(), event)); } return Uni.createFrom().item(securityIdentity); } }).onTermination().invoke(new Functions.TriConsumer<SecurityIdentity, Throwable, Boolean>() { @Override public void accept(SecurityIdentity identity, Throwable throwable, Boolean aBoolean) { if (identity != null) { //when the result is evaluated we set the user, even if it is evaluated lazily event.setUser(new QuarkusHttpUser(identity)); } else if (throwable != null) { //handle the auth failure //this can be customised BiConsumer<RoutingContext, Throwable> handler = event .get(QuarkusHttpUser.AUTH_FAILURE_HANDLER); if (handler != null) { handler.accept(event, throwable); } } } }).memoize().indefinitely(); event.put(QuarkusHttpUser.DEFERRED_IDENTITY_KEY, lazyUser); event.next(); } } // this must happen before the router is finalized, so that
AuthenticationHandler
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLShowGrantsStatement.java
{ "start": 815, "end": 1533 }
class ____ extends SQLStatementImpl implements SQLShowStatement { protected SQLExpr user; protected SQLExpr on; @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, user); } visitor.endVisit(this); } public SQLExpr getUser() { return user; } public void setUser(SQLExpr user) { if (user != null) { user.setParent(this); } this.user = user; } public SQLExpr getOn() { return on; } public void setOn(SQLExpr x) { if (x != null) { x.setParent(this); } this.on = x; } }
SQLShowGrantsStatement
java
hibernate__hibernate-orm
hibernate-community-dialects/src/main/java/org/hibernate/community/dialect/SybaseASELegacySqlAstTranslator.java
{ "start": 2342, "end": 17201 }
class ____<T extends JdbcOperation> extends AbstractSqlAstTranslator<T> { private static final String UNION_ALL = " union all "; public SybaseASELegacySqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { super( sessionFactory, statement ); } @Override protected void visitInsertStatementOnly(InsertSelectStatement statement) { if ( statement.getConflictClause() == null || statement.getConflictClause().isDoNothing() ) { // Render plain insert statement and possibly run into unique constraint violation super.visitInsertStatementOnly( statement ); } else { visitInsertStatementEmulateMerge( statement ); } } @Override protected void renderDeleteClause(DeleteStatement statement) { appendSql( "delete " ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.DELETE ); renderDmlTargetTableExpression( statement.getTargetTable() ); if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); renderTableReferenceIdentificationVariable( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } finally { clauseStack.pop(); } } @Override protected void renderUpdateClause(UpdateStatement updateStatement) { appendSql( "update " ); final Stack<Clause> clauseStack = getClauseStack(); try { clauseStack.push( Clause.UPDATE ); renderDmlTargetTableExpression( updateStatement.getTargetTable() ); } finally { clauseStack.pop(); } } @Override protected void renderFromClauseAfterUpdateSet(UpdateStatement statement) { if ( statement.getFromClause().getRoots().isEmpty() ) { appendSql( " from " ); renderDmlTargetTableExpression( statement.getTargetTable() ); renderTableReferenceIdentificationVariable( statement.getTargetTable() ); } else { visitFromClause( statement.getFromClause() ); } } @Override protected void visitConflictClause(ConflictClause conflictClause) { if ( conflictClause != null ) { if ( conflictClause.isDoUpdate() && conflictClause.getConstraintName() != null ) { throw new IllegalQueryOperationException( "Insert conflict 'do update' clause with constraint name is not supported" ); } } } // Sybase ASE does not allow CASE expressions where all result arms contain plain parameters. // At least one result arm must provide some type context for inference, // so we cast the first result arm if we encounter this condition @Override protected void visitAnsiCaseSearchedExpression( CaseSearchedExpression caseSearchedExpression, Consumer<Expression> resultRenderer) { if ( getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters( caseSearchedExpression ) ) { final List<CaseSearchedExpression.WhenFragment> whenFragments = caseSearchedExpression.getWhenFragments(); final Expression firstResult = whenFragments.get( 0 ).getResult(); super.visitAnsiCaseSearchedExpression( caseSearchedExpression, e -> { if ( e == firstResult ) { renderCasted( e ); } else { resultRenderer.accept( e ); } } ); } else { super.visitAnsiCaseSearchedExpression( caseSearchedExpression, resultRenderer ); } } @Override protected void visitAnsiCaseSimpleExpression( CaseSimpleExpression caseSimpleExpression, Consumer<Expression> resultRenderer) { if ( getParameterRenderingMode() == SqlAstNodeRenderingMode.DEFAULT && areAllResultsParameters( caseSimpleExpression ) ) { final List<CaseSimpleExpression.WhenFragment> whenFragments = caseSimpleExpression.getWhenFragments(); final Expression firstResult = whenFragments.get( 0 ).getResult(); super.visitAnsiCaseSimpleExpression( caseSimpleExpression, e -> { if ( e == firstResult ) { renderCasted( e ); } else { resultRenderer.accept( e ); } } ); } else { super.visitAnsiCaseSimpleExpression( caseSimpleExpression, resultRenderer ); } } @Override protected boolean renderNamedTableReference(NamedTableReference tableReference, LockMode lockMode) { final String tableExpression = tableReference.getTableExpression(); if ( tableReference instanceof UnionTableReference && lockMode != LockMode.NONE && tableExpression.charAt( 0 ) == '(' ) { // SQL Server requires to push down the lock hint to the actual table names int searchIndex = 0; int unionIndex; while ( ( unionIndex = tableExpression.indexOf( UNION_ALL, searchIndex ) ) != -1 ) { append( tableExpression, searchIndex, unionIndex ); renderLockHint( lockMode ); appendSql( UNION_ALL ); searchIndex = unionIndex + UNION_ALL.length(); } append( tableExpression, searchIndex, tableExpression.length() - 1 ); renderLockHint( lockMode ); appendSql( " )" ); registerAffectedTable( tableReference ); renderTableReferenceIdentificationVariable( tableReference ); } else { super.renderNamedTableReference( tableReference, lockMode ); renderLockHint( lockMode ); } // Just always return true because SQL Server doesn't support the FOR UPDATE clause return true; } private void renderLockHint(LockMode lockMode) { append( SybaseASESqlAstTranslator.determineLockHint( lockMode, getEffectiveLockTimeout( lockMode ) ) ); } @Override protected LockStrategy determineLockingStrategy( QuerySpec querySpec, Locking.FollowOn followOnStrategy) { if ( followOnStrategy == Locking.FollowOn.FORCE ) { return LockStrategy.FOLLOW_ON; } // No need for follow on locking return LockStrategy.CLAUSE; } @Override protected void visitSqlSelections(SelectClause selectClause) { if ( supportsTopClause() ) { renderTopClause( (QuerySpec) getQueryPartStack().getCurrent(), true, false ); } super.visitSqlSelections( selectClause ); } @Override protected void renderFetchPlusOffsetExpression( Expression fetchClauseExpression, Expression offsetClauseExpression, int offset) { renderFetchPlusOffsetExpressionAsLiteral( fetchClauseExpression, offsetClauseExpression, offset ); } @Override public void visitQueryGroup(QueryGroup queryGroup) { if ( queryGroup.hasSortSpecifications() || queryGroup.hasOffsetOrFetchClause() ) { appendSql( "select " ); renderTopClause( queryGroup.getOffsetClauseExpression(), queryGroup.getFetchClauseExpression(), queryGroup.getFetchClauseType(), true, false ); appendSql( "* from (" ); renderQueryGroup( queryGroup, false ); appendSql( ") grp_(c0" ); // Sybase doesn't have implicit names for non-column select expressions, so we need to assign names final int itemCount = queryGroup.getFirstQuerySpec().getSelectClause().getSqlSelections().size(); for (int i = 1; i < itemCount; i++) { appendSql( ",c" ); appendSql( i ); } appendSql( ')' ); visitOrderBy( queryGroup.getSortSpecifications() ); } else { super.visitQueryGroup( queryGroup ); } } @Override protected void visitValuesList(List<Values> valuesList) { visitValuesListEmulateSelectUnion( valuesList ); } @Override public void visitValuesTableReference(ValuesTableReference tableReference) { append( '(' ); visitValuesListEmulateSelectUnion( tableReference.getValuesList() ); append( ')' ); renderDerivedTableReferenceIdentificationVariable( tableReference ); } @Override public void visitOffsetFetchClause(QueryPart queryPart) { assertRowsOnlyFetchClauseType( queryPart ); if ( !queryPart.isRoot() && queryPart.hasOffsetOrFetchClause() ) { if ( queryPart.getFetchClauseExpression() != null && !supportsTopClause() || queryPart.getOffsetClauseExpression() != null ) { throw new IllegalArgumentException( "Can't emulate offset fetch clause in subquery" ); } } } @Override protected void renderFetchExpression(Expression fetchExpression) { if ( supportsParameterOffsetFetchExpression() ) { super.renderFetchExpression( fetchExpression ); } else { renderExpressionAsLiteral( fetchExpression, getJdbcParameterBindings() ); } } @Override protected void renderOffsetExpression(Expression offsetExpression) { if ( supportsParameterOffsetFetchExpression() ) { super.renderOffsetExpression( offsetExpression ); } else { renderExpressionAsLiteral( offsetExpression, getJdbcParameterBindings() ); } } @Override protected void renderComparison(Expression lhs, ComparisonOperator operator, Expression rhs) { // In Sybase ASE, XMLTYPE is not "comparable", so we have to cast the two parts to varchar for this purpose final boolean isLob = isLob( lhs.getExpressionType() ); if ( isLob ) { switch ( operator ) { case EQUAL: lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); return; case NOT_EQUAL: lhs.accept( this ); appendSql( " not like " ); rhs.accept( this ); return; default: // Fall through break; } } // I think intersect is only supported in 16.0 SP3 if ( ( (SybaseASELegacyDialect) getDialect() ).isAnsiNullOn() ) { if ( isLob ) { switch ( operator ) { case DISTINCT_FROM: appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=1" ); return; case NOT_DISTINCT_FROM: appendSql( "case when " ); lhs.accept( this ); appendSql( " like " ); rhs.accept( this ); appendSql( " or " ); lhs.accept( this ); appendSql( " is null and " ); rhs.accept( this ); appendSql( " is null then 0 else 1 end=0" ); return; default: // Fall through break; } } if ( getDialect().supportsDistinctFromPredicate() ) { renderComparisonEmulateIntersect( lhs, operator, rhs ); } else { renderComparisonEmulateCase( lhs, operator, rhs ); } } else { // The ansinull setting only matters if using a parameter or literal and the eq operator according to the docs // http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc32300.1570/html/sqlug/sqlug89.htm boolean rhsNotNullPredicate = lhs instanceof Literal || isParameter( lhs ); boolean lhsNotNullPredicate = rhs instanceof Literal || isParameter( rhs ); if ( rhsNotNullPredicate || lhsNotNullPredicate ) { lhs.accept( this ); switch ( operator ) { case DISTINCT_FROM: if ( isLob ) { appendSql( " not like " ); } else { appendSql( "<>" ); } break; case NOT_DISTINCT_FROM: if ( isLob ) { appendSql( " like " ); } else { appendSql( '=' ); } break; case LESS_THAN: case GREATER_THAN: case LESS_THAN_OR_EQUAL: case GREATER_THAN_OR_EQUAL: // These operators are not affected by ansinull=off lhsNotNullPredicate = false; rhsNotNullPredicate = false; default: appendSql( operator.sqlText() ); break; } rhs.accept( this ); if ( lhsNotNullPredicate ) { appendSql( " and " ); lhs.accept( this ); appendSql( " is not null" ); } if ( rhsNotNullPredicate ) { appendSql( " and " ); rhs.accept( this ); appendSql( " is not null" ); } } else { if ( getDialect().supportsDistinctFromPredicate() ) { renderComparisonEmulateIntersect( lhs, operator, rhs ); } else { renderComparisonEmulateCase( lhs, operator, rhs ); } } } } @Override protected void renderSelectTupleComparison( List<SqlSelection> lhsExpressions, SqlTuple tuple, ComparisonOperator operator) { emulateSelectTupleComparison( lhsExpressions, tuple.getExpressions(), operator, true ); } @Override protected void renderPartitionItem(Expression expression) { if ( expression instanceof Literal ) { // Note that this depends on the SqmToSqlAstConverter to add a dummy table group appendSql( "dummy_.x" ); } else if ( expression instanceof Summarization ) { // This could theoretically be emulated by rendering all grouping variations of the query and // connect them via union all but that's probably pretty inefficient and would have to happen // on the query spec level throw new UnsupportedOperationException( "Summarization is not supported by DBMS" ); } else { expression.accept( this ); } } @Override public void visitBinaryArithmeticExpression(BinaryArithmeticExpression arithmeticExpression) { appendSql( OPEN_PARENTHESIS ); visitArithmeticOperand( arithmeticExpression.getLeftHandOperand() ); appendSql( arithmeticExpression.getOperator().getOperatorSqlTextString() ); visitArithmeticOperand( arithmeticExpression.getRightHandOperand() ); appendSql( CLOSE_PARENTHESIS ); } @Override protected String determineColumnReferenceQualifier(ColumnReference columnReference) { final DmlTargetColumnQualifierSupport qualifierSupport = getDialect().getDmlTargetColumnQualifierSupport(); final MutationStatement currentDmlStatement; final String dmlAlias; if ( qualifierSupport == DmlTargetColumnQualifierSupport.TABLE_ALIAS || ( currentDmlStatement = getCurrentDmlStatement() ) == null || ( dmlAlias = currentDmlStatement.getTargetTable().getIdentificationVariable() ) == null || !dmlAlias.equals( columnReference.getQualifier() ) ) { return columnReference.getQualifier(); } // Sybase needs a table name prefix // but not if this is a restricted union table reference subquery final QuerySpec currentQuerySpec = (QuerySpec) getQueryPartStack().getCurrent(); final List<TableGroup> roots; if ( currentQuerySpec != null && !currentQuerySpec.isRoot() && (roots = currentQuerySpec.getFromClause().getRoots()).size() == 1 && roots.get( 0 ).getPrimaryTableReference() instanceof UnionTableReference ) { return columnReference.getQualifier(); } else if ( columnReference.isColumnExpressionFormula() ) { // For formulas, we have to replace the qualifier as the alias was already rendered into the formula // This is fine for now as this is only temporary anyway until we render aliases for table references return null; } else { return getCurrentDmlStatement().getTargetTable().getTableExpression(); } } @Override protected boolean needsRowsToSkip() { return true; } @Override protected boolean needsMaxRows() { return !supportsTopClause(); } private boolean supportsTopClause() { return getDialect().getVersion().isSameOrAfter( 12, 5 ); } private boolean supportsParameterOffsetFetchExpression() { return false; } }
SybaseASELegacySqlAstTranslator
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/PromqlBaseParserBaseVisitor.java
{ "start": 409, "end": 756 }
class ____ an empty implementation of {@link PromqlBaseParserVisitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param <T> The return type of the visit operation. Use {@link Void} for * operations with no return type. */ @SuppressWarnings("CheckReturnValue") public
provides
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ConstructorInvoker_newInstance_Test.java
{ "start": 980, "end": 1415 }
class ____ { private ConstructorInvoker invoker; @BeforeEach public void setUp() { invoker = new ConstructorInvoker(); } @Test void should_create_Object_using_reflection() throws Exception { // WHEN Object o = invoker.newInstance("java.lang.Exception", new Class<?>[] { String.class }, "Hi"); // THEN then(o).asInstanceOf(THROWABLE) .hasMessage("Hi"); } }
ConstructorInvoker_newInstance_Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/ip/IpPrefix.java
{ "start": 2165, "end": 7904 }
class ____ extends EsqlScalarFunction implements OptionalArgument { public static final NamedWriteableRegistry.Entry ENTRY = new NamedWriteableRegistry.Entry(Expression.class, "IpPrefix", IpPrefix::new); // Borrowed from Lucene, rfc4291 prefix private static final byte[] IPV4_PREFIX = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1 }; private final Expression ipField; private final Expression prefixLengthV4Field; private final Expression prefixLengthV6Field; @FunctionInfo( returnType = "ip", description = "Truncates an IP to a given prefix length.", examples = @Example(file = "ip", tag = "ipPrefix") ) public IpPrefix( Source source, @Param( name = "ip", type = { "ip" }, description = "IP address of type `ip` (both IPv4 and IPv6 are supported)." ) Expression ipField, @Param( name = "prefixLengthV4", type = { "integer" }, description = "Prefix length for IPv4 addresses." ) Expression prefixLengthV4Field, @Param( name = "prefixLengthV6", type = { "integer" }, description = "Prefix length for IPv6 addresses." ) Expression prefixLengthV6Field ) { super(source, Arrays.asList(ipField, prefixLengthV4Field, prefixLengthV6Field)); this.ipField = ipField; this.prefixLengthV4Field = prefixLengthV4Field; this.prefixLengthV6Field = prefixLengthV6Field; } private IpPrefix(StreamInput in) throws IOException { this( Source.readFrom((PlanStreamInput) in), in.readNamedWriteable(Expression.class), in.readNamedWriteable(Expression.class), in.readNamedWriteable(Expression.class) ); } @Override public void writeTo(StreamOutput out) throws IOException { source().writeTo(out); out.writeNamedWriteable(ipField); out.writeNamedWriteable(prefixLengthV4Field); out.writeNamedWriteable(prefixLengthV6Field); } @Override public String getWriteableName() { return ENTRY.name; } public Expression ipField() { return ipField; } public Expression prefixLengthV4Field() { return prefixLengthV4Field; } public Expression prefixLengthV6Field() { return prefixLengthV6Field; } @Override public boolean foldable() { return Expressions.foldable(children()); } @Override public ExpressionEvaluator.Factory toEvaluator(ToEvaluator toEvaluator) { var ipEvaluatorSupplier = toEvaluator.apply(ipField); var prefixLengthV4EvaluatorSupplier = toEvaluator.apply(prefixLengthV4Field); var prefixLengthV6EvaluatorSupplier = toEvaluator.apply(prefixLengthV6Field); return new IpPrefixEvaluator.Factory( source(), ipEvaluatorSupplier, prefixLengthV4EvaluatorSupplier, prefixLengthV6EvaluatorSupplier, context -> new BytesRef(new byte[16]) ); } @Evaluator(warnExceptions = IllegalArgumentException.class) static BytesRef process( BytesRef ip, int prefixLengthV4, int prefixLengthV6, @Fixed(includeInToString = false, scope = THREAD_LOCAL) BytesRef scratch ) { if (prefixLengthV4 < 0 || prefixLengthV4 > 32) { throw new IllegalArgumentException("Prefix length v4 must be in range [0, 32], found " + prefixLengthV4); } if (prefixLengthV6 < 0 || prefixLengthV6 > 128) { throw new IllegalArgumentException("Prefix length v6 must be in range [0, 128], found " + prefixLengthV6); } boolean isIpv4 = Arrays.compareUnsigned( ip.bytes, ip.offset, ip.offset + IPV4_PREFIX.length, IPV4_PREFIX, 0, IPV4_PREFIX.length ) == 0; if (isIpv4) { makePrefix(ip, scratch, 12 + prefixLengthV4 / 8, prefixLengthV4 % 8); } else { makePrefix(ip, scratch, prefixLengthV6 / 8, prefixLengthV6 % 8); } return scratch; } private static void makePrefix(BytesRef ip, BytesRef scratch, int fullBytes, int remainingBits) { // Copy the first full bytes System.arraycopy(ip.bytes, ip.offset, scratch.bytes, 0, fullBytes); // Copy the last byte ignoring the trailing bits if (remainingBits > 0) { byte lastByteMask = (byte) (0xFF << (8 - remainingBits)); scratch.bytes[fullBytes] = (byte) (ip.bytes[ip.offset + fullBytes] & lastByteMask); } // Copy the last empty bytes if (fullBytes < 16) { Arrays.fill(scratch.bytes, fullBytes + 1, 16, (byte) 0); } } @Override public DataType dataType() { return DataType.IP; } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } return isIPAndExact(ipField, sourceText(), FIRST).and( isType(prefixLengthV4Field, dt -> dt == INTEGER, sourceText(), SECOND, "integer") ).and(isType(prefixLengthV6Field, dt -> dt == INTEGER, sourceText(), THIRD, "integer")); } @Override public Expression replaceChildren(List<Expression> newChildren) { return new IpPrefix(source(), newChildren.get(0), newChildren.get(1), newChildren.get(2)); } @Override protected NodeInfo<? extends Expression> info() { return NodeInfo.create(this, IpPrefix::new, ipField, prefixLengthV4Field, prefixLengthV6Field); } }
IpPrefix
java
apache__camel
core/camel-base-engine/src/main/java/org/apache/camel/impl/engine/CamelInternalProcessor.java
{ "start": 43972, "end": 44910 }
class ____ implements CamelInternalProcessorAdvice<Object> { private static final Logger LOG = LoggerFactory.getLogger(DelayerAdvice.class); private final long delay; public DelayerAdvice(long delay) { this.delay = delay; } @Override public Object before(Exchange exchange) throws Exception { try { LOG.trace("Sleeping for: {} millis", delay); Thread.sleep(delay); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw e; } return null; } @Override public void after(Exchange exchange, Object data) throws Exception { // noop } @Override public boolean hasState() { return false; } } /** * Advice for tracing */ public static
DelayerAdvice
java
quarkusio__quarkus
extensions/hibernate-reactive/deployment/src/test/java/io/quarkus/hibernate/reactive/multiplepersistenceunits/model/config/user/User.java
{ "start": 265, "end": 774 }
class ____ { private long id; private String name; public User() { } public User(String name) { this.name = name; } @Id @GeneratedValue public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User:" + name; } }
User
java
grpc__grpc-java
rls/src/main/java/io/grpc/rls/LbPolicyConfiguration.java
{ "start": 1749, "end": 3567 }
class ____ { private final RouteLookupConfig routeLookupConfig; @Nullable private final Map<String, ?> routeLookupChannelServiceConfig; private final ChildLoadBalancingPolicy policy; LbPolicyConfiguration( RouteLookupConfig routeLookupConfig, @Nullable Map<String, ?> routeLookupChannelServiceConfig, ChildLoadBalancingPolicy policy) { this.routeLookupConfig = checkNotNull(routeLookupConfig, "routeLookupConfig"); this.routeLookupChannelServiceConfig = routeLookupChannelServiceConfig; this.policy = checkNotNull(policy, "policy"); } RouteLookupConfig getRouteLookupConfig() { return routeLookupConfig; } @Nullable Map<String, ?> getRouteLookupChannelServiceConfig() { return routeLookupChannelServiceConfig; } ChildLoadBalancingPolicy getLoadBalancingPolicy() { return policy; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LbPolicyConfiguration that = (LbPolicyConfiguration) o; return Objects.equals(routeLookupConfig, that.routeLookupConfig) && Objects.equals(routeLookupChannelServiceConfig, that.routeLookupChannelServiceConfig) && Objects.equals(policy, that.policy); } @Override public int hashCode() { return Objects.hash(routeLookupConfig, routeLookupChannelServiceConfig, policy); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("routeLookupConfig", routeLookupConfig) .add("routeLookupChannelServiceConfig", routeLookupChannelServiceConfig) .add("policy", policy) .toString(); } /** ChildLoadBalancingPolicy is an elected child policy to delegate requests. */ static final
LbPolicyConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/function/array/ArrayViaArgumentReturnTypeResolver.java
{ "start": 1038, "end": 2527 }
class ____ implements FunctionReturnTypeResolver { public static final FunctionReturnTypeResolver DEFAULT_INSTANCE = new ArrayViaArgumentReturnTypeResolver( 0 ); private final int arrayIndex; public ArrayViaArgumentReturnTypeResolver(int arrayIndex) { this.arrayIndex = arrayIndex; } @Override public ReturnableType<?> resolveFunctionReturnType( ReturnableType<?> impliedType, @Nullable SqmToSqlAstConverter converter, List<? extends SqmTypedNode<?>> arguments, TypeConfiguration typeConfiguration) { final MappingModelExpressible<?> inferredType = converter == null ? null : converter.resolveFunctionImpliedReturnType(); if ( inferredType != null ) { if ( inferredType instanceof ReturnableType<?> returnableType ) { return returnableType; } else if ( inferredType instanceof BasicValuedMapping basicValuedMapping ) { return (ReturnableType<?>) basicValuedMapping.getJdbcMapping(); } } if ( impliedType != null ) { return impliedType; } final SqmExpressible<?> expressible = arguments.get( arrayIndex ).getExpressible(); final DomainType<?> type; if ( expressible != null && ( type = expressible.getSqmType() ) instanceof BasicPluralType<?, ?> ) { return (ReturnableType<?>) type; } return null; } @Override public BasicValuedMapping resolveFunctionReturnType( Supplier<BasicValuedMapping> impliedTypeAccess, List<? extends SqlAstNode> arguments) { return null; } }
ArrayViaArgumentReturnTypeResolver
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/xml/CounterListener.java
{ "start": 294, "end": 697 }
class ____ { public static int insert; public static int update; public static int delete; @PrePersist public void increaseInsert(Object object) { insert++; } @PreUpdate public void increaseUpdate(Object object) { update++; } @PreRemove public void increaseDelete(Object object) { delete++; } public static void reset() { insert = 0; update = 0; delete = 0; } }
CounterListener
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/action/ScriptCondition.java
{ "start": 2025, "end": 6001 }
class ____ { private static Logger LOGGER = StatusLogger.getLogger(); private final AbstractScript script; private final Configuration configuration; /** * Constructs a new ScriptCondition. * * @param script the script that can select files to delete * @param configuration configuration containing the StrSubstitutor passed to the script */ public ScriptCondition(final AbstractScript script, final Configuration configuration) { this.script = Objects.requireNonNull(script, "script"); this.configuration = Objects.requireNonNull(configuration, "configuration"); } /** * Executes the script * * @param basePath base directory for files to delete * @param candidates a list of paths, that can be deleted by the script * @return a list of paths selected to delete by the script execution */ @SuppressWarnings("unchecked") public List<PathWithAttributes> selectFilesToDelete( final Path basePath, final List<PathWithAttributes> candidates) { final SimpleBindings bindings = new SimpleBindings(); bindings.put("basePath", basePath); bindings.put("pathList", candidates); bindings.putAll(configuration.getProperties()); bindings.put("configuration", configuration); bindings.put("substitutor", configuration.getStrSubstitutor()); bindings.put("statusLogger", LOGGER); final Object object = configuration.getScriptManager().execute(script.getId(), bindings); return (List<PathWithAttributes>) object; } /** * Creates the ScriptCondition. * * @param script The script to run. This may be a {@link org.apache.logging.log4j.core.script.Script}, a {@link ScriptFile} or a {@link ScriptRef}. The * script must return a {@code List<PathWithAttributes>}. When the script is executed, it is provided the * following bindings: * <ul> * <li>basePath - the directory from where the {@link DeleteAction Delete} action started scanning for * files to delete. Can be used to relativize the paths in the pathList.</li> * <li>pathList - a {@code java.util.List} containing {@link org.apache.logging.log4j.core.appender.rolling.action.PathWithAttributes} objects. (The script is * free to modify and return this list.)</li> * <li>substitutor - a {@link org.apache.logging.log4j.core.lookup.StrSubstitutor} that can be used to look up variables embedded in the base * dir or other properties</li> * <li>statusLogger - the {@link StatusLogger} that can be used to log events during script execution</li> * <li>any properties declared in the configuration</li> * </ul> * @param configuration the configuration * @return A ScriptCondition. */ @PluginFactory public static ScriptCondition createCondition( @PluginElement("Script") final AbstractScript script, @PluginConfiguration final Configuration configuration) { if (script == null) { LOGGER.error("A Script, ScriptFile or ScriptRef element must be provided for this ScriptCondition"); return null; } if (configuration.getScriptManager() == null) { LOGGER.error("Script support is not enabled"); return null; } if (script instanceof ScriptRef) { if (configuration.getScriptManager().getScript(script.getId()) == null) { LOGGER.error("ScriptCondition: No script with name {} has been declared.", script.getId()); return null; } } else { if (!configuration.getScriptManager().addScript(script)) { return null; } } return new ScriptCondition(script, configuration); } }
ScriptCondition
java
redisson__redisson
redisson-micronaut/redisson-micronaut-20/src/main/java/org/redisson/micronaut/RedissonFactory.java
{ "start": 1388, "end": 3353 }
class ____ { @Requires(beans = Config.class) @Singleton @Bean(preDestroy = "shutdown") public RedissonClient redisson(Config config) { return Redisson.create(config); } @EachBean(RedissonCacheConfiguration.class) public RedissonSyncCache cache(@Parameter RedissonCacheConfiguration configuration, RedissonClient redisson, ConversionService conversionService, @Named(TaskExecutors.IO) ExecutorService executorService) { if (configuration.getExpireAfterAccess().toMillis() != 0 || configuration.getExpireAfterWrite().toMillis() != 0 || configuration.getMaxSize() != 0) { RMapCache<Object, Object> mapCache = redisson.getMapCache(configuration.getMapCacheOptions()); return new RedissonSyncCache(conversionService, mapCache, mapCache, executorService, configuration); } RMap<Object, Object> map = redisson.getMap(configuration.getMapOptions()); return new RedissonSyncCache(conversionService, null, map, executorService, configuration); } @EachBean(RedissonCacheNativeConfiguration.class) public RedissonSyncCache cache(@Parameter RedissonCacheNativeConfiguration configuration, RedissonClient redisson, ConversionService conversionService, @Named(TaskExecutors.IO) ExecutorService executorService) { RMapCache<Object, Object> mapCache = null; RMapCacheNative<Object, Object> map = redisson.getMapCacheNative(configuration.getMapOptions()); if (configuration.getExpireAfterWrite().toMillis() != 0) { mapCache = new MapCacheNativeWrapper<>(map); } return new RedissonSyncCache(conversionService, mapCache, map, executorService, configuration); } }
RedissonFactory
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingDefaultTest.java
{ "start": 6667, "end": 7081 }
class ____ { void m(int i) { // BUG: Diagnostic contains: switch (i) { case 1 -> {} case 2 -> {} } } } """) .doTest(); } @Test public void arrowSwitchNegative() { compilationHelper .addSourceLines( "Test.java", """
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/StateWithoutExecutionGraphTest.java
{ "start": 3971, "end": 4287 }
class ____ extends StateWithoutExecutionGraph { TestingStateWithoutExecutionGraph(Context context, Logger logger) { super(context, logger); } @Override public JobStatus getJobStatus() { return null; } } }
TestingStateWithoutExecutionGraph
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/openshiftai/OpenShiftAiService.java
{ "start": 16728, "end": 18697 }
class ____ { public static InferenceServiceConfiguration get() { return CONFIGURATION.getOrCompute(); } private static final LazyInitializable<InferenceServiceConfiguration, RuntimeException> CONFIGURATION = new LazyInitializable<>( () -> { var configurationMap = new HashMap<String, SettingsConfiguration>(); configurationMap.put( URL, new SettingsConfiguration.Builder(SUPPORTED_TASK_TYPES).setDescription("The URL endpoint to use for the requests.") .setLabel("URL") .setRequired(true) .setSensitive(false) .setUpdatable(false) .setType(SettingsConfigurationFieldType.STRING) .build() ); configurationMap.put( MODEL_ID, new SettingsConfiguration.Builder(SUPPORTED_TASK_TYPES).setDescription( "The name of the model to use for the inference task." ) .setLabel("Model ID") .setRequired(false) .setSensitive(false) .setUpdatable(false) .setType(SettingsConfigurationFieldType.STRING) .build() ); configurationMap.putAll(DefaultSecretSettings.toSettingsConfiguration(SUPPORTED_TASK_TYPES)); configurationMap.putAll(RateLimitSettings.toSettingsConfiguration(SUPPORTED_TASK_TYPES)); return new InferenceServiceConfiguration.Builder().setService(NAME) .setName(SERVICE_NAME) .setTaskTypes(SUPPORTED_TASK_TYPES) .setConfigurations(configurationMap) .build(); } ); } }
Configuration
java
apache__flink
flink-table/flink-table-code-splitter/src/main/java/org/apache/flink/table/codesplit/BlockStatementGrouper.java
{ "start": 5052, "end": 11914 }
class ____ { // Needs to be an ordered map, so that we later apply the innermost nested // groups/transformations first and work on the results of such extractions with outer // groups/transformations. private final Map<String, List<LocalGroupElement>> groups = new LinkedHashMap<>(); private final long maxMethodLength; private final String parameters; private int counter = 0; private BlockStatementGrouperVisitor(long maxMethodLength, String parameters) { this.maxMethodLength = maxMethodLength; this.parameters = parameters; } public void visitStatement(StatementContext ctx, String context) { if (ctx.getChildCount() == 0) { return; } // For these statements here we want to process all "branches" separately, for example // TRUE and FALSE branch of IF/ELSE block. // each statement can be rewritten and extracted. if (ctx.WHILE() != null || ctx.IF() != null || ctx.ELSE() != null) { for (StatementContext statement : ctx.statement()) { if (shouldExtract(statement)) { String localContext = String.format("%s_%d", context, counter++); groupBlock(statement, localContext); } } } else { // The block did not start from IF/ELSE/WHILE statement if (shouldExtract(ctx)) { groupBlock(ctx, context); } } } // Group continuous block of statements together. If Statement is an IF/ELSE/WHILE, // its body can be further grouped by recursive call to visitStatement method. private void groupBlock(StatementContext ctx, String context) { int localGroupCodeLength = 0; List<LocalGroupElement> localGroup = new ArrayList<>(); for (BlockStatementContext bsc : ctx.block().blockStatement()) { StatementContext statement = bsc.statement(); if (statement.IF() != null || statement.ELSE() != null || statement.WHILE() != null) { String localContext = context + "_rewriteGroup" + this.counter++; visitStatement(statement, localContext); localGroup.add(new RewriteContextGroupElement(statement)); // new method call length to the localGroupCodeLength. The "3" contains two // brackets for parameters and semicolon at the end of method call localGroupCodeLength += 3 + localContext.length() + parameters.length(); } else { if (localGroupCodeLength + 1 + bsc.getText().length() <= maxMethodLength) { localGroup.add(new ContextGroupElement(bsc)); localGroupCodeLength += bsc.getText().length(); } else { if (addLocalGroup(localGroup, context)) { localGroup = new ArrayList<>(); localGroupCodeLength = 0; } localGroupCodeLength += bsc.getText().length(); localGroup.add(new ContextGroupElement(bsc)); } } } // Groups that have only one statement that is "single line statement" such as // "a[2] += b[2];" will not be extracted. addLocalGroup(localGroup, context); } private boolean addLocalGroup(List<LocalGroupElement> localGroup, String context) { if (localGroup.size() > 1 || (localGroup.size() == 1 && canGroupAsSingleStatement(localGroup.get(0).getContext()))) { String localContext = context + "_rewriteGroup" + this.counter++; groups.put(localContext, localGroup); return true; } return false; } private boolean canGroupAsSingleStatement(ParserRuleContext context) { StatementContext statement; if (context instanceof StatementContext) { statement = (StatementContext) context; } else if (context instanceof BlockStatementContext) { statement = ((BlockStatementContext) context).statement(); } else { return false; } return statement != null && (statement.IF() != null || statement.ELSE() != null || statement.WHILE() != null); } private boolean shouldExtract(StatementContext ctx) { return ctx != null && ctx.block() != null && ctx.block().blockStatement() != null // if there is only one statement in the block it's useless to extract // it into a separate function && ctx.block().blockStatement().size() > 1 // should not extract blocks with return statements && getNumOfReturnOrJumpStatements(ctx.block()) == 0; } private int getNumOfReturnOrJumpStatements(ParserRuleContext ctx) { ReturnAndJumpCounter counter = new ReturnAndJumpCounter(); counter.visit(ctx); return counter.getCounter(); } private Map<String, List<String>> rewrite(TokenStreamRewriter rewriter) { Map<String, List<String>> groupStrings = CollectionUtil.newHashMapWithExpectedSize(groups.size()); for (Entry<String, List<LocalGroupElement>> group : groups.entrySet()) { List<LocalGroupElement> groupElements = group.getValue(); List<String> collectedStringGroups = groupElements.stream() .map(el -> el.getBody(rewriter)) .collect(Collectors.toList()); rewriter.replace( groupElements.get(0).getStart(), groupElements.get(groupElements.size() - 1).getStop(), group.getKey() + "(" + this.parameters + ");"); groupStrings.put(group.getKey(), collectedStringGroups); } return groupStrings; } } /** * Represents an extracted statement, it boundaries (start and stop token) and its String * representation. For example single line statement like: int a = 3; or block statement like * IF/ELSE/WHILE bodies. */ private
BlockStatementGrouperVisitor
java
apache__kafka
clients/src/test/java/org/apache/kafka/common/security/oauthbearer/internals/secured/RefreshingHttpsJwksTest.java
{ "start": 9748, "end": 12917 }
class ____ implements MockTime.Listener { private final MockTime time; private final TreeMap<Long, List<AbstractMap.SimpleEntry<Long, KafkaFutureImpl<Long>>>> waiters = new TreeMap<>(); public MockExecutorService(MockTime time) { this.time = time; time.addListener(this); } /** * The actual execution and rescheduling logic. Check all internal tasks to see if any one reaches its next * execution point, call it and optionally reschedule it if it has a specified period. */ @Override public synchronized void onTimeUpdated() { long timeMs = time.milliseconds(); while (true) { Map.Entry<Long, List<AbstractMap.SimpleEntry<Long, KafkaFutureImpl<Long>>>> entry = waiters.firstEntry(); if ((entry == null) || (entry.getKey() > timeMs)) { break; } for (AbstractMap.SimpleEntry<Long, KafkaFutureImpl<Long>> pair : entry.getValue()) { pair.getValue().complete(timeMs); if (pair.getKey() != null) { addWaiter(entry.getKey() + pair.getKey(), pair.getKey(), pair.getValue()); } } waiters.remove(entry.getKey()); } } /** * Add a task with `delayMs` and optional period to the internal waiter. * When `delayMs` < 0, we immediately complete the waiter. Otherwise, we add the task metadata to the waiter and * onTimeUpdated will take care of execute and reschedule it when it reaches its scheduled timestamp. * * @param delayMs Delay time in ms. * @param period Scheduling period, null means no periodic. * @param waiter A wrapper over a callable function. */ private synchronized void addWaiter(long delayMs, Long period, KafkaFutureImpl<Long> waiter) { long timeMs = time.milliseconds(); if (delayMs <= 0) { waiter.complete(timeMs); } else { long triggerTimeMs = timeMs + delayMs; List<AbstractMap.SimpleEntry<Long, KafkaFutureImpl<Long>>> futures = waiters.computeIfAbsent(triggerTimeMs, k -> new ArrayList<>()); futures.add(new AbstractMap.SimpleEntry<>(period, waiter)); } } /** * Internal utility function for periodic or one time refreshes. * * @param period null indicates one time refresh, otherwise it is periodic. */ public <T> ScheduledFuture<T> schedule(final Callable<T> callable, long delayMs, Long period) { KafkaFutureImpl<Long> waiter = new KafkaFutureImpl<>(); waiter.thenApply(now -> { try { callable.call(); } catch (Throwable e) { e.printStackTrace(); } return null; }); addWaiter(delayMs, period, waiter); return null; } } }
MockExecutorService
java
google__guava
guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
{ "start": 5228, "end": 8793 }
class ____ { /** * Returns a {@link Scheduler} that schedules the task using the {@link * ScheduledExecutorService#scheduleWithFixedDelay} method. * * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one execution and the commencement of the * next * @since 28.0 (but only since 33.4.0 in the Android flavor) */ public static Scheduler newFixedDelaySchedule(Duration initialDelay, Duration delay) { return newFixedDelaySchedule( toNanosSaturated(initialDelay), toNanosSaturated(delay), NANOSECONDS); } /** * Returns a {@link Scheduler} that schedules the task using the {@link * ScheduledExecutorService#scheduleWithFixedDelay} method. * * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one execution and the commencement of the * next * @param unit the time unit of the initialDelay and delay parameters */ @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static Scheduler newFixedDelaySchedule(long initialDelay, long delay, TimeUnit unit) { checkNotNull(unit); checkArgument(delay > 0, "delay must be > 0, found %s", delay); return new Scheduler() { @Override public Cancellable schedule( AbstractService service, ScheduledExecutorService executor, Runnable task) { return new FutureAsCancellable( executor.scheduleWithFixedDelay(task, initialDelay, delay, unit)); } }; } /** * Returns a {@link Scheduler} that schedules the task using the {@link * ScheduledExecutorService#scheduleAtFixedRate} method. * * @param initialDelay the time to delay first execution * @param period the period between successive executions of the task * @since 28.0 (but only since 33.4.0 in the Android flavor) */ public static Scheduler newFixedRateSchedule(Duration initialDelay, Duration period) { return newFixedRateSchedule( toNanosSaturated(initialDelay), toNanosSaturated(period), NANOSECONDS); } /** * Returns a {@link Scheduler} that schedules the task using the {@link * ScheduledExecutorService#scheduleAtFixedRate} method. * * @param initialDelay the time to delay first execution * @param period the period between successive executions of the task * @param unit the time unit of the initialDelay and period parameters */ @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static Scheduler newFixedRateSchedule(long initialDelay, long period, TimeUnit unit) { checkNotNull(unit); checkArgument(period > 0, "period must be > 0, found %s", period); return new Scheduler() { @Override public Cancellable schedule( AbstractService service, ScheduledExecutorService executor, Runnable task) { return new FutureAsCancellable( executor.scheduleAtFixedRate(task, initialDelay, period, unit)); } }; } /** Schedules the task to run on the provided executor on behalf of the service. */ abstract Cancellable schedule( AbstractService service, ScheduledExecutorService executor, Runnable runnable); private Scheduler() {} } /* use AbstractService for state management */ private final AbstractService delegate = new ServiceDelegate(); @WeakOuter private final
Scheduler
java
quarkusio__quarkus
extensions/smallrye-openapi/deployment/src/test/java/io/quarkus/smallrye/openapi/test/jaxrs/AutoAddSecurityDisabledTestCase.java
{ "start": 401, "end": 1165 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(OpenApiResource.class, ResourceBean.class) .addAsResource( new StringAsset("quarkus.smallrye-openapi.auto-add-security=false\n"), "application.properties")); @Test void testAutoSecurityRequirement() { RestAssured.given().header("Accept", "application/json") .when() .get("/q/openapi") .then() .log().ifValidationFails() .body("components", not(hasKey(equalTo("securitySchemes")))); } }
AutoAddSecurityDisabledTestCase
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/inheritance/classrolesallowed/ClassRolesAllowedSubResourceWithoutPath.java
{ "start": 148, "end": 466 }
class ____ { private final String subResourcePath; public ClassRolesAllowedSubResourceWithoutPath(String subResourcePath) { this.subResourcePath = subResourcePath; } @POST public String post(JsonObject array) { return subResourcePath; } }
ClassRolesAllowedSubResourceWithoutPath
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/util/WhatWgUrlParser.java
{ "start": 23916, "end": 59582 }
enum ____ { SCHEME_START { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is an ASCII alpha, append c, lowercased, to buffer, and set state to scheme state. if (isAsciiAlpha(c)) { p.append(p.openCurlyBracketCount == 0 ? Character.toLowerCase((char) c) : c); p.setState(SCHEME); } // EXTRA: if c is '{', append to buffer and continue as SCHEME else if (c == '{') { p.openCurlyBracketCount++; p.append(c); p.setState(SCHEME); } // Otherwise, if state override is not given, // set state to no scheme state and decrease pointer by 1. else if (p.stateOverride == null) { p.setState(NO_SCHEME); p.pointer--; } // Otherwise, return failure. else { p.failure(null); } } }, SCHEME { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is an ASCII alphanumeric, U+002B (+), U+002D (-), or U+002E (.), append c, lowercased, to buffer. if (isAsciiAlphaNumeric(c) || (c == '+' || c == '-' || c == '.')) { p.append(p.openCurlyBracketCount == 0 ? Character.toLowerCase((char) c) : c); } // Otherwise, if c is U+003A (:), then: else if (c == ':') { // If state override is given, then: if (p.stateOverride != null) { boolean urlSpecialScheme = url.isSpecial(); String bufferString = p.buffer.toString(); boolean bufferSpecialScheme = isSpecialScheme(bufferString); // If url’s scheme is a special scheme and buffer is not a special scheme, then return. if (urlSpecialScheme && !bufferSpecialScheme) { return; } // If url’s scheme is not a special scheme and buffer is a special scheme, then return. if (!urlSpecialScheme && bufferSpecialScheme) { return; } // If url includes credentials or has a non-null port, and buffer is "file", then return. if ((url.includesCredentials() || url.port() != null) && "file".equals(bufferString)) { return; } // If url’s scheme is "file" and its host is an empty host, then return. if ("file".equals(url.scheme()) && (url.host() == null || url.host() == EmptyHost.INSTANCE)) { return; } } // Set url’s scheme to buffer. url.scheme = p.buffer.toString(); // If state override is given, then: if (p.stateOverride != null) { // If url’s port is url’s scheme’s default port, then set url’s port to null. if (url.port instanceof IntPort intPort && intPort.value() == defaultPort(url.scheme)) { url.port = null; // Return. p.stopMainLoop = true; return; } } // Set buffer to the empty string. p.emptyBuffer(); // If url’s scheme is "file", then: if (url.scheme.equals("file")) { // If remaining does not start with "//", // special-scheme-missing-following-solidus validation error. if (p.validate() && (p.remaining(0) != '/' || p.remaining(1) != '/')) { p.validationError("\"file\" scheme not followed by \"//\"."); } // Set state to file state. p.setState(FILE); } // Otherwise, if url is special, base is non-null, and base’s scheme is url’s scheme: else if (url.isSpecial() && p.base != null && p.base.scheme().equals(url.scheme)) { // Assert: base is special (and therefore does not have an opaque path). Assert.state(!p.base.path().isOpaque(), "Opaque path not expected"); // Set state to special relative or authority state. p.setState(SPECIAL_RELATIVE_OR_AUTHORITY); } // Otherwise, if url is special, set state to special authority slashes state. else if (url.isSpecial()) { p.setState(SPECIAL_AUTHORITY_SLASHES); } // Otherwise, if remaining starts with an U+002F (/), // set state to path or authority state and increase pointer by 1. else if (p.remaining(0) == '/') { p.setState(PATH_OR_AUTHORITY); p.pointer++; } // Otherwise, set url’s path to the empty string and set state to opaque path state. else { url.path = new PathSegment(""); p.setState(OPAQUE_PATH); } } // EXTRA: if c is within URI variable, keep appending else if (p.processCurlyBrackets(c)) { p.append(c); } // Otherwise, if state override is not given, set buffer to the empty string, // state to no scheme state, and start over (from the first code point in input). else if (p.stateOverride == null) { p.emptyBuffer(); p.setState(NO_SCHEME); p.pointer = -1; } // Otherwise, return failure. else { p.failure(null); } } }, NO_SCHEME { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If base is null, or base has an opaque path and c is not U+0023 (#), // missing-scheme-non-relative-URL validation error, return failure. if (p.base == null || p.base.path().isOpaque() && c != '#') { p.failure("The input is missing a scheme, because it does not begin with an ASCII alpha \"" + (c != EOF ? Character.toString(c) : "") + "\", and no base URL was provided."); } // Otherwise, if base has an opaque path and c is U+0023 (#), // set url’s scheme to base’s scheme, url’s path to base’s path, // url’s query to base’s query, url’s fragment to the empty string, // and set state to fragment state. else if (p.base.path().isOpaque() && c == '#') { url.scheme = p.base.scheme(); url.path = p.base.path(); url.query = p.base.query; url.fragment = new StringBuilder(); p.setState(FRAGMENT); } // Otherwise, if base’s scheme is not "file", // set state to relative state and decrease pointer by 1. else if (!"file".equals(p.base.scheme())) { p.setState(RELATIVE); p.pointer--; } // Otherwise, set state to file state and decrease pointer by 1. else { p.setState(FILE); p.pointer--; } } }, SPECIAL_RELATIVE_OR_AUTHORITY { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+002F (/) and remaining starts with U+002F (/), // then set state to special authority ignore slashes state and // increase pointer by 1. if (c == '/' && p.remaining(0) == '/') { p.setState(SPECIAL_AUTHORITY_IGNORE_SLASHES); p.pointer++; } // Otherwise, special-scheme-missing-following-solidus validation error, // set state to relative state and decrease pointer by 1. else { if (p.validate()) { p.validationError("The input’s scheme is not followed by \"//\"."); } p.setState(RELATIVE); p.pointer--; } } }, PATH_OR_AUTHORITY { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+002F (/), then set state to authority state. if (c == '/') { p.setState(AUTHORITY); } // Otherwise, set state to path state, and decrease pointer by 1. else { p.setState(PATH); p.pointer--; } } }, RELATIVE { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // Assert: base’s scheme is not "file". Assert.state(p.base != null && !"file".equals(p.base.scheme()), "Base scheme not provided or supported"); // Set url’s scheme to base’s scheme. url.scheme = p.base.scheme; // If c is U+002F (/), then set state to relative slash state. if (c == '/') { // EXTRA : append '/' to let the path segment start with / p.append('/'); p.setState(RELATIVE_SLASH); } // Otherwise, if url is special and c is U+005C (\), // invalid-reverse-solidus validation error, set state to relative slash state. else if (url.isSpecial() && c == '\\') { if (p.validate()) { p.validationError("URL uses \\ instead of /."); } // EXTRA : append '/' to let the path segment start with / p.append('/'); p.setState(RELATIVE_SLASH); } // Otherwise else { // Set url’s username to base’s username, url’s password to base’s password, // url’s host to base’s host, url’s port to base’s port, // url’s path to a clone of base’s path, and url’s query to base’s query. url.username = ((p.base.username != null) ? new StringBuilder(p.base.username) : null); url.password = ((p.base.password != null) ? new StringBuilder(p.base.password) : null); url.host = p.base.host(); url.port = p.base.port(); url.path = p.base.path().clone(); url.query = p.base.query; // If c is U+003F (?), then set url’s query to the empty string, and state to query state. if (c == '?') { url.query = new StringBuilder(); p.setState(QUERY); } // Otherwise, if c is U+0023 (#), set url’s fragment to the empty string and state to fragment state. else if (c == '#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } // Otherwise, if c is not the EOF code point: else if (c != EOF) { // Set url’s query to null. url.query = null; // Shorten url’s path. url.shortenPath(); // Set state to path state and decrease pointer by 1. p.setState(PATH); p.pointer--; } } } }, RELATIVE_SLASH { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If url is special and c is U+002F (/) or U+005C (\), then: if (url.isSpecial() && (c == '/' || c == '\\')) { // If c is U+005C (\), invalid-reverse-solidus validation error. if (p.validate() && c == '\\') { p.validationError("URL uses \\ instead of /."); } // Set state to special authority ignore slashes state. p.setState(SPECIAL_AUTHORITY_IGNORE_SLASHES); } // Otherwise, if c is U+002F (/), then set state to authority state. else if (c == '/') { // EXTRA: empty buffer to remove appended slash, since this is not a path p.emptyBuffer(); p.setState(AUTHORITY); } // Otherwise, set url’s username to base’s username, url’s password to base’s password, // url’s host to base’s host, url’s port to base’s port, state to path state, // and then, decrease pointer by 1. else { Assert.state(p.base != null, "No base URL available"); url.username = (p.base.username != null) ? new StringBuilder(p.base.username) : null; url.password = (p.base.password != null) ? new StringBuilder(p.base.password) : null; url.host = p.base.host(); url.port = p.base.port(); p.setState(PATH); p.pointer--; } } }, SPECIAL_AUTHORITY_SLASHES { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+002F (/) and remaining starts with U+002F (/), // then set state to special authority ignore slashes state and // increase pointer by 1. if (c == '/' && p.remaining(0) == '/') { p.setState(SPECIAL_AUTHORITY_IGNORE_SLASHES); p.pointer++; } // Otherwise, special-scheme-missing-following-solidus validation error, // set state to special authority ignore slashes state and decrease pointer by 1. else { if (p.validate()) { p.validationError("Scheme \"" + url.scheme + "\" not followed by \"//\"."); } p.setState(SPECIAL_AUTHORITY_IGNORE_SLASHES); p.pointer--; } } }, SPECIAL_AUTHORITY_IGNORE_SLASHES { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is neither U+002F (/) nor U+005C (\), // then set state to authority state and decrease pointer by 1. if (c != '/' && c != '\\') { p.setState(AUTHORITY); p.pointer--; } // Otherwise, special-scheme-missing-following-solidus validation error. else { if (p.validate()) { p.validationError("Scheme \"" + url.scheme + "\" not followed by \"//\"."); } } } }, AUTHORITY { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+0040 (@), then: if (c == '@') { // Invalid-credentials validation error. if (p.validate()) { p.validationError("Invalid credentials"); } // If atSignSeen is true, then prepend "%40" to buffer. if (p.atSignSeen) { p.prepend("%40"); } // Set atSignSeen to true. p.atSignSeen = true; int bufferLen = p.buffer.length(); // For each codePoint in buffer: for (int i = 0; i < bufferLen; i++) { int codePoint = p.buffer.codePointAt(i); // If codePoint is U+003A (:) and passwordTokenSeen is false, // then set passwordTokenSeen to true and continue. if (codePoint == ':' && !p.passwordTokenSeen) { p.passwordTokenSeen = true; continue; } // Let encodedCodePoints be the result of running UTF-8 percent-encode codePoint // using the userinfo percent-encode set. String encodedCodePoints = p.percentEncode(codePoint, WhatWgUrlParser::userinfoPercentEncodeSet); // If passwordTokenSeen is true, then append encodedCodePoints to url’s password. if (p.passwordTokenSeen) { if (encodedCodePoints != null) { url.appendToPassword(encodedCodePoints); } else { url.appendToPassword(codePoint); } } // Otherwise, append encodedCodePoints to url’s username. else { if (encodedCodePoints != null) { url.appendToUsername(encodedCodePoints); } else { url.appendToUsername(codePoint); } } } // Set buffer to the empty string. p.emptyBuffer(); } // Otherwise, if one of the following is true: // - c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#) // - url is special and c is U+005C (\) else if ((c == EOF || c == '/' || c == '?' || c == '#') || (url.isSpecial() && c == '\\')) { // If atSignSeen is true and buffer is the empty string, // host-missing validation error, return failure. if (p.atSignSeen && p.buffer.isEmpty()) { p.failure("Missing host."); } // Decrease pointer by buffer’s code point length + 1, // set buffer to the empty string, and set state to host state. p.pointer -= p.buffer.length() + 1; p.emptyBuffer(); p.setState(HOST); } // Otherwise, append c to buffer. else { p.append(c); } } }, HOST { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If state override is given and url’s scheme is "file", // then decrease pointer by 1 and set state to file host state. if (p.stateOverride != null && "file".equals(url.scheme())) { p.pointer--; p.setState(FILE_HOST); } // Otherwise, if c is U+003A (:) and insideBrackets is false, then: else if (c == ':' && !p.insideBrackets) { // If buffer is the empty string, host-missing validation error, return failure. if (p.buffer.isEmpty()) { p.failure("Missing host."); } // If state override is given and state override is hostname state, then return. if (p.stateOverride == HOST) { p.stopMainLoop = true; return; } // Let host be the result of host parsing buffer with url is not special. // Set url’s host to host, buffer to the empty string, and state to port state. url.host = Host.parse(p.buffer.toString(), !url.isSpecial(), p); p.emptyBuffer(); p.setState(PORT); } // Otherwise, if one of the following is true: // - c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#) // - url is special and c is U+005C (\) else if ( (c == EOF || c == '/' || c == '?' || c == '#') || (url.isSpecial() && c == '\\')) { // then decrease pointer by 1, and then: p.pointer--; // If url is special and buffer is the empty string, // host-missing validation error, return failure. if (url.isSpecial() && p.buffer.isEmpty()) { p.failure("The input has a special scheme, but does not contain a host."); } // Otherwise, if state override is given, buffer is the empty string, // and either url includes credentials or url’s port is non-null, return. else if (p.stateOverride != null && p.buffer.isEmpty() && (url.includesCredentials() || url.port() != null )) { p.stopMainLoop = true; return; } // EXTRA: if buffer is not empty if (!p.buffer.isEmpty()) { // Let host be the result of host parsing buffer with url is not special. // Set url’s host to host, buffer to the empty string, and state to path start state. url.host = Host.parse(p.buffer.toString(), !url.isSpecial(), p); } else { url.host = EmptyHost.INSTANCE; } p.emptyBuffer(); p.setState(PATH_START); // If state override is given, then return. if (p.stateOverride != null) { p.stopMainLoop = true; } } // Otherwise: else { // If c is U+005B ([), then set insideBrackets to true. if (c == '[') { p.insideBrackets = true; } // If c is U+005D (]), then set insideBrackets to false. else if (c == ']') { p.insideBrackets = false; } // Append c to buffer. p.append(c); } } }, PORT { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is an ASCII digit, append c to buffer. if (isAsciiDigit(c)) { p.append(c); } // Otherwise, if one of the following is true: // - c is the EOF code point, U+002F (/), U+003F (?), or U+0023 (#) // - url is special and c is U+005C (\) // - state override is given else if (c == EOF || c == '/' || c == '?' || c == '#' || (url.isSpecial() && c == '\\') || (p.stateOverride != null)) { // If buffer is not the empty string, then: if (!p.buffer.isEmpty()) { // EXTRA: if buffer contains only ASCII digits, then if (containsOnlyAsciiDigits(p.buffer)) { try { // Let port be the mathematical integer value that is represented // by buffer in radix-10 using ASCII digits for digits with values 0 through 9. int port = Integer.parseInt(p.buffer, 0, p.buffer.length(), 10); // If port is greater than 2^16 − 1, // port-out-of-range validation error, return failure. if (port > MAX_PORT) { p.failure("Port \"" + port + "\" is out of range"); } int defaultPort = defaultPort(url.scheme); // Set url’s port to null, if port is url’s scheme’s default port; otherwise to port. if (defaultPort != -1 && port == defaultPort) { url.port = null; } else { url.port = new IntPort(port); } } catch (NumberFormatException ex) { p.failure(ex.getMessage()); } } // EXTRA: otherwise, set url's port to buffer else { url.port = new StringPort(p.buffer.toString()); } // Set buffer to the empty string. p.emptyBuffer(); } // If state override is given, then return. if (p.stateOverride != null) { p.stopMainLoop = true; return; } // Set state to path start state and decrease pointer by 1. p.setState(PATH_START); p.pointer--; } // EXTRA: if c is within URI variable, keep appending else if (p.processCurlyBrackets(c)) { p.append(c); } // Otherwise, port-invalid validation error, return failure. else { p.failure("Invalid port: \"" + Character.toString(c) + "\""); } } }, FILE { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // Set url’s scheme to "file". url.scheme = "file"; // Set url’s host to the empty string. url.host = EmptyHost.INSTANCE; // If c is U+002F (/) or U+005C (\), then: if (c == '/' || c == '\\') { // If c is U+005C (\), invalid-reverse-solidus validation error. if (p.validate() && c == '\\') { p.validationError("URL uses \\ instead of /."); } // Set state to file slash state. p.setState(FILE_SLASH); } // Otherwise, if base is non-null and base’s scheme is "file": else if (p.base != null && p.base.scheme().equals("file")) { // Set url’s host to base’s host, url’s path to a clone of base’s path, // and url’s query to base’s query. url.host = p.base.host; url.path = p.base.path().clone(); url.query = p.base.query; // If c is U+003F (?), then set url’s query to the empty string and state to query state. if (c == '?') { url.query = new StringBuilder(); p.setState(QUERY); } // Otherwise, if c is U+0023 (#), set url’s fragment to // the empty string and state to fragment state. else if (c == '#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } // Otherwise, if c is not the EOF code point: else if (c != EOF) { // Set url’s query to null. url.query = null; // If the code point substring from pointer to the end of input does not start with // a Windows drive letter, then shorten url’s path. String substring = p.input.substring(p.pointer); if (!startsWithWindowsDriveLetter(substring)) { url.shortenPath(); } // Otherwise: else { // File-invalid-Windows-drive-letter validation error. if (p.validate()) { p.validationError("The input is a relative-URL string that starts with " + "a Windows drive letter and the base URL’s scheme is \"file\"."); } // Set url’s path to « ». url.path = new PathSegments(); } // Set state to path state and decrease pointer by 1. p.setState(PATH); p.pointer--; } } // Otherwise, set state to path state, and decrease pointer by 1. else { p.setState(PATH); p.pointer--; } } }, FILE_SLASH { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+002F (/) or U+005C (\), then: if (c == '/' || c == '\\') { // If c is U+005C (\), invalid-reverse-solidus validation error. if (p.validate() && c == '\\') { p.validationError("URL uses \\ instead of /."); } // Set state to file host state. p.setState(FILE_HOST); } // Otherwise: else { // If base is non-null and base’s scheme is "file", then: if (p.base != null && p.base.scheme.equals("file")) { // Set url’s host to base’s host. url.host = p.base.host; // If the code point substring from pointer to the end of input does not start with // a Windows drive letter and base’s path[0] is a normalized Windows drive letter, // then append base’s path[0] to url’s path. String substring = p.input.substring(p.pointer); if (!startsWithWindowsDriveLetter(substring) && p.base.path instanceof PathSegments basePath && !basePath.isEmpty() && isWindowsDriveLetter(basePath.get(0), true)) { url.path.append(basePath.get(0)); } } // Set state to path state, and decrease pointer by 1. p.setState(PATH); p.pointer--; } } }, FILE_HOST { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is the EOF code point, U+002F (/), U+005C (\), U+003F (?), or U+0023 (#), // then decrease pointer by 1 and then: if (c == EOF || c == '/' || c == '\\' || c == '?' || c == '#') { p.pointer--; // If state override is not given and buffer is a Windows drive letter, // file-invalid-Windows-drive-letter-host validation error, set state to path state. if (p.stateOverride == null && isWindowsDriveLetter(p.buffer, false)) { p.validationError("A file: URL’s host is a Windows drive letter."); p.setState(PATH); } // Otherwise, if buffer is the empty string, then: else if (p.buffer.isEmpty()) { // Set url’s host to the empty string. url.host = EmptyHost.INSTANCE; // If state override is given, then return. if (p.stateOverride != null) { p.stopMainLoop = true; return; } // Set state to path start state. p.setState(PATH_START); } // Otherwise, run these steps: else { // Let host be the result of host parsing buffer with url is not special. Host host = Host.parse(p.buffer.toString(), !url.isSpecial(), p); // If host is "localhost", then set host to the empty string. if (host instanceof Domain domain && domain.domain().equals("localhost")) { host = EmptyHost.INSTANCE; } // Set url’s host to host. url.host = host; // If state override is given, then return. if (p.stateOverride != null) { p.stopMainLoop = true; return; } // Set buffer to the empty string and state to path start state. p.emptyBuffer(); p.setState(PATH_START); } } // Otherwise, append c to buffer. else { p.append(c); } } }, PATH_START { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If url is special, then: if (url.isSpecial()) { // If c is U+005C (\), invalid-reverse-solidus validation error. if (p.validate() && c == '\\') { p.validationError("URL uses \"\\\" instead of \"/\""); } // Set state to path state. p.setState(PATH); // If c is neither U+002F (/) nor U+005C (\), then decrease pointer by 1. if (c != '/' && c != '\\') { p.pointer--; } else { p.append('/'); } } // Otherwise, if state override is not given and if c is U+003F (?), // set url’s query to the empty string and state to query state. else if (p.stateOverride == null && c == '?') { url.query = new StringBuilder(); p.setState(QUERY); } // Otherwise, if state override is not given and if c is U+0023 (#), // set url’s fragment to the empty string and state to fragment state. else if (p.stateOverride == null && c =='#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } // Otherwise, if c is not the EOF code point: else if (c != EOF) { // Set state to path state. p.setState(PATH); // If c is not U+002F (/), then decrease pointer by 1. if (c != '/') { p.pointer--; } // EXTRA: otherwise append '/' to let the path segment start with / else { p.append('/'); } } // Otherwise, if state override is given and url’s host is null, // append the empty string to url’s path. else if (p.stateOverride != null && url.host() == null) { url.path().append(""); } } }, PATH { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If one of the following is true: // - c is the EOF code point or U+002F (/) // - url is special and c is U+005C (\) // - state override is not given and c is U+003F (?) or U+0023 (#) // then: if (c == EOF || c == '/' || (url.isSpecial() && c == '\\') || (p.stateOverride == null && (c == '?' || c == '#'))) { // If url is special and c is U+005C (\), invalid-reverse-solidus validation error. if (p.validate() && url.isSpecial() && c == '\\') { p.validationError("URL uses \"\\\" instead of \"/\""); } // If buffer is a double-dot URL path segment, then: if (isDoubleDotPathSegment(p.buffer)) { // Shorten url’s path. url.shortenPath(); // If neither c is U+002F (/), nor url is special and c is U+005C (\), // append the empty string to url’s path. if (c != '/' && !(url.isSpecial() && c == '\\')) { url.path.append(""); } } else { boolean singlePathSegment = isSingleDotPathSegment(p.buffer); // Otherwise, if buffer is a single-dot URL path segment and if neither c is U+002F (/), // nor url is special and c is U+005C (\), append the empty string to url’s path. if (singlePathSegment && c != '/' && !(url.isSpecial() && c == '\\')) { url.path.append(""); } // Otherwise, if buffer is not a single-dot URL path segment, then: else if (!singlePathSegment) { // If url’s scheme is "file", url’s path is empty, and buffer is // a Windows drive letter, then replace the second code point in buffer with U+003A (:). if ("file".equals(url.scheme) && url.path.isEmpty() && isWindowsDriveLetter(p.buffer, false)) { p.buffer.setCharAt(1, ':'); } // Append buffer to url’s path. url.path.append(p.buffer.toString()); } } // Set buffer to the empty string. p.emptyBuffer(); if ( c == '/' || url.isSpecial() && c == '\\') { p.append('/'); } // If c is U+003F (?), then set url’s query to the empty string and state to query state. if (c == '?') { url.query = new StringBuilder(); p.setState(QUERY); } // If c is U+0023 (#), then set url’s fragment to the empty string and state to fragment state. if (c == '#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } } // Otherwise, run these steps: else { if (p.validate()) { // If c is not a URL code point and not U+0025 (%), invalid-URL-unit validation error. if (!isUrlCodePoint(c) && c != '%') { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } // If c is U+0025 (%) and remaining does not start with two ASCII hex digits, // invalid-URL-unit validation error. else if (c == '%' && (p.pointer >= p.input.length() - 2 || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 1)) || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 2)))) { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } } // UTF-8 percent-encode c using the path percent-encode set and append the result to buffer. String encoded = p.percentEncode(c, WhatWgUrlParser::pathPercentEncodeSet); if (encoded != null) { p.append(encoded); } else { p.append(c); } } } }, OPAQUE_PATH { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is U+003F (?), then set url’s query to the empty string and state to query state. if (c == '?') { url.query = new StringBuilder(); p.setState(QUERY); } // Otherwise, if c is U+0023 (#), then set url’s fragment to // the empty string and state to fragment state. else if (c == '#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } // Otherwise: else { if (p.validate()) { // If c is not the EOF code point, not a URL code point, and not U+0025 (%), // invalid-URL-unit validation error. if (c != EOF && !isUrlCodePoint(c) && c != '%') { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } // If c is U+0025 (%) and remaining does not start with two ASCII hex digits, // invalid-URL-unit validation error. else if (c == '%' && (p.pointer >= p.input.length() - 2 || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 1)) || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 2)))) { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } } // If c is not the EOF code point, UTF-8 percent-encode c using // the C0 control percent-encode set and append the result to url’s path. if (c != EOF) { String encoded = p.percentEncode(c, WhatWgUrlParser::c0ControlPercentEncodeSet); if (encoded != null) { url.path.append(encoded); } else { url.path.append(c); } } } } }, QUERY { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If encoding is not UTF-8 and one of the following is true: // - url is not special // - url’s scheme is "ws" or "wss" // then set encoding to UTF-8. if (p.encoding != null && !StandardCharsets.UTF_8.equals(p.encoding) && (!url.isSpecial() || "ws".equals(url.scheme) || "wss".equals(url.scheme))) { p.encoding = StandardCharsets.UTF_8; } // If one of the following is true: // - state override is not given and c is U+0023 (#) // - c is the EOF code point if ( (p.stateOverride == null && c == '#') || c == EOF) { // Let queryPercentEncodeSet be the special-query percent-encode set if url is special; // otherwise the query percent-encode set. IntPredicate queryPercentEncodeSet = (url.isSpecial() ? WhatWgUrlParser::specialQueryPercentEncodeSet : WhatWgUrlParser::queryPercentEncodeSet); // Percent-encode after encoding, with encoding, buffer, and queryPercentEncodeSet, // and append the result to url’s query. String encoded = p.percentEncode(p.buffer.toString(), queryPercentEncodeSet); Assert.state(url.query != null, "Url's query should not be null"); url.query.append(encoded); // Set buffer to the empty string. p.emptyBuffer(); // If c is U+0023 (#), then set url’s fragment to the empty string and state to fragment state. if (c == '#') { url.fragment = new StringBuilder(); p.setState(FRAGMENT); } } // Otherwise, if c is not the EOF code point: else { if (p.validate()) { // If c is not a URL code point and not U+0025 (%), invalid-URL-unit validation error. if (!isUrlCodePoint(c) && c != '%') { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } // If c is U+0025 (%) and remaining does not start with two ASCII hex digits, // invalid-URL-unit validation error. else if (c == '%' && (p.pointer >= p.input.length() - 2 || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 1)) || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 2)))) { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } } // Append c to buffer. p.append(c); } } }, FRAGMENT { @Override public void handle(int c, UrlRecord url, WhatWgUrlParser p) { // If c is not the EOF code point, then: if (c != EOF) { if (p.validate()) { // If c is not a URL code point and not U+0025 (%), invalid-URL-unit validation error. if (!isUrlCodePoint(c) && c != '%') { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } // If c is U+0025 (%) and remaining does not start with two ASCII hex digits, // invalid-URL-unit validation error. else if (c == '%' && (p.pointer >= p.input.length() - 2 || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 1)) || !isAsciiHexDigit(p.input.codePointAt(p.pointer + 2)))) { p.validationError("Invalid URL Unit: \"" + (char) c + "\""); } } // UTF-8 percent-encode c using the fragment percent-encode set and // append the result to url’s fragment. String encoded = p.percentEncode(c, WhatWgUrlParser::fragmentPercentEncodeSet); Assert.state(url.fragment != null, "Url's fragment should not be null"); if (encoded != null) { url.fragment.append(encoded); } else { url.fragment.appendCodePoint(c); } } } }; public abstract void handle(int c, UrlRecord url, WhatWgUrlParser p); } /** * A URL is a struct that represents a universal identifier. * To disambiguate from a valid URL string it can also be referred to as a * <em>URL record</em>. */ static final
State
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/OffsetFetcherUtils.java
{ "start": 2416, "end": 19909 }
class ____ { private final ConsumerMetadata metadata; private final SubscriptionState subscriptionState; private final Time time; private final long retryBackoffMs; private final ApiVersions apiVersions; private final PositionsValidator positionsValidator; private final Logger log; /** * Exception that occurred while resetting positions, that will be propagated on the next * call to reset positions. This will have the error received in the response to the * ListOffsets request. It will be cleared when thrown on the next call to reset. */ private final AtomicReference<RuntimeException> cachedResetPositionsException = new AtomicReference<>(); OffsetFetcherUtils(LogContext logContext, ConsumerMetadata metadata, SubscriptionState subscriptionState, Time time, long retryBackoffMs, ApiVersions apiVersions) { this(logContext, metadata, subscriptionState, time, retryBackoffMs, apiVersions, new PositionsValidator(logContext, time, subscriptionState, metadata)); } OffsetFetcherUtils(LogContext logContext, ConsumerMetadata metadata, SubscriptionState subscriptionState, Time time, long retryBackoffMs, ApiVersions apiVersions, PositionsValidator positionsValidator) { this.log = logContext.logger(getClass()); this.metadata = metadata; this.subscriptionState = subscriptionState; this.time = time; this.retryBackoffMs = retryBackoffMs; this.apiVersions = apiVersions; this.positionsValidator = positionsValidator; } /** * Callback for the response of the list offset call. * * @param listOffsetsResponse The response from the server. * @return {@link OffsetFetcherUtils.ListOffsetResult} extracted from the response, containing the fetched offsets * and partitions to retry. */ OffsetFetcherUtils.ListOffsetResult handleListOffsetResponse(ListOffsetsResponse listOffsetsResponse) { Map<TopicPartition, OffsetFetcherUtils.ListOffsetData> fetchedOffsets = new HashMap<>(); Set<TopicPartition> partitionsToRetry = new HashSet<>(); Set<String> unauthorizedTopics = new HashSet<>(); for (ListOffsetsResponseData.ListOffsetsTopicResponse topic : listOffsetsResponse.topics()) { for (ListOffsetsResponseData.ListOffsetsPartitionResponse partition : topic.partitions()) { TopicPartition topicPartition = new TopicPartition(topic.name(), partition.partitionIndex()); Errors error = Errors.forCode(partition.errorCode()); switch (error) { case NONE: log.debug("Handling ListOffsetResponse response for {}. Fetched offset {}, timestamp {}", topicPartition, partition.offset(), partition.timestamp()); if (partition.offset() != ListOffsetsResponse.UNKNOWN_OFFSET) { Optional<Integer> leaderEpoch = (partition.leaderEpoch() == ListOffsetsResponse.UNKNOWN_EPOCH) ? Optional.empty() : Optional.of(partition.leaderEpoch()); OffsetFetcherUtils.ListOffsetData offsetData = new OffsetFetcherUtils.ListOffsetData(partition.offset(), partition.timestamp(), leaderEpoch); fetchedOffsets.put(topicPartition, offsetData); } break; case UNSUPPORTED_FOR_MESSAGE_FORMAT: // The message format on the broker side is before 0.10.0, which means it does not // support timestamps. We treat this case the same as if we weren't able to find an // offset corresponding to the requested timestamp and leave it out of the result. log.debug("Cannot search by timestamp for partition {} because the message format version " + "is before 0.10.0", topicPartition); break; case NOT_LEADER_OR_FOLLOWER: case REPLICA_NOT_AVAILABLE: case KAFKA_STORAGE_ERROR: case OFFSET_NOT_AVAILABLE: case LEADER_NOT_AVAILABLE: case FENCED_LEADER_EPOCH: case UNKNOWN_LEADER_EPOCH: log.debug("Attempt to fetch offsets for partition {} failed due to {}, retrying.", topicPartition, error); partitionsToRetry.add(topicPartition); break; case UNKNOWN_TOPIC_OR_PARTITION: log.warn("Received unknown topic or partition error in ListOffset request for partition {}", topicPartition); partitionsToRetry.add(topicPartition); break; case TOPIC_AUTHORIZATION_FAILED: unauthorizedTopics.add(topicPartition.topic()); break; default: log.warn("Attempt to fetch offsets for partition {} failed due to unexpected exception: {}, retrying.", topicPartition, error.message()); partitionsToRetry.add(topicPartition); } } } if (!unauthorizedTopics.isEmpty()) throw new TopicAuthorizationException(unauthorizedTopics); else return new OffsetFetcherUtils.ListOffsetResult(fetchedOffsets, partitionsToRetry); } <T> Map<Node, Map<TopicPartition, T>> regroupPartitionMapByNode(Map<TopicPartition, T> partitionMap) { return partitionMap.entrySet() .stream() .collect(Collectors.groupingBy(entry -> metadata.fetch().leaderFor(entry.getKey()), Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } Map<TopicPartition, SubscriptionState.FetchPosition> refreshAndGetPartitionsToValidate() { return positionsValidator.refreshAndGetPartitionsToValidate(apiVersions); } /** * If we have seen new metadata (as tracked by {@link org.apache.kafka.clients.Metadata#updateVersion()}), then * we should check that all the assignments have a valid position. */ void validatePositionsOnMetadataChange() { positionsValidator.validatePositionsOnMetadataChange(apiVersions); } /** * get OffsetResetStrategy for all assigned partitions */ Map<TopicPartition, AutoOffsetResetStrategy> getOffsetResetStrategyForPartitions() { // Raise exception from previous offset fetch if there is one RuntimeException exception = cachedResetPositionsException.getAndSet(null); if (exception != null) throw exception; Set<TopicPartition> partitions = subscriptionState.partitionsNeedingReset(time.milliseconds()); final Map<TopicPartition, AutoOffsetResetStrategy> partitionAutoOffsetResetStrategyMap = new HashMap<>(); for (final TopicPartition partition : partitions) { partitionAutoOffsetResetStrategyMap.put(partition, offsetResetStrategyWithValidTimestamp(partition)); } return partitionAutoOffsetResetStrategyMap; } static Map<TopicPartition, OffsetAndTimestamp> buildListOffsetsResult( final Map<TopicPartition, Long> timestampsToSearch, final Map<TopicPartition, ListOffsetData> fetchedOffsets, BiFunction<TopicPartition, ListOffsetData, OffsetAndTimestamp> resultMapper) { HashMap<TopicPartition, OffsetAndTimestamp> offsetsResults = new HashMap<>(timestampsToSearch.size()); for (Map.Entry<TopicPartition, Long> entry : timestampsToSearch.entrySet()) offsetsResults.put(entry.getKey(), null); for (Map.Entry<TopicPartition, ListOffsetData> entry : fetchedOffsets.entrySet()) { ListOffsetData offsetData = entry.getValue(); offsetsResults.put(entry.getKey(), resultMapper.apply(entry.getKey(), offsetData)); } return offsetsResults; } static Map<TopicPartition, OffsetAndTimestamp> buildOffsetsForTimesResult( final Map<TopicPartition, Long> timestampsToSearch, final Map<TopicPartition, ListOffsetData> fetchedOffsets) { return buildListOffsetsResult(timestampsToSearch, fetchedOffsets, (topicPartition, offsetData) -> new OffsetAndTimestamp( offsetData.offset, offsetData.timestamp, offsetData.leaderEpoch)); } static Map<TopicPartition, OffsetAndTimestampInternal> buildOffsetsForTimeInternalResult( final Map<TopicPartition, Long> timestampsToSearch, final Map<TopicPartition, ListOffsetData> fetchedOffsets) { HashMap<TopicPartition, OffsetAndTimestampInternal> offsetsResults = new HashMap<>(timestampsToSearch.size()); for (Map.Entry<TopicPartition, Long> entry : timestampsToSearch.entrySet()) { offsetsResults.put(entry.getKey(), null); } for (Map.Entry<TopicPartition, ListOffsetData> entry : fetchedOffsets.entrySet()) { ListOffsetData offsetData = entry.getValue(); offsetsResults.put(entry.getKey(), new OffsetAndTimestampInternal( offsetData.offset, offsetData.timestamp, offsetData.leaderEpoch)); } return offsetsResults; } private AutoOffsetResetStrategy offsetResetStrategyWithValidTimestamp(final TopicPartition partition) { AutoOffsetResetStrategy strategy = subscriptionState.resetStrategy(partition); if (strategy.timestamp().isPresent()) { return strategy; } else { throw new NoOffsetForPartitionException(partition); } } static Set<String> topicsForPartitions(Collection<TopicPartition> partitions) { return partitions.stream().map(TopicPartition::topic).collect(Collectors.toSet()); } void updateSubscriptionState(Map<TopicPartition, OffsetFetcherUtils.ListOffsetData> fetchedOffsets, IsolationLevel isolationLevel) { for (final Map.Entry<TopicPartition, ListOffsetData> entry : fetchedOffsets.entrySet()) { final TopicPartition partition = entry.getKey(); // if the interested partitions are part of the subscriptions, use the returned offset to update // the subscription state as well: // * with read-committed, the returned offset would be LSO; // * with read-uncommitted, the returned offset would be HW; if (subscriptionState.isAssigned(partition)) { final long offset = entry.getValue().offset; if (isolationLevel == IsolationLevel.READ_COMMITTED) { log.trace("Updating last stable offset for partition {} to {}", partition, offset); subscriptionState.updateLastStableOffset(partition, offset); } else { log.trace("Updating high watermark for partition {} to {}", partition, offset); subscriptionState.updateHighWatermark(partition, offset); } } } } void onSuccessfulResponseForResettingPositions( final ListOffsetResult result, final Map<TopicPartition, AutoOffsetResetStrategy> partitionAutoOffsetResetStrategyMap) { if (!result.partitionsToRetry.isEmpty()) { subscriptionState.requestFailed(result.partitionsToRetry, time.milliseconds() + retryBackoffMs); metadata.requestUpdate(false); } for (Map.Entry<TopicPartition, ListOffsetData> fetchedOffset : result.fetchedOffsets.entrySet()) { TopicPartition partition = fetchedOffset.getKey(); ListOffsetData offsetData = fetchedOffset.getValue(); resetPositionIfNeeded( partition, partitionAutoOffsetResetStrategyMap.get(partition), offsetData); } } void onFailedResponseForResettingPositions( final Map<TopicPartition, ListOffsetsRequestData.ListOffsetsPartition> resetTimestamps, final RuntimeException error) { subscriptionState.requestFailed(resetTimestamps.keySet(), time.milliseconds() + retryBackoffMs); metadata.requestUpdate(false); if (!(error instanceof RetriableException) && !cachedResetPositionsException.compareAndSet(null, error)) log.error("Discarding error resetting positions because another error is pending", error); } void onSuccessfulResponseForValidatingPositions( final Map<TopicPartition, SubscriptionState.FetchPosition> fetchPositions, final OffsetsForLeaderEpochUtils.OffsetForEpochResult offsetsResult) { List<SubscriptionState.LogTruncation> truncations = new ArrayList<>(); if (!offsetsResult.partitionsToRetry().isEmpty()) { subscriptionState.setNextAllowedRetry(offsetsResult.partitionsToRetry(), time.milliseconds() + retryBackoffMs); metadata.requestUpdate(false); } // For each OffsetsForLeader response, check if the end-offset is lower than our current offset // for the partition. If so, it means we have experienced log truncation and need to reposition // that partition's offset. // In addition, check whether the returned offset and epoch are valid. If not, then we should reset // its offset if reset policy is configured, or throw out of range exception. offsetsResult.endOffsets().forEach((topicPartition, respEndOffset) -> { SubscriptionState.FetchPosition requestPosition = fetchPositions.get(topicPartition); Optional<SubscriptionState.LogTruncation> truncationOpt = subscriptionState.maybeCompleteValidation(topicPartition, requestPosition, respEndOffset); truncationOpt.ifPresent(truncations::add); }); if (!truncations.isEmpty()) { positionsValidator.maybeSetError(buildLogTruncationException(truncations)); } } void onFailedResponseForValidatingPositions(final Map<TopicPartition, SubscriptionState.FetchPosition> fetchPositions, final RuntimeException error) { subscriptionState.requestFailed(fetchPositions.keySet(), time.milliseconds() + retryBackoffMs); metadata.requestUpdate(false); if (!(error instanceof RetriableException)) { positionsValidator.maybeSetError(error); } } private LogTruncationException buildLogTruncationException(List<SubscriptionState.LogTruncation> truncations) { Map<TopicPartition, OffsetAndMetadata> divergentOffsets = new HashMap<>(); Map<TopicPartition, Long> truncatedFetchOffsets = new HashMap<>(); for (SubscriptionState.LogTruncation truncation : truncations) { truncation.divergentOffsetOpt.ifPresent(divergentOffset -> divergentOffsets.put(truncation.topicPartition, divergentOffset)); truncatedFetchOffsets.put(truncation.topicPartition, truncation.fetchPosition.offset); } return new LogTruncationException(truncatedFetchOffsets, divergentOffsets); } // Visible for testing void resetPositionIfNeeded(TopicPartition partition, AutoOffsetResetStrategy requestedResetStrategy, ListOffsetData offsetData) { SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetData.offset, Optional.empty(), // This will ensure we skip validation metadata.currentLeader(partition)); offsetData.leaderEpoch.ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(partition, epoch)); subscriptionState.maybeSeekUnvalidated(partition, position, requestedResetStrategy); } static Map<Node, Map<TopicPartition, SubscriptionState.FetchPosition>> regroupFetchPositionsByLeader( Map<TopicPartition, SubscriptionState.FetchPosition> partitionMap) { return partitionMap.entrySet() .stream() .filter(entry -> entry.getValue().currentLeader.leader.isPresent()) .collect(Collectors.groupingBy(entry -> entry.getValue().currentLeader.leader.get(), Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); } static boolean hasUsableOffsetForLeaderEpochVersion(NodeApiVersions nodeApiVersions) { ApiVersionsResponseData.ApiVersion apiVersion = nodeApiVersions.apiVersion(ApiKeys.OFFSET_FOR_LEADER_EPOCH); if (apiVersion == null) return false; return OffsetsForLeaderEpochRequest.supportsTopicPermission(apiVersion.maxVersion()); } static
OffsetFetcherUtils
java
apache__flink
flink-connectors/flink-connector-base/src/test/java/org/apache/flink/connector/base/source/reader/fetcher/SplitFetcherTest.java
{ "start": 14358, "end": 15389 }
class ____ extends CheckedThread { private final FutureCompletingBlockingQueue<?> queue; private final SplitFetcher<?, ?> fetcher; private final int numFetchesToTake; private volatile boolean wasIdleWhenFinished; QueueDrainerThread( FutureCompletingBlockingQueue<?> queue, SplitFetcher<?, ?> fetcher, int numFetchesToTake) { super("Queue Drainer"); setPriority(Thread.MAX_PRIORITY); this.queue = queue; this.fetcher = fetcher; this.numFetchesToTake = numFetchesToTake; } @Override public void go() throws Exception { int remaining = numFetchesToTake; while (remaining > 0) { remaining--; queue.take(); } wasIdleWhenFinished = fetcher.isIdle(); } public boolean wasIdleWhenFinished() { return wasIdleWhenFinished; } } }
QueueDrainerThread
java
apache__camel
components/camel-azure/camel-azure-files/src/main/java/org/apache/camel/component/file/azure/strategy/StrategyUtil.java
{ "start": 1057, "end": 2678 }
class ____ { private StrategyUtil() { } static <T> void ifNotEmpty(Map<String, Object> params, String key, Class<T> clazz, Consumer<T> consumer) { Object o = params.get(key); if (o != null) { consumer.accept(clazz.cast(o)); } } static void setup(GenericFileRenameExclusiveReadLockStrategy<?> readLockStrategy, Map<String, Object> params) { ifNotEmpty(params, "readLockTimeout", Long.class, readLockStrategy::setTimeout); ifNotEmpty(params, "readLockCheckInterval", Long.class, readLockStrategy::setCheckInterval); ifNotEmpty(params, "readLockMarkerFile", Boolean.class, readLockStrategy::setMarkerFiler); ifNotEmpty(params, "readLockLoggingLevel", LoggingLevel.class, readLockStrategy::setReadLockLoggingLevel); } static void setup(FilesChangedExclusiveReadLockStrategy readLockStrategy, Map<String, Object> params) { ifNotEmpty(params, "readLockTimeout", Long.class, readLockStrategy::setTimeout); ifNotEmpty(params, "readLockCheckInterval", Long.class, readLockStrategy::setCheckInterval); ifNotEmpty(params, "readLockMinLength", Long.class, readLockStrategy::setMinLength); ifNotEmpty(params, "readLockMinAge", Long.class, readLockStrategy::setMinAge); ifNotEmpty(params, "fastExistsCheck", Boolean.class, readLockStrategy::setFastExistsCheck); ifNotEmpty(params, "readLockMarkerFile", Boolean.class, readLockStrategy::setMarkerFiler); ifNotEmpty(params, "readLockLoggingLevel", LoggingLevel.class, readLockStrategy::setReadLockLoggingLevel); } }
StrategyUtil
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/util/JandexUtilTest.java
{ "start": 9861, "end": 9930 }
class ____ implements Repo<Integer> { } public static
DirectRepo
java
apache__maven
its/core-it-support/core-it-plugins/maven-it-plugin-dependency-resolution/src/main/java/org/apache/maven/plugin/coreit/AbstractDependencyMojo.java
{ "start": 4779, "end": 5223 }
class ____ elements to write to the file, may be <code>null</code>. * @throws MojoExecutionException If the output file could not be written. */ protected void writeClassPath(String pathname, Collection classPath) throws MojoExecutionException { if (pathname == null || pathname.length() <= 0) { return; } File file = resolveFile(pathname); getLog().info("[MAVEN-CORE-IT-LOG] Dumping
path
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/X509SelfSignedCertificateVerifier.java
{ "start": 4466, "end": 6444 }
class ____ implements Function<RegisteredClient, JWKSet> { private static final MediaType APPLICATION_JWK_SET_JSON = new MediaType("application", "jwk-set+json"); private final RestOperations restOperations; private final Map<String, Supplier<JWKSet>> jwkSets = new ConcurrentHashMap<>(); private JwkSetSupplier() { SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout(15_000); requestFactory.setReadTimeout(15_000); this.restOperations = new RestTemplate(requestFactory); } @Override public JWKSet apply(RegisteredClient registeredClient) { Supplier<JWKSet> jwkSetSupplier = this.jwkSets.computeIfAbsent(registeredClient.getId(), (key) -> { if (!StringUtils.hasText(registeredClient.getClientSettings().getJwkSetUrl())) { throwInvalidClient("client_jwk_set_url"); } return new JwkSetHolder(registeredClient.getClientSettings().getJwkSetUrl()); }); return jwkSetSupplier.get(); } private JWKSet retrieve(String jwkSetUrl) { URI jwkSetUri = null; try { jwkSetUri = new URI(jwkSetUrl); } catch (URISyntaxException ex) { throwInvalidClient("jwk_set_uri", ex); } HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON, APPLICATION_JWK_SET_JSON)); RequestEntity<Void> request = new RequestEntity<>(headers, HttpMethod.GET, jwkSetUri); ResponseEntity<String> response = null; try { response = this.restOperations.exchange(request, String.class); } catch (Exception ex) { throwInvalidClient("jwk_set_response_error", ex); } if (response.getStatusCode().value() != 200) { throwInvalidClient("jwk_set_response_status"); } JWKSet jwkSet = null; try { jwkSet = JWKSet.parse(response.getBody()); } catch (ParseException ex) { throwInvalidClient("jwk_set_response_body", ex); } return jwkSet; } private final
JwkSetSupplier
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ResourceConditionTests.java
{ "start": 2997, "end": 3198 }
class ____ extends ResourceCondition { DefaultLocationResourceCondition() { super("test", "spring.foo.test.config", "classpath:/logging.properties"); } } static
DefaultLocationResourceCondition
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/ASTHelpersTest.java
{ "start": 45888, "end": 46546 }
class ____ { } """); TestScanner scanner = new TestScanner() { @Override public Void visitClass(ClassTree node, VisitorState visitorState) { // we specifically want to test getSymbol(Tree), not getSymbol(ClassTree) Tree tree = node; assertThat(ASTHelpers.getSymbol(tree).isDeprecated()).isTrue(); setAssertionsComplete(); return super.visitClass(node, visitorState); } }; tests.add(scanner); assertCompiles(scanner); } @Test public void outermostclass_dotClass() { writeFile( "Foo.java", """
A
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/ipc/RPC.java
{ "start": 36769, "end": 36825 }
class ____. * * 4. If it is an anonymous
TestClass
java
google__dagger
dagger-runtime/main/java/dagger/Component.java
{ "start": 1319, "end": 4399 }
interface ____ {...}} will produce an implementation named * {@code DaggerMyComponent}. * * <p><a id="component-methods"></a> * * <h2>Component methods</h2> * * <p>Every type annotated with {@code @Component} must contain at least one abstract component * method. Component methods may have any name, but must have signatures that conform to either * {@linkplain Provider provision} or {@linkplain MembersInjector members-injection} contracts. * * <p><a id="provision-methods"></a> * * <h3>Provision methods</h3> * * <p>Provision methods have no parameters and return an {@link Inject injected} or {@link Provides * provided} type. Each method may have a {@link Qualifier} annotation as well. The following are * all valid provision method declarations: * * <pre><code> * SomeType getSomeType(); * {@literal Set<SomeType>} getSomeTypes(); * {@literal @PortNumber} int getPortNumber(); * </code></pre> * * <p>Provision methods, like typical {@link Inject injection} sites, may use {@link Provider} or * {@link Lazy} to more explicitly control provision requests. A {@link Provider} allows the user of * the component to request provision any number of times by calling {@link Provider#get}. A {@link * Lazy} will only ever request a single provision, but will defer it until the first call to {@link * Lazy#get}. The following provision methods all request provision of the same type, but each * implies different semantics: * * <pre><code> * SomeType getSomeType(); * {@literal Provider<SomeType>} getSomeTypeProvider(); * {@literal Lazy<SomeType>} getLazySomeType(); * </code></pre> * * <a id="members-injection-methods"></a> * * <h3>Members-injection methods</h3> * * <p>Members-injection methods have a single parameter and inject dependencies into each of the * {@link Inject}-annotated fields and methods of the passed instance. A members-injection method * may be void or return its single parameter as a convenience for chaining. The following are all * valid members-injection method declarations: * * <pre><code> * void injectSomeType(SomeType someType); * SomeType injectAndReturnSomeType(SomeType someType); * </code></pre> * * <p>A method with no parameters that returns a {@link MembersInjector} is equivalent to a members * injection method. Calling {@link MembersInjector#injectMembers} on the returned object will * perform the same work as a members injection method. For example: * * <pre><code> * {@literal MembersInjector<SomeType>} getSomeTypeMembersInjector(); * </code></pre> * * <h4>A note about covariance</h4> * * <p>While a members-injection method for a type will accept instances of its subtypes, only {@link * Inject}-annotated members of the parameter type and its supertypes will be injected; members of * subtypes will not. For example, given the following types, only {@code a} and {@code b} will be * injected into an instance of {@code Child} when it is passed to the members-injection method * {@code injectSelf(Self instance)}: * * <pre><code> *
MyComponent
java
apache__flink
flink-test-utils-parent/flink-connector-test-utils/src/main/java/org/apache/flink/connector/testutils/source/TestingJobInfo.java
{ "start": 1453, "end": 1918 }
class ____ { private JobID jobID = null; private String jobName = ""; public Builder() {} public Builder setJobID(JobID jobID) { this.jobID = jobID; return this; } public Builder setJobName(String jobName) { this.jobName = jobName; return this; } public JobInfo build() { return new TestingJobInfo(jobID, jobName); } } }
Builder
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/util/JandexUtilTest.java
{ "start": 7956, "end": 8035 }
interface ____<T1, T2> extends Multiple<T2, T1> { } public
InverseMultiple
java
redisson__redisson
redisson/src/main/java/org/redisson/codec/MarshallingCodec.java
{ "start": 3169, "end": 3938 }
class ____ implements ByteOutput { private final ByteBuf byteBuf; public ByteOutputWrapper(ByteBuf byteBuf) { this.byteBuf = byteBuf; } @Override public void close() throws IOException { } @Override public void flush() throws IOException { } @Override public void write(int b) throws IOException { byteBuf.writeByte(b); } @Override public void write(byte[] b) throws IOException { byteBuf.writeBytes(b); } @Override public void write(byte[] b, int off, int len) throws IOException { byteBuf.writeBytes(b, off, len); } } public
ByteOutputWrapper
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/xml/hbm/HbmXmlHotReloadExplicitFileTestCase.java
{ "start": 485, "end": 1758 }
class ____ { @RegisterExtension final static QuarkusDevModeTest TEST = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClass(SmokeTestUtils.class) .addClass(SchemaUtil.class) .addClass(NonAnnotatedEntity.class) .addClass(HbmXmlHotReloadTestResource.class) .addAsResource("application-mapping-files-my-hbm-xml.properties", "application.properties") .addAsResource("META-INF/hbm-simple.xml", "my-hbm.xml")); @Test public void changeOrmXml() { assertThat(getColumnNames()) .contains("thename") .doesNotContain("name", "thename2"); TEST.modifyResourceFile("my-hbm.xml", s -> s.replace("<property name=\"name\" column=\"thename\"/>", "<property name=\"name\" column=\"thename2\"/>")); assertThat(getColumnNames()) .contains("thename2") .doesNotContain("name", "thename"); } private String[] getColumnNames() { return when().get("/hbm-xml-hot-reload-test/column-names") .then().extract().body().asString() .split("\n"); } }
HbmXmlHotReloadExplicitFileTestCase
java
quarkusio__quarkus
extensions/arc/deployment/src/main/java/io/quarkus/arc/deployment/WrongAnnotationUsageProcessor.java
{ "start": 4052, "end": 4886 }
class ____, incl. the annotations added via transformers Collection<AnnotationInstance> classLevelAnnotations = transformedAnnotations.getAnnotations(clazz); if (scopeAnnotations.isScopeIn(classLevelAnnotations)) { validationErrors.produce(new ValidationErrorBuildItem( new IllegalStateException(String.format( "The %s class %s has a scope annotation but it must be ignored per the CDI rules", clazz.nestingType().toString(), clazz.name().toString())))); } else if (Annotations.containsAny(classLevelAnnotations, interceptorResolverBuildItem.getInterceptorBindings())) { // detect interceptor bindings declared at nested
level
java
netty__netty
transport-native-epoll/src/test/java/io/netty/channel/epoll/EpollSocketSslEchoTest.java
{ "start": 901, "end": 1161 }
class ____ extends SocketSslEchoTest { @Override protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() { return EpollSocketTestPermutation.INSTANCE.socketWithFastOpen(); } }
EpollSocketSslEchoTest
java
google__auto
value/src/test/java/com/google/auto/value/processor/AutoBuilderCompilationTest.java
{ "start": 12093, "end": 12581 }
class ____ {", " Builder(int bogus) {}", " Baz build();", " }", "}"); Compilation compilation = javac() .withProcessors(new AutoBuilderProcessor()) .withOptions("-Acom.google.auto.value.AutoBuilderIsUnstable") .compile(javaFileObject); assertThat(compilation).failed(); assertThat(compilation) .hadErrorContaining( "[AutoBuilderConstructor] @AutoBuilder
Builder
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/deser/SettableBeanProperty.java
{ "start": 862, "end": 1166 }
class ____ deserializable properties of a bean: contains * both type and name definitions, and reflection-based set functionality. * Concrete sub-classes implement details, so that field- and * setter-backed properties, as well as a few more esoteric variations, * can be handled. */ public abstract
for
java
apache__thrift
lib/javame/src/org/apache/thrift/meta_data/StructMetaData.java
{ "start": 1743, "end": 1938 }
class ____ extends FieldValueMetaData { public final Class structClass; public StructMetaData(byte type, Class sClass){ super(type); this.structClass = sClass; } }
StructMetaData
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/webapp/dao/AppsInfo.java
{ "start": 1174, "end": 1422 }
class ____ { protected ArrayList<AppInfo> app = new ArrayList<>(); public AppsInfo() { } // JAXB needs this public void add(AppInfo appInfo) { app.add(appInfo); } public ArrayList<AppInfo> getApps() { return app; } }
AppsInfo
java
spring-projects__spring-boot
module/spring-boot-micrometer-metrics-test/src/main/java/org/springframework/boot/micrometer/metrics/test/autoconfigure/AutoConfigureMetrics.java
{ "start": 1557, "end": 1787 }
interface ____ { /** * Whether metrics should be reported to external systems in the test. * @return whether metrics should be reported to external systems in the test */ boolean export() default true; }
AutoConfigureMetrics
java
spring-projects__spring-framework
spring-oxm/src/main/java/org/springframework/oxm/xstream/XStreamMarshaller.java
{ "start": 10707, "end": 10949 }
class ____. * @see XStream#alias(String, Class) */ public void setAliases(Map<String, ?> aliases) { this.aliases = aliases; } /** * Set the <em>aliases by type</em> map, consisting of string aliases mapped to classes. * <p>Any
names
java
spring-projects__spring-framework
integration-tests/src/test/java/org/springframework/cache/annotation/EnableCachingIntegrationTests.java
{ "start": 3009, "end": 3146 }
class ____ { @Bean CacheManager mgr() { return new NoOpCacheManager(); } } @Configuration static
ProxyTargetClassCachingConfig
java
apache__flink
flink-core/src/main/java/org/apache/flink/util/TemporaryClassLoaderContext.java
{ "start": 901, "end": 1098 }
class ____ in a "try-with-resources" pattern. * * <pre>{@code * try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(classloader)) { * // code that needs the context
loader
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusShowEffectiveConfig.java
{ "start": 805, "end": 4394 }
class ____ extends QuarkusBuildTask { private final Property<Boolean> saveConfigProperties; @Inject public QuarkusShowEffectiveConfig() { super("Collect dependencies for the Quarkus application, prefer the 'quarkusBuild' task", true); this.saveConfigProperties = getProject().getObjects().property(Boolean.class).convention(Boolean.FALSE); } @Option(option = "save-config-properties", description = "Save the effective Quarkus configuration properties to a file.") @Internal public Property<Boolean> getSaveConfigProperties() { return saveConfigProperties; } @TaskAction public void dumpEffectiveConfiguration() { try { ApplicationModel appModel = resolveAppModelForBuild(); EffectiveConfig effectiveConfig = effectiveProvider() .buildEffectiveConfiguration(appModel, getAdditionalForcedProperties().get().getProperties()); SmallRyeConfig config = effectiveConfig.getConfig(); List<String> sourceNames = new ArrayList<>(); config.getConfigSources().forEach(configSource -> sourceNames.add(configSource.getName())); Map<String, String> values = new HashMap<>(); for (String key : config.getMapKeys("quarkus").values()) { values.put(key, config.getConfigValue(key).getValue()); } String quarkusConfig = values .entrySet() .stream() .map(e -> format("%s=%s", e.getKey(), e.getValue())).sorted() .collect(Collectors.joining("\n ", "\n ", "\n")); getLogger().lifecycle("Effective Quarkus configuration options: {}", quarkusConfig); String finalName = getExtensionView().getFinalName().get(); String jarType = config.getOptionalValue("quarkus.package.jar.type", String.class).orElse("fast-jar"); File fastJar = fastJar(); getLogger().lifecycle(""" Quarkus JAR type: {} Final name: {} Output directory: {} Fast jar directory (if built): {} Runner jar (if built): {} Native runner (if built): {} application.(properties|yaml|yml) sources: {}""", jarType, finalName, outputDirectory(), fastJar, runnerJar(), nativeRunner(), sourceNames.stream().collect(Collectors.joining("\n ", "\n ", "\n"))); if (getSaveConfigProperties().get()) { Properties props = new Properties(); props.putAll(effectiveConfig.getValues()); Path file = buildDir.toPath().resolve(finalName + ".quarkus-build.properties"); try (BufferedWriter writer = newBufferedWriter(file)) { props.store(writer, format("Quarkus build properties with JAR type %s", jarType)); } catch (IOException e) { throw new GradleException("Failed to write Quarkus build configuration settings", e); } getLogger().lifecycle("\nWrote configuration settings to {}", file); } } catch (Exception e) { e.printStackTrace(); throw new GradleException("WTF", e); } } }
QuarkusShowEffectiveConfig
java
grpc__grpc-java
examples/example-hostname/src/main/java/io/grpc/examples/hostname/HostnameGreeter.java
{ "start": 1060, "end": 2072 }
class ____ extends GreeterGrpc.GreeterImplBase { private static final Logger logger = Logger.getLogger(HostnameGreeter.class.getName()); private final String serverName; public HostnameGreeter(String serverName) { if (serverName == null) { serverName = determineHostname(); } this.serverName = serverName; } @Override public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { HelloReply reply = HelloReply.newBuilder() .setMessage("Hello " + req.getName() + ", from " + serverName) .build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } private static String determineHostname() { try { return InetAddress.getLocalHost().getHostName(); } catch (IOException ex) { logger.log(Level.INFO, "Failed to determine hostname. Will generate one", ex); } // Strange. Well, let's make an identifier for ourselves. return "generated-" + new Random().nextInt(); } }
HostnameGreeter
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/proxy/AbstractProxyInvoker.java
{ "start": 1913, "end": 6856 }
class ____<T> implements Invoker<T> { ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractProxyInvoker.class); private final T proxy; private final Class<T> type; private final URL url; public AbstractProxyInvoker(T proxy, Class<T> type, URL url) { if (proxy == null) { throw new IllegalArgumentException("proxy == null"); } if (type == null) { throw new IllegalArgumentException("interface == null"); } if (!type.isInstance(proxy)) { throw new IllegalArgumentException(proxy.getClass().getName() + " not implement interface " + type); } this.proxy = proxy; this.type = type; this.url = url; } @Override public Class<T> getInterface() { return type; } @Override public URL getUrl() { return url; } @Override public boolean isAvailable() { return true; } @Override public void destroy() {} @Override public Result invoke(Invocation invocation) throws RpcException { ProfilerEntry originEntry = null; try { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { ProfilerEntry profiler = Profiler.enter( (ProfilerEntry) fromInvocation, "Receive request. Server biz impl invoke begin."); invocation.put(Profiler.PROFILER_KEY, profiler); originEntry = Profiler.setToBizProfiler(profiler); } } Object value = doInvoke( proxy, invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments()); CompletableFuture<Object> future = wrapWithFuture(value, invocation); CompletableFuture<AppResponse> appResponseFuture = future.handle((obj, t) -> { AppResponse result = new AppResponse(invocation); if (t != null) { if (t instanceof CompletionException) { result.setException(t.getCause()); } else { result.setException(t); } } else { result.setValue(obj); } return result; }); return new AsyncRpcResult(appResponseFuture, invocation); } catch (InvocationTargetException e) { if (RpcContext.getServiceContext().isAsyncStarted() && !RpcContext.getServiceContext().stopAsync()) { logger.error( PROXY_ERROR_ASYNC_RESPONSE, "", "", "Provider async started, but got an exception from the original method, cannot write the exception back to consumer because an async result may have returned the new thread.", e); } return AsyncRpcResult.newDefaultAsyncResult(null, e.getTargetException(), invocation); } catch (Throwable e) { throw new RpcException( "Failed to invoke remote proxy method " + invocation.getMethodName() + " to " + getUrl() + ", cause: " + e.getMessage(), e); } finally { if (ProfilerSwitch.isEnableSimpleProfiler()) { Object fromInvocation = invocation.get(Profiler.PROFILER_KEY); if (fromInvocation instanceof ProfilerEntry) { ProfilerEntry profiler = Profiler.release((ProfilerEntry) fromInvocation); invocation.put(Profiler.PROFILER_KEY, profiler); } } Profiler.removeBizProfiler(); if (originEntry != null) { Profiler.setToBizProfiler(originEntry); } } } private CompletableFuture<Object> wrapWithFuture(Object value, Invocation invocation) { if (value instanceof CompletableFuture) { invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE); return (CompletableFuture<Object>) value; } else if (RpcContext.getServerAttachment().isAsyncStarted()) { invocation.put(PROVIDER_ASYNC_KEY, Boolean.TRUE); return ((AsyncContextImpl) (RpcContext.getServerAttachment().getAsyncContext())).getInternalFuture(); } return CompletableFuture.completedFuture(value); } protected abstract Object doInvoke(T proxy, String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Throwable; @Override public String toString() { return getInterface() + " -> " + (getUrl() == null ? " " : getUrl().toString()); } }
AbstractProxyInvoker
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/TypesOfThings.java
{ "start": 197, "end": 249 }
enum ____ { PUPPIES, RAINDROPS, SMOKE }
TypesOfThings
java
spring-projects__spring-framework
spring-oxm/src/main/java/org/springframework/oxm/GenericUnmarshaller.java
{ "start": 822, "end": 1225 }
interface ____ extends Unmarshaller { /** * Indicates whether this marshaller can marshal instances of the supplied generic type. * @param genericType the type that this marshaller is being asked if it can marshal * @return {@code true} if this marshaller can indeed marshal instances of the supplied type; * {@code false} otherwise */ boolean supports(Type genericType); }
GenericUnmarshaller
java
quarkusio__quarkus
integration-tests/spring-data-jpa/src/test/java/io/quarkus/it/spring/data/jpa/CustomerResourceIT.java
{ "start": 125, "end": 183 }
class ____ extends CustomerResourceTest { }
CustomerResourceIT
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/metrics/CommandMetrics.java
{ "start": 250, "end": 1732 }
class ____ { private final long count; private final TimeUnit timeUnit; private final CommandLatency firstResponse; private final CommandLatency completion; public CommandMetrics(long count, TimeUnit timeUnit, CommandLatency firstResponse, CommandLatency completion) { this.count = count; this.timeUnit = timeUnit; this.firstResponse = firstResponse; this.completion = completion; } /** * * @return the count */ public long getCount() { return count; } /** * * @return the time unit for the {@link #getFirstResponse()} and {@link #getCompletion()} latencies. */ public TimeUnit getTimeUnit() { return timeUnit; } /** * * @return latencies between send and the first command response */ public CommandLatency getFirstResponse() { return firstResponse; } /** * * @return latencies between send and the command completion */ public CommandLatency getCompletion() { return completion; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("[count=").append(count); sb.append(", timeUnit=").append(timeUnit); sb.append(", firstResponse=").append(firstResponse); sb.append(", completion=").append(completion); sb.append(']'); return sb.toString(); } public static
CommandMetrics
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/models/partitions/ClusterPartitionParser.java
{ "start": 11518, "end": 11776 }
class ____ { private final Map<String, Object> map; public KeyValueMap(Map<String, Object> map) { this.map = map; } public <T> T get(String key) { return (T) map.get(key); } } }
KeyValueMap
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/MapValueSupplier.java
{ "start": 230, "end": 540 }
class ____<T> implements Supplier<T> { private final Map<String, T> map; private final String key; public MapValueSupplier(Map<String, T> map, String key) { this.map = map; this.key = key; } @Override public T get() { return map.get(key); } }
MapValueSupplier
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_330.java
{ "start": 264, "end": 833 }
class ____ extends TestCase { public void test_for_issue() throws Exception { String jsonContent = "{\"data\":{\"content\":\"xxx\",\"hour\":1}}"; StatusBean<WorkBean> bean = JSONObject.parseObject(jsonContent, new TypeReference<StatusBean<WorkBean>>() { }); Assert.assertNotNull(bean.getData()); Assert.assertEquals(1, bean.getData().getHour()); Assert.assertEquals("xxx", bean.getData().getContent()); } public static
Bug_for_issue_330
java
google__dagger
javatests/dagger/functional/cycle/Cycles.java
{ "start": 3012, "end": 3584 }
class ____ { @Provides static Object provideObjectWithCycle( @SuppressWarnings("unused") // TODO(b/438800095): This parameter was renamed from "object" to "obj" because "object" is // a keyword in Kotlin (which will fail if Kotlin codegen is enabled). However, we should // probably work around this on the codegen side rather than letting the compiler fail. // See b/438800095 for more details. Provider<Object> obj) { return "object"; } } @SuppressWarnings("dependency-cycle") @Component
CycleModule
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3089/Issue3089Test.java
{ "start": 1391, "end": 1995 }
class ____ { @ProcessorTest public void shouldIgnorePutterOfMap() { Map<String, String> attributesMap = new HashMap<>(); attributesMap.put( "a", "b" ); attributesMap.put( "c", "d" ); ItemDTO item = ImmutableItemDTO.builder() .id( "test" ) .attributes( attributesMap ) .build(); Item target = ItemMapper.INSTANCE.map( item ); assertThat( target ).isNotNull(); assertThat( target.getId() ).isEqualTo( "test" ); assertThat( target.getAttributes() ).isEqualTo( attributesMap ); } }
Issue3089Test
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/config/AbstractListenerContainerParser.java
{ "start": 1745, "end": 14018 }
class ____ implements BeanDefinitionParser { protected static final String FACTORY_ID_ATTRIBUTE = "factory-id"; protected static final String LISTENER_ELEMENT = "listener"; protected static final String ID_ATTRIBUTE = "id"; protected static final String DESTINATION_ATTRIBUTE = "destination"; protected static final String SUBSCRIPTION_ATTRIBUTE = "subscription"; protected static final String SELECTOR_ATTRIBUTE = "selector"; protected static final String REF_ATTRIBUTE = "ref"; protected static final String METHOD_ATTRIBUTE = "method"; protected static final String DESTINATION_RESOLVER_ATTRIBUTE = "destination-resolver"; protected static final String MESSAGE_CONVERTER_ATTRIBUTE = "message-converter"; protected static final String RESPONSE_DESTINATION_ATTRIBUTE = "response-destination"; protected static final String DESTINATION_TYPE_ATTRIBUTE = "destination-type"; protected static final String DESTINATION_TYPE_QUEUE = "queue"; protected static final String DESTINATION_TYPE_TOPIC = "topic"; protected static final String DESTINATION_TYPE_DURABLE_TOPIC = "durableTopic"; protected static final String DESTINATION_TYPE_SHARED_TOPIC = "sharedTopic"; protected static final String DESTINATION_TYPE_SHARED_DURABLE_TOPIC = "sharedDurableTopic"; protected static final String RESPONSE_DESTINATION_TYPE_ATTRIBUTE = "response-destination-type"; protected static final String CLIENT_ID_ATTRIBUTE = "client-id"; protected static final String ACKNOWLEDGE_ATTRIBUTE = "acknowledge"; protected static final String ACKNOWLEDGE_AUTO = "auto"; protected static final String ACKNOWLEDGE_CLIENT = "client"; protected static final String ACKNOWLEDGE_DUPS_OK = "dups-ok"; protected static final String ACKNOWLEDGE_TRANSACTED = "transacted"; protected static final String TRANSACTION_MANAGER_ATTRIBUTE = "transaction-manager"; protected static final String CONCURRENCY_ATTRIBUTE = "concurrency"; protected static final String PHASE_ATTRIBUTE = "phase"; protected static final String PREFETCH_ATTRIBUTE = "prefetch"; @Override public @Nullable BeanDefinition parse(Element element, ParserContext parserContext) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), parserContext.extractSource(element)); parserContext.pushContainingComponent(compositeDef); MutablePropertyValues commonProperties = parseCommonContainerProperties(element, parserContext); MutablePropertyValues specificProperties = parseSpecificContainerProperties(element, parserContext); String factoryId = element.getAttribute(FACTORY_ID_ATTRIBUTE); if (StringUtils.hasText(factoryId)) { RootBeanDefinition beanDefinition = createContainerFactory( factoryId, element, parserContext, commonProperties, specificProperties); if (beanDefinition != null) { beanDefinition.setSource(parserContext.extractSource(element)); parserContext.registerBeanComponent(new BeanComponentDefinition(beanDefinition, factoryId)); } } NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node child = childNodes.item(i); if (child.getNodeType() == Node.ELEMENT_NODE) { String localName = parserContext.getDelegate().getLocalName(child); if (LISTENER_ELEMENT.equals(localName)) { parseListener(element, (Element) child, parserContext, commonProperties, specificProperties); } } } parserContext.popAndRegisterContainingComponent(); return null; } private void parseListener(Element containerEle, Element listenerEle, ParserContext parserContext, MutablePropertyValues commonContainerProperties, PropertyValues specificContainerProperties) { RootBeanDefinition listenerDef = new RootBeanDefinition(); listenerDef.setSource(parserContext.extractSource(listenerEle)); listenerDef.setBeanClassName("org.springframework.jms.listener.adapter.MessageListenerAdapter"); String ref = listenerEle.getAttribute(REF_ATTRIBUTE); if (!StringUtils.hasText(ref)) { parserContext.getReaderContext().error( "Listener 'ref' attribute contains empty value.", listenerEle); } else { listenerDef.getPropertyValues().add("delegate", new RuntimeBeanReference(ref)); } if (listenerEle.hasAttribute(METHOD_ATTRIBUTE)) { String method = listenerEle.getAttribute(METHOD_ATTRIBUTE); if (!StringUtils.hasText(method)) { parserContext.getReaderContext().error( "Listener 'method' attribute contains empty value.", listenerEle); } listenerDef.getPropertyValues().add("defaultListenerMethod", method); } PropertyValue messageConverterPv = commonContainerProperties.getPropertyValue("messageConverter"); if (messageConverterPv != null) { listenerDef.getPropertyValues().addPropertyValue(messageConverterPv); } BeanDefinition containerDef = createContainer( containerEle, listenerEle, parserContext, commonContainerProperties, specificContainerProperties); containerDef.getPropertyValues().add("messageListener", listenerDef); if (listenerEle.hasAttribute(RESPONSE_DESTINATION_ATTRIBUTE)) { String responseDestination = listenerEle.getAttribute(RESPONSE_DESTINATION_ATTRIBUTE); Boolean pubSubDomain = (Boolean) commonContainerProperties.get("replyPubSubDomain"); if (pubSubDomain == null) { pubSubDomain = false; } listenerDef.getPropertyValues().add( pubSubDomain ? "defaultResponseTopicName" : "defaultResponseQueueName", responseDestination); PropertyValue destinationResolver = containerDef.getPropertyValues().getPropertyValue("destinationResolver"); if (destinationResolver != null) { listenerDef.getPropertyValues().addPropertyValue(destinationResolver); } } String containerBeanName = listenerEle.getAttribute(ID_ATTRIBUTE); // If no bean id is given auto generate one using the ReaderContext's BeanNameGenerator if (!StringUtils.hasText(containerBeanName)) { containerBeanName = parserContext.getReaderContext().generateBeanName(containerDef); } // Register the listener and fire event parserContext.registerBeanComponent(new BeanComponentDefinition(containerDef, containerBeanName)); } protected void parseListenerConfiguration(Element ele, ParserContext parserContext, MutablePropertyValues configValues) { String destination = ele.getAttribute(DESTINATION_ATTRIBUTE); if (!StringUtils.hasText(destination)) { parserContext.getReaderContext().error( "Listener 'destination' attribute contains empty value.", ele); } configValues.add("destinationName", destination); if (ele.hasAttribute(SUBSCRIPTION_ATTRIBUTE)) { String subscription = ele.getAttribute(SUBSCRIPTION_ATTRIBUTE); if (!StringUtils.hasText(subscription)) { parserContext.getReaderContext().error( "Listener 'subscription' attribute contains empty value.", ele); } configValues.add("subscriptionName", subscription); } if (ele.hasAttribute(SELECTOR_ATTRIBUTE)) { String selector = ele.getAttribute(SELECTOR_ATTRIBUTE); if (!StringUtils.hasText(selector)) { parserContext.getReaderContext().error( "Listener 'selector' attribute contains empty value.", ele); } configValues.add("messageSelector", selector); } if (ele.hasAttribute(CONCURRENCY_ATTRIBUTE)) { String concurrency = ele.getAttribute(CONCURRENCY_ATTRIBUTE); if (!StringUtils.hasText(concurrency)) { parserContext.getReaderContext().error( "Listener 'concurrency' attribute contains empty value.", ele); } configValues.add("concurrency", concurrency); } } protected MutablePropertyValues parseCommonContainerProperties(Element containerEle, ParserContext parserContext) { MutablePropertyValues properties = new MutablePropertyValues(); String destinationType = containerEle.getAttribute(DESTINATION_TYPE_ATTRIBUTE); boolean pubSubDomain = false; boolean subscriptionDurable = false; boolean subscriptionShared = false; if (DESTINATION_TYPE_SHARED_DURABLE_TOPIC.equals(destinationType)) { pubSubDomain = true; subscriptionDurable = true; subscriptionShared = true; } else if (DESTINATION_TYPE_SHARED_TOPIC.equals(destinationType)) { pubSubDomain = true; subscriptionShared = true; } else if (DESTINATION_TYPE_DURABLE_TOPIC.equals(destinationType)) { pubSubDomain = true; subscriptionDurable = true; } else if (DESTINATION_TYPE_TOPIC.equals(destinationType)) { pubSubDomain = true; } else if (!StringUtils.hasLength(destinationType) || DESTINATION_TYPE_QUEUE.equals(destinationType)) { // the default: queue } else { parserContext.getReaderContext().error("Invalid listener container 'destination-type': only " + "\"queue\", \"topic\", \"durableTopic\", \"sharedTopic\", \"sharedDurableTopic\" supported.", containerEle); } properties.add("pubSubDomain", pubSubDomain); properties.add("subscriptionDurable", subscriptionDurable); properties.add("subscriptionShared", subscriptionShared); boolean replyPubSubDomain = false; String replyDestinationType = containerEle.getAttribute(RESPONSE_DESTINATION_TYPE_ATTRIBUTE); if (!StringUtils.hasText(replyDestinationType)) { replyPubSubDomain = pubSubDomain; // the default: same value as pubSubDomain } else if (DESTINATION_TYPE_TOPIC.equals(replyDestinationType)) { replyPubSubDomain = true; } else if (!DESTINATION_TYPE_QUEUE.equals(replyDestinationType)) { parserContext.getReaderContext().error("Invalid listener container 'response-destination-type': only " + "\"queue\", \"topic\" supported.", containerEle); } properties.add("replyPubSubDomain", replyPubSubDomain); if (containerEle.hasAttribute(CLIENT_ID_ATTRIBUTE)) { String clientId = containerEle.getAttribute(CLIENT_ID_ATTRIBUTE); if (!StringUtils.hasText(clientId)) { parserContext.getReaderContext().error( "Listener 'client-id' attribute contains empty value.", containerEle); } properties.add("clientId", clientId); } if (containerEle.hasAttribute(MESSAGE_CONVERTER_ATTRIBUTE)) { String messageConverter = containerEle.getAttribute(MESSAGE_CONVERTER_ATTRIBUTE); if (!StringUtils.hasText(messageConverter)) { parserContext.getReaderContext().error( "listener container 'message-converter' attribute contains empty value.", containerEle); } else { properties.add("messageConverter", new RuntimeBeanReference(messageConverter)); } } return properties; } /** * Parse the common properties for all listeners as defined by the specified * container {@link Element}. */ protected abstract MutablePropertyValues parseSpecificContainerProperties(Element containerEle, ParserContext parserContext); /** * Create the {@link BeanDefinition} for the container factory using the specified * shared property values. */ protected abstract @Nullable RootBeanDefinition createContainerFactory(String factoryId, Element containerEle, ParserContext parserContext, PropertyValues commonContainerProperties, PropertyValues specificContainerProperties); /** * Create the container {@link BeanDefinition} for the specified context. */ protected abstract RootBeanDefinition createContainer(Element containerEle, Element listenerEle, ParserContext parserContext, PropertyValues commonContainerProperties, PropertyValues specificContainerProperties); protected @Nullable Integer parseAcknowledgeMode(Element ele, ParserContext parserContext) { String acknowledge = ele.getAttribute(ACKNOWLEDGE_ATTRIBUTE); if (StringUtils.hasText(acknowledge)) { int acknowledgeMode = Session.AUTO_ACKNOWLEDGE; if (ACKNOWLEDGE_TRANSACTED.equals(acknowledge)) { acknowledgeMode = Session.SESSION_TRANSACTED; } else if (ACKNOWLEDGE_DUPS_OK.equals(acknowledge)) { acknowledgeMode = Session.DUPS_OK_ACKNOWLEDGE; } else if (ACKNOWLEDGE_CLIENT.equals(acknowledge)) { acknowledgeMode = Session.CLIENT_ACKNOWLEDGE; } else if (!ACKNOWLEDGE_AUTO.equals(acknowledge)) { parserContext.getReaderContext().error("Invalid listener container 'acknowledge' setting [" + acknowledge + "]: only \"auto\", \"client\", \"dups-ok\" and \"transacted\" supported.", ele); } return acknowledgeMode; } else { return null; } } }
AbstractListenerContainerParser
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java
{ "start": 18894, "end": 19074 }
class ____ { @Bean Integer testBean() { return 1; } } @Configuration(proxyBeanMethods = false) @ConditionalOnBean(String.class) static
OverridingDefinitionConfiguration
java
spring-projects__spring-boot
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/FilteredClassLoader.java
{ "start": 1341, "end": 1960 }
class ____ extends URLClassLoader implements SmartClassLoader { private final Collection<Predicate<String>> classesFilters; private final Collection<Predicate<String>> resourcesFilters; /** * Create a {@link FilteredClassLoader} that hides the given classes. * @param hiddenClasses the classes to hide */ public FilteredClassLoader(Class<?>... hiddenClasses) { this(Collections.singleton(ClassFilter.of(hiddenClasses)), Collections.emptyList()); } /** * Create a {@link FilteredClassLoader} with the given {@code parent} that hides the * given classes. * @param parent the parent
FilteredClassLoader
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/internal/arrays2d/Arrays2D_assertNotEmpty_Test.java
{ "start": 1395, "end": 2703 }
class ____ extends Arrays2D_BaseTest { @Test void should_fail_if_actual_is_null() { // GIVEN int[][] actual = null; // WHEN var assertionError = expectAssertionError(() -> arrays.assertNotEmpty(someInfo(), failures, actual)); // THEN then(assertionError).hasMessage(shouldNotBeNull().create()); } @ParameterizedTest @MethodSource("should_fail_if_actual_is_empty_parameters") void should_fail_if_actual_is_empty(Object[][] actual) { // WHEN var assertionError = expectAssertionError(() -> arrays.assertNotEmpty(someInfo(), failures, actual)); // THEN then(assertionError).hasMessage(shouldNotBeEmpty().create()); } static Stream<String[][]> should_fail_if_actual_is_empty_parameters() { // some arrays have multiple rows but no elements in them return Stream.of(new String[][] {}, new String[][] { {} }, new String[][] { {} }, new String[][] { {}, {}, {} }); } @Test void should_pass_if_actual_is_not_empty() { arrays.assertNotEmpty(someInfo(), failures, new int[][] { { 1 }, { 2 } }); arrays.assertNotEmpty(someInfo(), failures, new int[][] { { 1 }, {} }); arrays.assertNotEmpty(someInfo(), failures, new int[][] { {}, { 2 } }); } }
Arrays2D_assertNotEmpty_Test
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/db/DBOutputFormat.java
{ "start": 1573, "end": 1815 }
class ____<K extends DBWritable, V> extends org.apache.hadoop.mapreduce.lib.db.DBOutputFormat<K, V> implements OutputFormat<K, V> { /** * A RecordWriter that writes the reduce output to a SQL table */ protected
DBOutputFormat
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/util/ExpressionListComparatorTest.java
{ "start": 1297, "end": 1533 }
class ____ implements Expression { @Override @SuppressWarnings("unchecked") public <T> T evaluate(Exchange exchange, Class<T> type) { return (T) "foo"; } } private static
MyFooExpression
java
apache__camel
tooling/camel-util-json/src/main/java/org/apache/camel/util/json/JsonObject.java
{ "start": 1401, "end": 14411 }
class ____ compatible with. This value doesn't need to be incremented if and only if * the only changes to occur were updating comments, updating javadocs, adding new fields to the class, changing the * fields from static to non-static, or changing the fields from transient to non transient. All other changes * require this number be incremented. */ private static final long serialVersionUID = 1L; /** Instantiates an empty JsonObject. */ public JsonObject() { } /** * Instantiate a new JsonObject by accepting a map's entries, which could lead to de/serialization issues of the * resulting JsonObject since the entry values aren't validated as JSON values. * * @param map represents the mappings to produce the JsonObject with. */ public JsonObject(final Map<String, ?> map) { super(map); } /** * A convenience method that assumes there is a BigDecimal, Number, or String at the given key. If a Number is there * its Number#toString() is used to construct a new BigDecimal(String). If a String is there it is used to construct * a new BigDecimal(String). * * @param key representing where the value ought to be stored at. * @return the value stored at the key. * @throws ClassCastException if the value didn't match the assumed return type. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see BigDecimal * @see Number#toString() */ public BigDecimal getBigDecimal(final String key) { Object returnable = this.get(key); if (returnable instanceof BigDecimal) { /* Success there was a BigDecimal or it defaulted. */ } else if (returnable instanceof Number) { /* A number can be used to construct a BigDecimal */ returnable = new BigDecimal(returnable.toString()); } else if (returnable instanceof String) { /* A number can be used to construct a BigDecimal */ returnable = new BigDecimal((String) returnable); } return (BigDecimal) returnable; } /** * A convenience method that assumes there is a BigDecimal, Number, or String at the given key. If a Number is there * its Number#toString() is used to construct a new BigDecimal(String). If a String is there it is used to construct * a new BigDecimal(String). * * @param key representing where the value ought to be stored at. * @param defaultValue representing what is returned when the key isn't in the JsonObject. * @return the value stored at the key or the default provided if the key doesn't exist. * @throws ClassCastException if there was a value but didn't match the assumed return types. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see BigDecimal * @see Number#toString() */ public BigDecimal getBigDecimalOrDefault(final String key, final BigDecimal defaultValue) { Object returnable; if (this.containsKey(key)) { returnable = this.get(key); } else { return defaultValue; } if (returnable instanceof BigDecimal) { /* Success there was a BigDecimal or it defaulted. */ } else if (returnable instanceof Number) { /* A number can be used to construct a BigDecimal */ returnable = new BigDecimal(returnable.toString()); } else if (returnable instanceof String) { /* A String can be used to construct a BigDecimal */ returnable = new BigDecimal((String) returnable); } return (BigDecimal) returnable; } /** * A convenience method that assumes there is a Boolean or String value at the given key. * * @param key representing where the value ought to be stored at. * @return the value stored at the key. * @throws ClassCastException if the value didn't match the assumed return type. */ public Boolean getBoolean(final String key) { Object returnable = this.get(key); if (returnable instanceof String) { returnable = Boolean.valueOf((String) returnable); } return (Boolean) returnable; } /** * A convenience method that assumes there is a Boolean or String value at the given key. * * @param key representing where the value ought to be stored at. * @param defaultValue representing what is returned when the key isn't in the JsonObject. * @return the value stored at the key or the default provided if the key doesn't exist. * @throws ClassCastException if there was a value but didn't match the assumed return type. */ public Boolean getBooleanOrDefault(final String key, final boolean defaultValue) { Object returnable; if (this.containsKey(key)) { returnable = this.get(key); } else { return defaultValue; } if (returnable instanceof String) { returnable = Boolean.valueOf((String) returnable); } return (Boolean) returnable; } /** * A convenience method that assumes there is a Number or String value at the given key. * * @param key representing where the value ought to be stored at. * @return the value stored at the key (which may involve rounding or truncation). * @throws ClassCastException if the value didn't match the assumed return type. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see Number#byteValue() */ public Byte getByte(final String key) { Object returnable = this.get(key); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String) returnable); } return ((Number) returnable).byteValue(); } /** * A convenience method that assumes there is a Number or String value at the given key. * * @param key representing where the value ought to be stored at. * @param defaultValue representing what is returned when the key isn't in the JsonObject. * @return the value stored at the key (which may involve rounding or truncation) or the * default provided if the key doesn't exist. * @throws ClassCastException if there was a value but didn't match the assumed return type. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see Number#byteValue() */ public Byte getByteOrDefault(final String key, final byte defaultValue) { Object returnable; if (this.containsKey(key)) { returnable = this.get(key); } else { return defaultValue; } if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String) returnable); } return ((Number) returnable).byteValue(); } /** * A convenience method that assumes there is a Collection at the given key. * * @param <T> the kind of collection to expect at the key. Note unless manually added, collection * values will be a JsonArray. * @param key representing where the value ought to be stored at. * @return the value stored at the key. * @throws ClassCastException if the value didn't match the assumed return type. */ @SuppressWarnings("unchecked") public <T extends Collection<?>> T getCollection(final String key) { /* * The unchecked warning is suppressed because there is no way of * guaranteeing at compile time the cast will work. */ return (T) this.get(key); } /** * A convenience method that assumes there is a Collection at the given key. * * @param <T> the kind of collection to expect at the key. Note unless manually added, collection * values will be a JsonArray. * @param key representing where the value ought to be stored at. * @param defaultValue representing what is returned when the key isn't in the JsonObject. * @return the value stored at the key or the default provided if the key doesn't exist. * @throws ClassCastException if there was a value but didn't match the assumed return type. */ @SuppressWarnings("unchecked") public <T extends Collection<?>> T getCollectionOrDefault(final String key, final T defaultValue) { /* * The unchecked warning is suppressed because there is no way of * guaranteeing at compile time the cast will work. */ Object returnable; if (this.containsKey(key)) { returnable = this.get(key); } else { return defaultValue; } return (T) returnable; } /** * A convenience method that assumes there is a Number or String value at the given key. * * @param key representing where the value ought to be stored at. * @return the value stored at the key (which may involve rounding or truncation). * @throws ClassCastException if the value didn't match the assumed return type. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see Number#doubleValue() */ public Double getDouble(final String key) { Object returnable = this.get(key); if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String) returnable); } return ((Number) returnable).doubleValue(); } /** * A convenience method that assumes there is a Number or String value at the given key. * * @param key representing where the value ought to be stored at. * @param defaultValue representing what is returned when the key isn't in the JsonObject. * @return the value stored at the key (which may involve rounding or truncation) or the * default provided if the key doesn't exist. * @throws ClassCastException if there was a value but didn't match the assumed return type. * @throws NumberFormatException if a String isn't a valid representation of a BigDecimal or if the Number * represents the double or float Infinity or NaN. * @see Number#doubleValue() */ public Double getDoubleOrDefault(final String key, final double defaultValue) { Object returnable; if (this.containsKey(key)) { returnable = this.get(key); } else { return defaultValue; } if (returnable == null) { return null; } if (returnable instanceof String) { /* A String can be used to construct a BigDecimal. */ returnable = new BigDecimal((String) returnable); } return ((Number) returnable).doubleValue(); } /** * A convenience method that assumes there is a String value at the given key representing a fully qualified name in * dot notation of an enum. * * @param key representing where the value ought to be stored at. * @param <T> the Enum type the value at the key is expected to belong to. * @return the
is