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
|
spring-projects__spring-data-jpa
|
spring-data-envers/src/test/java/org/springframework/data/envers/sample/License.java
|
{
"start": 958,
"end": 1446
}
|
class ____ extends AbstractEntity {
@Version public Integer version;
public String name;
@ManyToMany public Set<Country> laender;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
License license = (License) o;
return Objects.equals(version, license.version) && Objects.equals(name, license.name);
}
@Override
public int hashCode() {
return Objects.hash(version, name);
}
}
|
License
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/literal/CriteriaLiteralHandlingModeInlineShortNameLowercaseTest.java
|
{
"start": 387,
"end": 842
}
|
class ____ extends AbstractCriteriaLiteralHandlingModeTest {
@Override
protected Map getConfig() {
Map config = super.getConfig();
config.put(
AvailableSettings.CRITERIA_VALUE_HANDLING_MODE,
"inline"
);
return config;
}
protected String expectedSQL() {
return "select 'abc',b1_0.name from Book b1_0 where b1_0.id=1 and b1_0.name='Vlad''s High-Performance Java Persistence'";
}
}
|
CriteriaLiteralHandlingModeInlineShortNameLowercaseTest
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/LoggedNetworkTopology.java
|
{
"start": 2514,
"end": 5419
}
|
class ____ implements Comparator<LoggedNetworkTopology>,
Serializable {
public int compare(LoggedNetworkTopology t1, LoggedNetworkTopology t2) {
return t1.name.getValue().compareTo(t2.name.getValue());
}
}
/**
* @param hosts
* a HashSet of the {@link ParsedHost}
* @param name
* the name of this level's host [for recursive descent]
* @param level
* the level number
*/
LoggedNetworkTopology(Set<ParsedHost> hosts, String name, int level) {
if (name == null) {
this.name = NodeName.ROOT;
} else {
this.name = new NodeName(name);
}
this.children = null;
if (level < ParsedHost.numberOfDistances() - 1) {
HashMap<String, HashSet<ParsedHost>> topologies =
new HashMap<String, HashSet<ParsedHost>>();
Iterator<ParsedHost> iter = hosts.iterator();
while (iter.hasNext()) {
ParsedHost host = iter.next();
String thisComponent = host.nameComponent(level);
HashSet<ParsedHost> thisSet = topologies.get(thisComponent);
if (thisSet == null) {
thisSet = new HashSet<ParsedHost>();
topologies.put(thisComponent, thisSet);
}
thisSet.add(host);
}
children = new ArrayList<LoggedNetworkTopology>();
for (Map.Entry<String, HashSet<ParsedHost>> ent : topologies.entrySet()) {
children.add(new LoggedNetworkTopology(ent.getValue(), ent.getKey(),
level + 1));
}
} else {
// nothing to do here
}
}
LoggedNetworkTopology(Set<ParsedHost> hosts) {
this(hosts, null, 0);
}
public NodeName getName() {
return name;
}
void setName(String name) {
this.name = new NodeName(name);
}
public List<LoggedNetworkTopology> getChildren() {
return children;
}
void setChildren(List<LoggedNetworkTopology> children) {
this.children = children;
}
private void compare1(List<LoggedNetworkTopology> c1,
List<LoggedNetworkTopology> c2, TreePath loc, String eltname)
throws DeepInequalityException {
if (c1 == null && c2 == null) {
return;
}
if (c1 == null || c2 == null || c1.size() != c2.size()) {
throw new DeepInequalityException(eltname + " miscompared", new TreePath(
loc, eltname));
}
Collections.sort(c1, new TopoSort());
Collections.sort(c2, new TopoSort());
for (int i = 0; i < c1.size(); ++i) {
c1.get(i).deepCompare(c2.get(i), new TreePath(loc, eltname, i));
}
}
public void deepCompare(DeepCompare comparand, TreePath loc)
throws DeepInequalityException {
if (!(comparand instanceof LoggedNetworkTopology)) {
throw new DeepInequalityException("comparand has wrong type", loc);
}
LoggedNetworkTopology other = (LoggedNetworkTopology) comparand;
compare1(children, other.children, loc, "children");
}
}
|
TopoSort
|
java
|
spring-projects__spring-framework
|
spring-tx/src/test/java/org/springframework/transaction/JndiJtaTransactionManagerTests.java
|
{
"start": 1471,
"end": 8369
}
|
class ____ {
@Test
void jtaTransactionManagerWithDefaultJndiLookups1() throws Exception {
doTestJtaTransactionManagerWithDefaultJndiLookups("java:comp/TransactionManager", true, true);
}
@Test
void jtaTransactionManagerWithDefaultJndiLookups2() throws Exception {
doTestJtaTransactionManagerWithDefaultJndiLookups("java:/TransactionManager", true, true);
}
@Test
void jtaTransactionManagerWithDefaultJndiLookupsAndNoTmFound() throws Exception {
doTestJtaTransactionManagerWithDefaultJndiLookups("java:/tm", false, true);
}
@Test
void jtaTransactionManagerWithDefaultJndiLookupsAndNoUtFound() throws Exception {
doTestJtaTransactionManagerWithDefaultJndiLookups("java:/TransactionManager", true, false);
}
private void doTestJtaTransactionManagerWithDefaultJndiLookups(String tmName, boolean tmFound, boolean defaultUt)
throws Exception {
UserTransaction ut = mock();
TransactionManager tm = mock();
if (defaultUt) {
given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
else {
given(tm.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
}
JtaTransactionManager ptm = new JtaTransactionManager();
ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate();
if (defaultUt) {
jndiTemplate.addObject("java:comp/UserTransaction", ut);
}
jndiTemplate.addObject(tmName, tm);
ptm.setJndiTemplate(jndiTemplate);
ptm.afterPropertiesSet();
if (tmFound) {
assertThat(ptm.getTransactionManager()).isEqualTo(tm);
}
else {
assertThat(ptm.getTransactionManager()).isNull();
}
if (defaultUt) {
assertThat(ptm.getUserTransaction()).isEqualTo(ut);
}
else {
boolean condition = ptm.getUserTransaction() instanceof UserTransactionAdapter;
assertThat(condition).isTrue();
UserTransactionAdapter uta = (UserTransactionAdapter) ptm.getUserTransaction();
assertThat(uta.getTransactionManager()).isEqualTo(tm);
}
TransactionTemplate tt = new TransactionTemplate(ptm);
boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition1).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
tt.executeWithoutResult(status -> {
// something transactional
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
});
boolean condition = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
if (defaultUt) {
verify(ut).begin();
verify(ut).commit();
}
else {
verify(tm).begin();
verify(tm).commit();
}
}
@Test
void jtaTransactionManagerWithCustomJndiLookups() throws Exception {
UserTransaction ut = mock();
given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
TransactionManager tm = mock();
JtaTransactionManager ptm = new JtaTransactionManager();
ptm.setUserTransactionName("jndi-ut");
ptm.setTransactionManagerName("jndi-tm");
ExpectedLookupTemplate jndiTemplate = new ExpectedLookupTemplate();
jndiTemplate.addObject("jndi-ut", ut);
jndiTemplate.addObject("jndi-tm", tm);
ptm.setJndiTemplate(jndiTemplate);
ptm.afterPropertiesSet();
assertThat(ptm.getUserTransaction()).isEqualTo(ut);
assertThat(ptm.getTransactionManager()).isEqualTo(tm);
TransactionTemplate tt = new TransactionTemplate(ptm);
boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition1).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
tt.executeWithoutResult(status -> {
// something transactional
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
});
boolean condition = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
verify(ut).begin();
verify(ut).commit();
}
@Test
void jtaTransactionManagerWithNotCacheUserTransaction() throws Exception {
UserTransaction ut = mock();
given(ut.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
UserTransaction ut2 = mock();
given(ut2.getStatus()).willReturn(Status.STATUS_NO_TRANSACTION, Status.STATUS_ACTIVE, Status.STATUS_ACTIVE);
JtaTransactionManager ptm = new JtaTransactionManager();
ptm.setJndiTemplate(new ExpectedLookupTemplate("java:comp/UserTransaction", ut));
ptm.setCacheUserTransaction(false);
ptm.afterPropertiesSet();
assertThat(ptm.getUserTransaction()).isEqualTo(ut);
TransactionTemplate tt = new TransactionTemplate(ptm);
assertThat(ptm.getTransactionSynchronization()).isEqualTo(JtaTransactionManager.SYNCHRONIZATION_ALWAYS);
boolean condition1 = !TransactionSynchronizationManager.isSynchronizationActive();
assertThat(condition1).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
tt.executeWithoutResult(status -> {
// something transactional
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
});
ptm.setJndiTemplate(new ExpectedLookupTemplate("java:comp/UserTransaction", ut2));
tt.executeWithoutResult(status -> {
// something transactional
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
});
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
verify(ut).begin();
verify(ut).commit();
verify(ut2).begin();
verify(ut2).commit();
}
/**
* Prevent any side effects due to this test modifying ThreadLocals that might
* affect subsequent tests when all tests are run in the same JVM, as with Eclipse.
*/
@AfterEach
void tearDown() {
assertThat(TransactionSynchronizationManager.getResourceMap()).isEmpty();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
assertThat(TransactionSynchronizationManager.getCurrentTransactionName()).isNull();
assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()).isFalse();
assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
}
}
|
JndiJtaTransactionManagerTests
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/enums/EnumAsMapKeySerializationTest.java
|
{
"start": 2763,
"end": 3115
}
|
enum ____ {
A,
B() {
// just to ensure subclass construction
@Override
public void foo() { }
};
// needed to force subclassing
public void foo() { }
@Override
public String toString() { return name() + " as string"; }
}
// [databind#2457]
|
MyEnum2457
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/common/requests/AlterReplicaLogDirsRequestTest.java
|
{
"start": 1808,
"end": 5000
}
|
class ____ {
@Test
public void testErrorResponse() {
AlterReplicaLogDirsRequestData data = new AlterReplicaLogDirsRequestData()
.setDirs(new AlterReplicaLogDirCollection(
singletonList(new AlterReplicaLogDir()
.setPath("/data0")
.setTopics(new AlterReplicaLogDirTopicCollection(
singletonList(new AlterReplicaLogDirTopic()
.setName("topic")
.setPartitions(asList(0, 1, 2))).iterator()))).iterator()));
AlterReplicaLogDirsResponse errorResponse = new AlterReplicaLogDirsRequest.Builder(data).build()
.getErrorResponse(123, new LogDirNotFoundException("/data0"));
assertEquals(1, errorResponse.data().results().size());
AlterReplicaLogDirTopicResult topicResponse = errorResponse.data().results().get(0);
assertEquals("topic", topicResponse.topicName());
assertEquals(3, topicResponse.partitions().size());
for (int i = 0; i < 3; i++) {
assertEquals(i, topicResponse.partitions().get(i).partitionIndex());
assertEquals(Errors.LOG_DIR_NOT_FOUND.code(), topicResponse.partitions().get(i).errorCode());
}
}
@Test
public void testPartitionDir() {
AlterReplicaLogDirsRequestData data = new AlterReplicaLogDirsRequestData()
.setDirs(new AlterReplicaLogDirCollection(
asList(new AlterReplicaLogDir()
.setPath("/data0")
.setTopics(new AlterReplicaLogDirTopicCollection(
asList(new AlterReplicaLogDirTopic()
.setName("topic")
.setPartitions(asList(0, 1)),
new AlterReplicaLogDirTopic()
.setName("topic2")
.setPartitions(singletonList(7))).iterator())),
new AlterReplicaLogDir()
.setPath("/data1")
.setTopics(new AlterReplicaLogDirTopicCollection(
singletonList(new AlterReplicaLogDirTopic()
.setName("topic3")
.setPartitions(singletonList(12))).iterator()))).iterator()));
AlterReplicaLogDirsRequest request = new AlterReplicaLogDirsRequest.Builder(data).build();
Map<TopicPartition, String> expect = new HashMap<>();
expect.put(new TopicPartition("topic", 0), "/data0");
expect.put(new TopicPartition("topic", 1), "/data0");
expect.put(new TopicPartition("topic2", 7), "/data0");
expect.put(new TopicPartition("topic3", 12), "/data1");
assertEquals(expect, request.partitionDirs());
}
}
|
AlterReplicaLogDirsRequestTest
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/CanonicalDurationTest.java
|
{
"start": 1344,
"end": 1884
}
|
class ____ {
static final int CONST = 86400;
{
Duration.ofSeconds(86400);
java.time.Duration.ofSeconds(86400);
Duration.ofSeconds(CONST);
Duration.ofMillis(0);
Duration.ofMillis(4611686018427387904L);
Duration.ofDays(1);
}
}
""")
.addOutputLines(
"out/A.java",
"""
package a;
import java.time.Duration;
public
|
A
|
java
|
spring-projects__spring-framework
|
spring-aop/src/main/java/org/springframework/aop/ClassFilter.java
|
{
"start": 1600,
"end": 1673
}
|
interface ____ {
/**
* Should the pointcut apply to the given
|
ClassFilter
|
java
|
apache__camel
|
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/JettyXsltHttpTemplateTest.java
|
{
"start": 1161,
"end": 2546
}
|
class ____ extends CamelTestSupport {
private int port;
@Test
void testXsltHttpTemplate() throws Exception {
// give Jetty a bit time to startup and be ready
Thread.sleep(1000);
String xml = template.requestBody("xslt:http://0.0.0.0:" + port + "/myxslt",
"<mail><subject>Hey</subject><body>Hello world!</body></mail>", String.class);
assertNotNull(xml, "The transformed XML should not be null");
assertTrue(xml.contains("transformed"));
// the cheese tag is in the transform.xsl
assertTrue(xml.contains("cheese"));
assertTrue(xml.contains("<subject>Hey</subject>"));
assertTrue(xml.contains("<body>Hello world!</body>"));
}
@Override
protected RouteBuilder createRouteBuilder() {
port = AvailablePortFinder.getNextAvailable();
return new RouteBuilder() {
@Override
public void configure() {
from("jetty:http://0.0.0.0:" + port + "/myxslt")
.pollEnrich(
"file://src/test/resources/org/apache/camel/component/jetty/?fileName=transform.xsl&noop=true&readLock=none",
2000)
.convertBodyTo(String.class)
.to("log:transform");
}
};
}
}
|
JettyXsltHttpTemplateTest
|
java
|
netty__netty
|
codec-base/src/main/java/io/netty/handler/codec/string/LineSeparator.java
|
{
"start": 840,
"end": 919
}
|
class ____ represent line separators in different environments.
*/
public final
|
to
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/stateless/events/CollectionListenerInStatelessSessionTest.java
|
{
"start": 2703,
"end": 3030
}
|
class ____ implements PreCollectionRemoveEventListener {
int called = 0;
@Override
public void onPreRemoveCollection(PreCollectionRemoveEvent event) {
assertThat( event.getAffectedOwnerOrNull() ).isNotNull();
assertThat( event.getCollection().getOwner() ).isNotNull();
called++;
}
}
|
MyPreCollectionRemoveEventListener
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/kstream/TimeWindowedDeserializerTest.java
|
{
"start": 1624,
"end": 8182
}
|
class ____ {
private final long windowSize = 5000000;
private final TimeWindowedDeserializer<?> timeWindowedDeserializer = new TimeWindowedDeserializer<>(new StringDeserializer(), windowSize);
private final Map<String, String> props = new HashMap<>();
@Test
public void testTimeWindowedDeserializerConstructor() {
timeWindowedDeserializer.configure(props, true);
final Deserializer<?> inner = timeWindowedDeserializer.innerDeserializer();
assertNotNull(inner, "Inner deserializer should be not null");
assertInstanceOf(StringDeserializer.class, inner, "Inner deserializer type should be StringDeserializer");
assertThat(timeWindowedDeserializer.getWindowSize(), is(5000000L));
}
@Deprecated
@Test
public void shouldSetWindowSizeAndDeserializerThroughWindowSizeMsAndWindowedInnerClassSerdeConfigs() {
props.put(StreamsConfig.WINDOW_SIZE_MS_CONFIG, "500");
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, Serdes.ByteArraySerde.class.getName());
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
deserializer.configure(props, false);
assertThat(deserializer.getWindowSize(), is(500L));
assertInstanceOf(ByteArrayDeserializer.class, deserializer.innerDeserializer());
}
}
@Test
public void shouldSetWindowSizeAndDeserializerThroughWindowSizeMsAndWindowedInnerDeserializerClassConfigs() {
props.put(TimeWindowedDeserializer.WINDOW_SIZE_MS_CONFIG, "500");
props.put(TimeWindowedDeserializer.WINDOWED_INNER_DESERIALIZER_CLASS, Serdes.ByteArraySerde.class.getName());
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
deserializer.configure(props, false);
assertThat(deserializer.getWindowSize(), is(500L));
assertInstanceOf(ByteArrayDeserializer.class, deserializer.innerDeserializer());
}
}
@Deprecated
@Test
public void shouldHaveSameConfigNameForWindowSizeMs() {
assertEquals(TimeWindowedDeserializer.WINDOW_SIZE_MS_CONFIG, StreamsConfig.WINDOW_SIZE_MS_CONFIG);
}
@Deprecated
@Test
public void shouldIgnoreWindowedInnerClassSerdeConfigIfWindowedInnerDeserializerClassConfigIsSet() {
props.put(TimeWindowedDeserializer.WINDOW_SIZE_MS_CONFIG, "500");
props.put(TimeWindowedDeserializer.WINDOWED_INNER_DESERIALIZER_CLASS, Serdes.ByteArraySerde.class.getName());
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
deserializer.configure(props, false);
assertThat(deserializer.getWindowSize(), is(500L));
assertInstanceOf(ByteArrayDeserializer.class, deserializer.innerDeserializer());
}
}
@Deprecated
@Test
public void shouldThrowErrorIfWindowSizeSetInStreamsConfigAndConstructor() {
props.put(StreamsConfig.WINDOW_SIZE_MS_CONFIG, "500");
assertThrows(IllegalArgumentException.class, () -> timeWindowedDeserializer.configure(props, false));
}
@Test
public void shouldThrowErrorIfWindowSizeSetInConstructorConfigAndConstructor() {
props.put(TimeWindowedDeserializer.WINDOW_SIZE_MS_CONFIG, "500");
assertThrows(IllegalArgumentException.class, () -> timeWindowedDeserializer.configure(props, false));
}
@Deprecated
@Test
public void shouldThrowErrorIfWindowSizeIsNotSetAndWindowedInnerClassSerdeIsSet() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, Serdes.ByteArraySerde.class.getName());
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(props, false));
}
}
@Test
public void shouldThrowErrorIfWindowSizeIsNotSetAndWindowedInnerDeserializerClassIsSet() {
props.put(TimeWindowedDeserializer.WINDOWED_INNER_DESERIALIZER_CLASS, Serdes.ByteArraySerde.class.getName());
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(props, false));
}
}
@Deprecated
@Test
public void shouldThrowErrorIfWindowedInnerClassSerdeIsNotSetAndWindowSizeMsInStreamsConfigIsSet() {
props.put(StreamsConfig.WINDOW_SIZE_MS_CONFIG, "500");
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(props, false));
}
}
@Test
public void shouldThrowErrorIfWindowedInnerClassSerdeIsNotSetAndWindowSizeMsInConstructorConfigIsSet() {
props.put(TimeWindowedDeserializer.WINDOW_SIZE_MS_CONFIG, "500");
try (final TimeWindowedDeserializer<?> deserializer = new TimeWindowedDeserializer<>()) {
assertThrows(IllegalArgumentException.class, () -> deserializer.configure(props, false));
}
}
@Deprecated
@Test
public void shouldThrowErrorIfDeserializerConflictInConstructorAndWindowedInnerClassSerdeConfig() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, Serdes.ByteArraySerde.class.getName());
assertThrows(IllegalArgumentException.class, () -> timeWindowedDeserializer.configure(props, false));
}
@Test
public void shouldThrowErrorIfDeserializerConflictInConstructorAndWindowedInnerDeserializerClassConfig() {
props.put(TimeWindowedDeserializer.WINDOWED_INNER_DESERIALIZER_CLASS, Serdes.ByteArraySerde.class.getName());
assertThrows(IllegalArgumentException.class, () -> timeWindowedDeserializer.configure(props, false));
}
@Deprecated
@Test
public void shouldThrowConfigExceptionWhenInvalidWindowedInnerClassSerdeSupplied() {
props.put(StreamsConfig.WINDOWED_INNER_CLASS_SERDE, "some.non.existent.class");
assertThrows(ConfigException.class, () -> timeWindowedDeserializer.configure(props, false));
}
@Test
public void shouldThrowConfigExceptionWhenInvalidWindowedInnerDeserializerClassSupplied() {
props.put(TimeWindowedDeserializer.WINDOWED_INNER_DESERIALIZER_CLASS, "some.non.existent.class");
assertThrows(ConfigException.class, () -> timeWindowedDeserializer.configure(props, false));
}
}
|
TimeWindowedDeserializerTest
|
java
|
apache__camel
|
components/camel-oauth/src/main/java/org/apache/camel/oauth/AuthCodeCredentials.java
|
{
"start": 843,
"end": 1611
}
|
class ____ extends Credentials {
private String code;
private String state;
private String redirectUri;
public AuthCodeCredentials() {
setFlowType(OAuthFlowType.AUTH_CODE);
}
public String getCode() {
return code;
}
public AuthCodeCredentials setCode(String code) {
this.code = code;
return this;
}
public String getState() {
return state;
}
public AuthCodeCredentials setState(String state) {
this.state = state;
return this;
}
public String getRedirectUri() {
return redirectUri;
}
public AuthCodeCredentials setRedirectUri(String redirectUri) {
this.redirectUri = redirectUri;
return this;
}
}
|
AuthCodeCredentials
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/CustomEntityDirtinessStrategy.java
|
{
"start": 931,
"end": 1034
}
|
interface ____ by entities which keep track of
* their own modified fields:
* <pre>
* public
|
implemented
|
java
|
grpc__grpc-java
|
api/src/main/java/io/grpc/StatusException.java
|
{
"start": 939,
"end": 2064
}
|
class ____ extends Exception {
private static final long serialVersionUID = -660954903976144640L;
@SuppressWarnings("serial") // https://github.com/grpc/grpc-java/issues/1913
private final Status status;
@SuppressWarnings("serial")
private final Metadata trailers;
/**
* Constructs an exception with both a status. See also {@link Status#asException()}.
*
* @since 1.0.0
*/
public StatusException(Status status) {
this(status, null);
}
/**
* Constructs an exception with both a status and trailers. See also
* {@link Status#asException(Metadata)}.
*
* @since 1.0.0
*/
public StatusException(Status status, @Nullable Metadata trailers) {
super(Status.formatThrowableMessage(status), status.getCause());
this.status = status;
this.trailers = trailers;
}
/**
* Returns the status code as a {@link Status} object.
*
* @since 1.0.0
*/
public final Status getStatus() {
return status;
}
/**
* Returns the received trailers.
*
* @since 1.0.0
*/
public final Metadata getTrailers() {
return trailers;
}
}
|
StatusException
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/spec/JoinSpec.java
|
{
"start": 1561,
"end": 1688
}
|
class ____ to {@link org.apache.calcite.rel.core.Join} rel node.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public
|
corresponds
|
java
|
google__truth
|
core/src/test/java/com/google/common/truth/DoubleSubjectTest.java
|
{
"start": 1348,
"end": 23094
}
|
class ____ {
private static final double NEARLY_MAX = 1.7976931348623155E308;
private static final double NEGATIVE_NEARLY_MAX = -1.7976931348623155E308;
private static final double OVER_MIN = 9.9E-324;
private static final double UNDER_NEGATIVE_MIN = -9.9E-324;
private static final double GOLDEN = 1.23;
private static final double OVER_GOLDEN = 1.2300000000000002;
@Test
@GwtIncompatible("Math.nextAfter")
public void doubleConstants_matchNextAfter() {
assertThat(Math.nextAfter(Double.MIN_VALUE, 1.0)).isEqualTo(OVER_MIN);
assertThat(Math.nextAfter(1.23, POSITIVE_INFINITY)).isEqualTo(OVER_GOLDEN);
assertThat(Math.nextAfter(Double.MAX_VALUE, 0.0)).isEqualTo(NEARLY_MAX);
assertThat(Math.nextAfter(-1.0 * Double.MAX_VALUE, 0.0)).isEqualTo(NEGATIVE_NEARLY_MAX);
assertThat(Math.nextAfter(-1.0 * Double.MIN_VALUE, -1.0)).isEqualTo(UNDER_NEGATIVE_MIN);
}
@Test
public void j2clCornerCaseZero() {
// GWT considers -0.0 to be equal to 0.0. But we've added a special workaround inside Truth.
assertThatIsEqualToFails(-0.0, 0.0);
}
@Test
@GwtIncompatible("GWT behavior difference")
public void j2clCornerCaseDoubleVsFloat() {
// Under GWT, 1.23f.toString() is different than 1.23d.toString(), so the message omits types.
// TODO(b/35377736): Consider making Truth add the types manually.
AssertionError e = expectFailure(whenTesting -> whenTesting.that(1.23).isEqualTo(1.23f));
assertFailureKeys(e, "expected", "an instance of", "but was", "an instance of");
}
@Test
public void isWithinOf() {
assertThat(2.0).isWithin(0.0).of(2.0);
assertThat(2.0).isWithin(0.00001).of(2.0);
assertThat(2.0).isWithin(1000.0).of(2.0);
assertThat(2.0).isWithin(1.00001).of(3.0);
assertThatIsWithinFails(2.0, 0.99999, 3.0);
assertThatIsWithinFails(2.0, 1000.0, 1003.0);
assertThatIsWithinFailsForNonFiniteExpected(2.0, 1000.0, POSITIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteExpected(2.0, 1000.0, NaN);
assertThatIsWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 1000.0, 2.0);
assertThatIsWithinFailsForNonFiniteActual(NaN, 1000.0, 2.0);
}
private static void assertThatIsWithinFails(double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isWithin(tolerance).of(expected));
assertThat(e).factKeys().containsExactly("expected", "but was", "outside tolerance").inOrder();
assertThat(e).factValue("expected").isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("but was").isEqualTo(formatNumericValue(actual));
assertThat(e).factValue("outside tolerance").isEqualTo(formatNumericValue(tolerance));
}
private static void assertThatIsWithinFailsForNonFiniteExpected(
double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isWithin(tolerance).of(expected));
assertThat(e)
.factKeys()
.containsExactly(
"could not perform approximate-equality check because expected value was not finite",
"expected",
"was",
"tolerance")
.inOrder();
assertThat(e).factValue("expected").isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("was").isEqualTo(formatNumericValue(actual));
assertThat(e).factValue("tolerance").isEqualTo(formatNumericValue(tolerance));
}
private static void assertThatIsWithinFailsForNonFiniteActual(
double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isWithin(tolerance).of(expected));
assertThat(e)
.factKeys()
.containsExactly("expected a finite value near", "but was", "tolerance")
.inOrder();
assertThat(e).factValue("expected a finite value near").isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("but was").isEqualTo(formatNumericValue(actual));
assertThat(e).factValue("tolerance").isEqualTo(formatNumericValue(tolerance));
}
@Test
public void isNotWithinOf() {
assertThatIsNotWithinFails(2.0, 0.0, 2.0);
assertThatIsNotWithinFails(2.0, 0.00001, 2.0);
assertThatIsNotWithinFails(2.0, 1000.0, 2.0);
assertThatIsNotWithinFails(2.0, 1.00001, 3.0);
assertThat(2.0).isNotWithin(0.99999).of(3.0);
assertThat(2.0).isNotWithin(1000.0).of(1003.0);
assertThatIsNotWithinFailsForNonFiniteExpected(2.0, 0.0, POSITIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteExpected(2.0, 0.0, NaN);
assertThatIsNotWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 1000.0, 2.0);
assertThatIsNotWithinFailsForNonFiniteActual(NaN, 1000.0, 2.0);
}
private static void assertThatIsNotWithinFails(double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isNotWithin(tolerance).of(expected));
assertThat(e).factValue("expected not to be").isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("within tolerance").isEqualTo(formatNumericValue(tolerance));
}
private static void assertThatIsNotWithinFailsForNonFiniteExpected(
double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isNotWithin(tolerance).of(expected));
assertThat(e)
.factKeys()
.containsExactly(
"could not perform approximate-equality check because expected value was not finite",
"expected not to be",
"was",
"tolerance");
assertThat(e).factValue("expected not to be").isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("was").isEqualTo(formatNumericValue(actual));
assertThat(e).factValue("tolerance").isEqualTo(formatNumericValue(tolerance));
}
private static void assertThatIsNotWithinFailsForNonFiniteActual(
double actual, double tolerance, double expected) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(actual).isNotWithin(tolerance).of(expected));
assertThat(e)
.factValue("expected a finite value that is not near")
.isEqualTo(formatNumericValue(expected));
assertThat(e).factValue("tolerance").isEqualTo(formatNumericValue(tolerance));
}
@Test
public void negativeTolerances() {
isWithinNegativeToleranceThrows(-0.5);
isNotWithinNegativeToleranceThrows(-0.5);
// You know what's worse than zero? Negative zero.
isWithinNegativeToleranceThrows(-0.0);
isNotWithinNegativeToleranceThrows(-0.0);
}
private static void isWithinNegativeToleranceThrows(double tolerance) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(5.0).isWithin(tolerance).of(5.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was negative",
"expected",
"was",
"tolerance");
}
private static void isNotWithinNegativeToleranceThrows(double tolerance) {
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(5.0).isNotWithin(tolerance).of(5.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was negative",
"expected not to be",
"was",
"tolerance");
}
@Test
public void nanTolerances() {
{
AssertionError e = expectFailure(whenTesting -> whenTesting.that(1.0).isWithin(NaN).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected",
"was",
"tolerance");
}
{
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(1.0).isNotWithin(NaN).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected not to be",
"was",
"tolerance");
}
}
@Test
public void positiveInfinityTolerances() {
{
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(1.0).isWithin(POSITIVE_INFINITY).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected",
"was",
"tolerance");
}
{
AssertionError e =
expectFailure(
whenTesting -> whenTesting.that(1.0).isNotWithin(POSITIVE_INFINITY).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected not to be",
"was",
"tolerance");
}
}
@SuppressWarnings("FloatingPointAssertionWithinEpsilon") // test of a bogus call
@Test
public void negativeInfinityTolerances() {
{
AssertionError e =
expectFailure(whenTesting -> whenTesting.that(1.0).isWithin(NEGATIVE_INFINITY).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected",
"was",
"tolerance");
}
{
AssertionError e =
expectFailure(
whenTesting -> whenTesting.that(1.0).isNotWithin(NEGATIVE_INFINITY).of(1.0));
assertFailureKeys(
e,
"could not perform approximate-equality check because tolerance was not finite",
"expected not to be",
"was",
"tolerance");
}
}
@Test
public void isWithinOfZero() {
assertThat(+0.0).isWithin(0.00001).of(+0.0);
assertThat(+0.0).isWithin(0.00001).of(-0.0);
assertThat(-0.0).isWithin(0.00001).of(+0.0);
assertThat(-0.0).isWithin(0.00001).of(-0.0);
assertThat(+0.0).isWithin(0.0).of(+0.0);
assertThat(+0.0).isWithin(0.0).of(-0.0);
assertThat(-0.0).isWithin(0.0).of(+0.0);
assertThat(-0.0).isWithin(0.0).of(-0.0);
}
@Test
public void isNotWithinOfZero() {
assertThat(+0.0).isNotWithin(0.00001).of(+1.0);
assertThat(+0.0).isNotWithin(0.00001).of(-1.0);
assertThat(-0.0).isNotWithin(0.00001).of(+1.0);
assertThat(-0.0).isNotWithin(0.00001).of(-1.0);
assertThat(+1.0).isNotWithin(0.00001).of(+0.0);
assertThat(+1.0).isNotWithin(0.00001).of(-0.0);
assertThat(-1.0).isNotWithin(0.00001).of(+0.0);
assertThat(-1.0).isNotWithin(0.00001).of(-0.0);
assertThat(+1.0).isNotWithin(0.0).of(+0.0);
assertThat(+1.0).isNotWithin(0.0).of(-0.0);
assertThat(-1.0).isNotWithin(0.0).of(+0.0);
assertThat(-1.0).isNotWithin(0.0).of(-0.0);
assertThatIsNotWithinFails(-0.0, 0.0, 0.0);
}
@Test
public void isWithinZeroTolerance() {
double max = Double.MAX_VALUE;
assertThat(max).isWithin(0.0).of(max);
assertThat(NEARLY_MAX).isWithin(0.0).of(NEARLY_MAX);
assertThatIsWithinFails(max, 0.0, NEARLY_MAX);
assertThatIsWithinFails(NEARLY_MAX, 0.0, max);
double negativeMax = -1.0 * Double.MAX_VALUE;
assertThat(negativeMax).isWithin(0.0).of(negativeMax);
assertThat(NEGATIVE_NEARLY_MAX).isWithin(0.0).of(NEGATIVE_NEARLY_MAX);
assertThatIsWithinFails(negativeMax, 0.0, NEGATIVE_NEARLY_MAX);
assertThatIsWithinFails(NEGATIVE_NEARLY_MAX, 0.0, negativeMax);
double min = Double.MIN_VALUE;
assertThat(min).isWithin(0.0).of(min);
assertThat(OVER_MIN).isWithin(0.0).of(OVER_MIN);
assertThatIsWithinFails(min, 0.0, OVER_MIN);
assertThatIsWithinFails(OVER_MIN, 0.0, min);
double negativeMin = -1.0 * Double.MIN_VALUE;
assertThat(negativeMin).isWithin(0.0).of(negativeMin);
assertThat(UNDER_NEGATIVE_MIN).isWithin(0.0).of(UNDER_NEGATIVE_MIN);
assertThatIsWithinFails(negativeMin, 0.0, UNDER_NEGATIVE_MIN);
assertThatIsWithinFails(UNDER_NEGATIVE_MIN, 0.0, negativeMin);
}
@Test
public void isNotWithinZeroTolerance() {
double max = Double.MAX_VALUE;
assertThatIsNotWithinFails(max, 0.0, max);
assertThatIsNotWithinFails(NEARLY_MAX, 0.0, NEARLY_MAX);
assertThat(max).isNotWithin(0.0).of(NEARLY_MAX);
assertThat(NEARLY_MAX).isNotWithin(0.0).of(max);
double min = Double.MIN_VALUE;
assertThatIsNotWithinFails(min, 0.0, min);
assertThatIsNotWithinFails(OVER_MIN, 0.0, OVER_MIN);
assertThat(min).isNotWithin(0.0).of(OVER_MIN);
assertThat(OVER_MIN).isNotWithin(0.0).of(min);
}
@Test
public void isWithinNonFinite() {
assertThatIsWithinFailsForNonFiniteExpected(NaN, 0.00001, NaN);
assertThatIsWithinFailsForNonFiniteExpected(NaN, 0.00001, POSITIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteExpected(NaN, 0.00001, NEGATIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteActual(NaN, 0.00001, +0.0);
assertThatIsWithinFailsForNonFiniteActual(NaN, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteActual(NaN, 0.00001, +1.0);
assertThatIsWithinFailsForNonFiniteActual(NaN, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteExpected(POSITIVE_INFINITY, 0.00001, POSITIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteExpected(POSITIVE_INFINITY, 0.00001, NEGATIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, +0.0);
assertThatIsWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, +1.0);
assertThatIsWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteExpected(NEGATIVE_INFINITY, 0.00001, NEGATIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, +0.0);
assertThatIsWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, +1.0);
assertThatIsWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, -0.0);
assertThatIsWithinFailsForNonFiniteExpected(+1.0, 0.00001, NaN);
assertThatIsWithinFailsForNonFiniteExpected(+1.0, 0.00001, POSITIVE_INFINITY);
assertThatIsWithinFailsForNonFiniteExpected(+1.0, 0.00001, NEGATIVE_INFINITY);
}
@Test
public void isNotWithinNonFinite() {
assertThatIsNotWithinFailsForNonFiniteExpected(NaN, 0.00001, NaN);
assertThatIsNotWithinFailsForNonFiniteExpected(NaN, 0.00001, POSITIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteExpected(NaN, 0.00001, NEGATIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteActual(NaN, 0.00001, +0.0);
assertThatIsNotWithinFailsForNonFiniteActual(NaN, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteActual(NaN, 0.00001, +1.0);
assertThatIsNotWithinFailsForNonFiniteActual(NaN, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteExpected(POSITIVE_INFINITY, 0.00001, POSITIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteExpected(POSITIVE_INFINITY, 0.00001, NEGATIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, +0.0);
assertThatIsNotWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, +1.0);
assertThatIsNotWithinFailsForNonFiniteActual(POSITIVE_INFINITY, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteExpected(NEGATIVE_INFINITY, 0.00001, NEGATIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, +0.0);
assertThatIsNotWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, +1.0);
assertThatIsNotWithinFailsForNonFiniteActual(NEGATIVE_INFINITY, 0.00001, -0.0);
assertThatIsNotWithinFailsForNonFiniteExpected(+1.0, 0.00001, NaN);
assertThatIsNotWithinFailsForNonFiniteExpected(+1.0, 0.00001, POSITIVE_INFINITY);
assertThatIsNotWithinFailsForNonFiniteExpected(+1.0, 0.00001, NEGATIVE_INFINITY);
}
@SuppressWarnings({"TruthSelfEquals", "PositiveInfinity", "NaN"})
@Test
public void isEqualTo() {
assertThat(1.23).isEqualTo(1.23);
assertThatIsEqualToFails(GOLDEN, OVER_GOLDEN);
assertThat(POSITIVE_INFINITY).isEqualTo(POSITIVE_INFINITY);
assertThat(NaN).isEqualTo(NaN);
assertThat((Double) null).isEqualTo(null);
assertThat(1.0).isEqualTo(1);
}
private static void assertThatIsEqualToFails(double actual, double expected) {
expectFailure(whenTesting -> whenTesting.that(actual).isEqualTo(expected));
}
@Test
public void isNotEqualTo() {
assertThatIsNotEqualToFails(1.23);
assertThat(GOLDEN).isNotEqualTo(OVER_GOLDEN);
assertThatIsNotEqualToFails(POSITIVE_INFINITY);
assertThatIsNotEqualToFails(NaN);
assertThat(-0.0).isNotEqualTo(0.0);
assertThatIsNotEqualToFails(null);
assertThat(1.23).isNotEqualTo(1.23f);
assertThat(1.0).isNotEqualTo(2);
}
@SuppressWarnings("SelfAssertion")
private static void assertThatIsNotEqualToFails(@Nullable Double value) {
expectFailure(whenTesting -> whenTesting.that(value).isNotEqualTo(value));
}
@Test
public void isZero() {
assertThat(0.0).isZero();
assertThat(-0.0).isZero();
assertThatIsZeroFails(Double.MIN_VALUE);
assertThatIsZeroFails(-1.23);
assertThatIsZeroFails(POSITIVE_INFINITY);
assertThatIsZeroFails(NaN);
assertThatIsZeroFails(null);
}
private static void assertThatIsZeroFails(@Nullable Double value) {
AssertionError e = expectFailure(whenTesting -> whenTesting.that(value).isZero());
assertThat(e).factKeys().containsExactly("expected zero", "but was").inOrder();
}
@Test
public void isNonZero() {
assertThatIsNonZeroFails(0.0, "expected not to be zero");
assertThatIsNonZeroFails(-0.0, "expected not to be zero");
assertThat(Double.MIN_VALUE).isNonZero();
assertThat(-1.23).isNonZero();
assertThat(POSITIVE_INFINITY).isNonZero();
assertThat(NaN).isNonZero();
assertThatIsNonZeroFails(null, "expected a double other than zero");
}
private static void assertThatIsNonZeroFails(@Nullable Double value, String factKey) {
AssertionError e = expectFailure(whenTesting -> whenTesting.that(value).isNonZero());
assertThat(e).factKeys().containsExactly(factKey, "but was").inOrder();
}
@Test
public void isPositiveInfinity() {
assertThat(POSITIVE_INFINITY).isPositiveInfinity();
assertThatIsPositiveInfinityFails(1.23);
assertThatIsPositiveInfinityFails(NEGATIVE_INFINITY);
assertThatIsPositiveInfinityFails(NaN);
assertThatIsPositiveInfinityFails(null);
}
private static void assertThatIsPositiveInfinityFails(@Nullable Double value) {
expectFailure(whenTesting -> whenTesting.that(value).isPositiveInfinity());
}
@Test
public void isNegativeInfinity() {
assertThat(NEGATIVE_INFINITY).isNegativeInfinity();
assertThatIsNegativeInfinityFails(1.23);
assertThatIsNegativeInfinityFails(POSITIVE_INFINITY);
assertThatIsNegativeInfinityFails(NaN);
assertThatIsNegativeInfinityFails(null);
}
private static void assertThatIsNegativeInfinityFails(@Nullable Double value) {
expectFailure(whenTesting -> whenTesting.that(value).isNegativeInfinity());
}
@Test
public void isNaN() {
assertThat(NaN).isNaN();
assertThatIsNaNFails(1.23);
assertThatIsNaNFails(POSITIVE_INFINITY);
assertThatIsNaNFails(NEGATIVE_INFINITY);
assertThatIsNaNFails(null);
}
private static void assertThatIsNaNFails(@Nullable Double value) {
expectFailure(whenTesting -> whenTesting.that(value).isNaN());
}
@Test
public void isFinite() {
assertThat(1.23).isFinite();
assertThat(Double.MAX_VALUE).isFinite();
assertThat(-1.0 * Double.MIN_VALUE).isFinite();
assertThatIsFiniteFails(POSITIVE_INFINITY);
assertThatIsFiniteFails(NEGATIVE_INFINITY);
assertThatIsFiniteFails(NaN);
assertThatIsFiniteFails(null);
}
private static void assertThatIsFiniteFails(@Nullable Double value) {
AssertionError e = expectFailure(whenTesting -> whenTesting.that(value).isFinite());
assertThat(e).factKeys().containsExactly("expected to be finite", "but was").inOrder();
}
@Test
public void isNotNaN() {
assertThat(1.23).isNotNaN();
assertThat(Double.MAX_VALUE).isNotNaN();
assertThat(-1.0 * Double.MIN_VALUE).isNotNaN();
assertThat(POSITIVE_INFINITY).isNotNaN();
assertThat(NEGATIVE_INFINITY).isNotNaN();
}
@Test
public void isNotNaNIsNaN() {
expectFailure(whenTesting -> whenTesting.that(NaN).isNotNaN());
}
@Test
public void isNotNaNIsNull() {
AssertionError e = expectFailure(whenTesting -> whenTesting.that((Double) null).isNotNaN());
assertFailureKeys(e, "expected a double other than NaN", "but was");
}
@Test
public void isGreaterThan_int_strictly() {
expectFailure(whenTesting -> whenTesting.that(2.0).isGreaterThan(3));
}
@Test
public void isGreaterThan_int() {
expectFailure(whenTesting -> whenTesting.that(2.0).isGreaterThan(2));
assertThat(2.0).isGreaterThan(1);
}
@Test
public void isLessThan_int_strictly() {
expectFailure(whenTesting -> whenTesting.that(2.0).isLessThan(1));
}
@Test
public void isLessThan_int() {
expectFailure(whenTesting -> whenTesting.that(2.0).isLessThan(2));
assertThat(2.0).isLessThan(3);
}
@Test
public void isAtLeast_int() {
expectFailure(whenTesting -> whenTesting.that(2.0).isAtLeast(3));
assertThat(2.0).isAtLeast(2);
assertThat(2.0).isAtLeast(1);
}
@Test
public void isAtMost_int() {
expectFailure(whenTesting -> whenTesting.that(2.0).isAtMost(1));
assertThat(2.0).isAtMost(2);
assertThat(2.0).isAtMost(3);
}
}
|
DoubleSubjectTest
|
java
|
jhy__jsoup
|
src/main/java/org/jsoup/select/Evaluator.java
|
{
"start": 8626,
"end": 9321
}
|
class ____ extends AttributeKeyPair {
public AttributeWithValueStarting(String key, String value) {
super(key, value);
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && lowerCase(element.attr(key)).startsWith(value); // value is lower case already
}
@Override protected int cost() {
return 4;
}
@Override
public String toString() {
return String.format("[%s^=%s]", key, value);
}
}
/**
* Evaluator for attribute name/value matching (value ending)
*/
public static final
|
AttributeWithValueStarting
|
java
|
apache__maven
|
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3297DependenciesNotLeakedToMojoTest.java
|
{
"start": 1154,
"end": 2144
}
|
class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that project dependencies resolved for one mojo are not exposed to another mojo if the latter
* does not require dependency resolution.
*
* @throws Exception in case of failure
*/
@Test
public void testit() throws Exception {
File testDir = extractResources("/mng-3297");
Verifier verifier = newVerifier(testDir.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("initialize");
verifier.execute();
verifier.verifyErrorFreeLog();
List<String> artifacts = verifier.loadLines("target/artifacts.txt");
assertEquals(1, artifacts.size(), artifacts.toString());
Properties props = verifier.loadProperties("target/artifact.properties");
assertEquals("0", props.getProperty("project.artifacts"));
}
}
|
MavenITmng3297DependenciesNotLeakedToMojoTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/LazyCollectionValidationTest.java
|
{
"start": 1344,
"end": 3819
}
|
class ____ {
@AfterAll
public void cleanup(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
entityManager.createQuery( "delete from enumuser" ).executeUpdate();
entityManager.createQuery( "delete from stringuser" ).executeUpdate();
entityManager.createQuery( "delete from stringuserrole" ).executeUpdate();
} );
}
@Test
public void testWithEnumCollection(EntityManagerFactoryScope scope) {
scope.inTransaction( entityManager -> {
UserWithEnumRoles a = new UserWithEnumRoles();
a.setUserRoles( EnumSet.of( EnumUserRole.USER ) );
entityManager.persist( a );
UserWithEnumRoles user = new UserWithEnumRoles();
user.setUserRoles( EnumSet.of( EnumUserRole.USER ) );
user.setCreatedBy( a );
entityManager.persist( user );
} );
scope.inTransaction( entityManager -> {
for ( UserWithEnumRoles user : entityManager.createQuery(
"Select u from enumuser u",
UserWithEnumRoles.class
).getResultList() ) {
entityManager.remove( user );
}
} );
}
@Test
public void testWithNormalCollection(EntityManagerFactoryScope scope) {
final Set<StringUserRole> bosses = scope.fromTransaction( entityManager -> {
StringUserRole role1 = new StringUserRole( 1, "Boss" );
StringUserRole role2 = new StringUserRole( 2, "SuperBoss" );
entityManager.persist( role1 );
entityManager.persist( role2 );
return Set.of( role1, role2 );
} );
final Set<StringUserRole> dorks = scope.fromTransaction( entityManager -> {
StringUserRole role1 = new StringUserRole( 3, "Dork" );
StringUserRole role2 = new StringUserRole( 4, "SuperDork" );
entityManager.persist( role1 );
entityManager.persist( role2 );
return Set.of( role1, role2 );
} );
scope.inTransaction( entityManager -> {
UserWithStringRoles a = new UserWithStringRoles();
a.setUserRoles( bosses );
entityManager.persist( a );
UserWithStringRoles userWithEnumRoles = new UserWithStringRoles();
userWithEnumRoles.setUserRoles( dorks );
userWithEnumRoles.setCreatedBy( a );
entityManager.persist( userWithEnumRoles );
} );
scope.inTransaction( entityManager -> {
for ( UserWithStringRoles userWithStringRoles : entityManager.createQuery(
"Select u from stringuser u",
UserWithStringRoles.class
).getResultList() ) {
entityManager.remove( userWithStringRoles );
}
} );
}
@Entity( name = "enumuser" )
@Table( name = "enum_user" )
public static
|
LazyCollectionValidationTest
|
java
|
mybatis__mybatis-3
|
src/main/java/org/apache/ibatis/executor/BaseExecutor.java
|
{
"start": 2007,
"end": 12621
}
|
class ____ implements Executor {
private static final Log log = LogFactory.getLog(BaseExecutor.class);
protected Transaction transaction;
protected Executor wrapper;
protected ConcurrentLinkedQueue<DeferredLoad> deferredLoads;
protected PerpetualCache localCache;
protected PerpetualCache localOutputParameterCache;
protected Configuration configuration;
protected int queryStack;
private boolean closed;
protected BaseExecutor(Configuration configuration, Transaction transaction) {
this.transaction = transaction;
this.deferredLoads = new ConcurrentLinkedQueue<>();
this.localCache = new PerpetualCache("LocalCache");
this.localOutputParameterCache = new PerpetualCache("LocalOutputParameterCache");
this.closed = false;
this.configuration = configuration;
this.wrapper = this;
}
@Override
public Transaction getTransaction() {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
return transaction;
}
@Override
public void close(boolean forceRollback) {
try {
try {
rollback(forceRollback);
} finally {
if (transaction != null) {
transaction.close();
}
}
} catch (SQLException e) {
// Ignore. There's nothing that can be done at this point.
log.warn("Unexpected exception on closing transaction. Cause: " + e);
} finally {
transaction = null;
deferredLoads = null;
localCache = null;
localOutputParameterCache = null;
closed = true;
}
}
@Override
public boolean isClosed() {
return closed;
}
@Override
public int update(MappedStatement ms, Object parameter) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing an update").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
clearLocalCache();
return doUpdate(ms, parameter);
}
@Override
public List<BatchResult> flushStatements() throws SQLException {
return flushStatements(false);
}
public List<BatchResult> flushStatements(boolean isRollBack) throws SQLException {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
return doFlushStatements(isRollBack);
}
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler)
throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
CacheKey key = createCacheKey(ms, parameter, rowBounds, boundSql);
return query(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
@SuppressWarnings("unchecked")
@Override
public <E> List<E> query(MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler,
CacheKey key, BoundSql boundSql) throws SQLException {
ErrorContext.instance().resource(ms.getResource()).activity("executing a query").object(ms.getId());
if (closed) {
throw new ExecutorException("Executor was closed.");
}
if (queryStack == 0 && ms.isFlushCacheRequired()) {
clearLocalCache();
}
List<E> list;
try {
queryStack++;
list = resultHandler == null ? (List<E>) localCache.getObject(key) : null;
if (list != null) {
handleLocallyCachedOutputParameters(ms, key, parameter, boundSql);
} else {
list = queryFromDatabase(ms, parameter, rowBounds, resultHandler, key, boundSql);
}
} finally {
queryStack--;
}
if (queryStack == 0) {
for (DeferredLoad deferredLoad : deferredLoads) {
deferredLoad.load();
}
// issue #601
deferredLoads.clear();
if (configuration.getLocalCacheScope() == LocalCacheScope.STATEMENT) {
// issue #482
clearLocalCache();
}
}
return list;
}
@Override
public <E> Cursor<E> queryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds) throws SQLException {
BoundSql boundSql = ms.getBoundSql(parameter);
return doQueryCursor(ms, parameter, rowBounds, boundSql);
}
@Override
public void deferLoad(MappedStatement ms, MetaObject resultObject, String property, CacheKey key,
Class<?> targetType) {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
DeferredLoad deferredLoad = new DeferredLoad(resultObject, property, key, localCache, configuration, targetType);
if (deferredLoad.canLoad()) {
deferredLoad.load();
} else {
deferredLoads.add(new DeferredLoad(resultObject, property, key, localCache, configuration, targetType));
}
}
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
if (closed) {
throw new ExecutorException("Executor was closed.");
}
CacheKey cacheKey = new CacheKey();
cacheKey.update(ms.getId());
cacheKey.update(rowBounds.getOffset());
cacheKey.update(rowBounds.getLimit());
cacheKey.update(boundSql.getSql());
List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
// mimic DefaultParameterHandler logic
MetaObject metaObject = null;
for (ParameterMapping parameterMapping : parameterMappings) {
if (parameterMapping.getMode() != ParameterMode.OUT) {
Object value;
String propertyName = parameterMapping.getProperty();
if (parameterMapping.hasValue()) {
value = parameterMapping.getValue();
} else if (boundSql.hasAdditionalParameter(propertyName)) {
value = boundSql.getAdditionalParameter(propertyName);
} else if (parameterObject == null) {
value = null;
} else {
ParamNameResolver paramNameResolver = ms.getParamNameResolver();
if (paramNameResolver != null
&& typeHandlerRegistry.hasTypeHandler(paramNameResolver.getType(paramNameResolver.getNames()[0]))
|| typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
value = parameterObject;
} else {
if (metaObject == null) {
metaObject = configuration.newMetaObject(parameterObject);
}
value = metaObject.getValue(propertyName);
}
}
cacheKey.update(value);
}
}
if (configuration.getEnvironment() != null) {
// issue #176
cacheKey.update(configuration.getEnvironment().getId());
}
return cacheKey;
}
@Override
public boolean isCached(MappedStatement ms, CacheKey key) {
return localCache.getObject(key) != null;
}
@Override
public void commit(boolean required) throws SQLException {
if (closed) {
throw new ExecutorException("Cannot commit, transaction is already closed");
}
clearLocalCache();
flushStatements();
if (required) {
transaction.commit();
}
}
@Override
public void rollback(boolean required) throws SQLException {
if (!closed) {
try {
clearLocalCache();
flushStatements(true);
} finally {
if (required) {
transaction.rollback();
}
}
}
}
@Override
public void clearLocalCache() {
if (!closed) {
localCache.clear();
localOutputParameterCache.clear();
}
}
protected abstract int doUpdate(MappedStatement ms, Object parameter) throws SQLException;
protected abstract List<BatchResult> doFlushStatements(boolean isRollback) throws SQLException;
protected abstract <E> List<E> doQuery(MappedStatement ms, Object parameter, RowBounds rowBounds,
ResultHandler resultHandler, BoundSql boundSql) throws SQLException;
protected abstract <E> Cursor<E> doQueryCursor(MappedStatement ms, Object parameter, RowBounds rowBounds,
BoundSql boundSql) throws SQLException;
protected void closeStatement(Statement statement) {
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// ignore
}
}
}
/**
* Apply a transaction timeout.
*
* @param statement
* a current statement
*
* @throws SQLException
* if a database access error occurs, this method is called on a closed <code>Statement</code>
*
* @since 3.4.0
*
* @see StatementUtil#applyTransactionTimeout(Statement, Integer, Integer)
*/
protected void applyTransactionTimeout(Statement statement) throws SQLException {
StatementUtil.applyTransactionTimeout(statement, statement.getQueryTimeout(), transaction.getTimeout());
}
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter,
BoundSql boundSql) {
if (ms.getStatementType() == StatementType.CALLABLE) {
final Object cachedParameter = localOutputParameterCache.getObject(key);
if (cachedParameter != null && parameter != null) {
final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
final MetaObject metaParameter = configuration.newMetaObject(parameter);
for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
if (parameterMapping.getMode() != ParameterMode.IN) {
final String parameterName = parameterMapping.getProperty();
final Object cachedValue = metaCachedParameter.getValue(parameterName);
metaParameter.setValue(parameterName, cachedValue);
}
}
}
}
}
private <E> List<E> queryFromDatabase(MappedStatement ms, Object parameter, RowBounds rowBounds,
ResultHandler resultHandler, CacheKey key, BoundSql boundSql) throws SQLException {
List<E> list;
localCache.putObject(key, EXECUTION_PLACEHOLDER);
try {
list = doQuery(ms, parameter, rowBounds, resultHandler, boundSql);
} finally {
localCache.removeObject(key);
}
localCache.putObject(key, list);
if (ms.getStatementType() == StatementType.CALLABLE) {
localOutputParameterCache.putObject(key, parameter);
}
return list;
}
protected Connection getConnection(Log statementLog) throws SQLException {
Connection connection = transaction.getConnection();
if (statementLog.isDebugEnabled()) {
return ConnectionLogger.newInstance(connection, statementLog, queryStack);
}
return connection;
}
@Override
public void setExecutorWrapper(Executor wrapper) {
this.wrapper = wrapper;
}
private static
|
BaseExecutor
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/boot/spi/AbstractDelegatingSessionFactoryBuilderImplementor.java
|
{
"start": 473,
"end": 1168
}
|
class ____<T extends SessionFactoryBuilderImplementor>
extends AbstractDelegatingSessionFactoryBuilder<T> implements SessionFactoryBuilderImplementor {
public AbstractDelegatingSessionFactoryBuilderImplementor(SessionFactoryBuilderImplementor delegate) {
super( delegate );
}
@Override
protected SessionFactoryBuilderImplementor delegate() {
return (SessionFactoryBuilderImplementor) super.delegate();
}
@Override
public void disableJtaTransactionAccess() {
delegate().disableJtaTransactionAccess();
}
@Override
public SessionFactoryOptions buildSessionFactoryOptions() {
return delegate().buildSessionFactoryOptions();
}
}
|
AbstractDelegatingSessionFactoryBuilderImplementor
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/JsltEndpointBuilderFactory.java
|
{
"start": 11745,
"end": 14750
}
|
interface ____ {
/**
* JSLT (camel-jslt)
* Query or transform JSON payloads using JSLT.
*
* Category: transformation
* Since: 3.1
* Maven coordinates: org.apache.camel:camel-jslt
*
* @return the dsl builder for the headers' name.
*/
default JsltHeaderNameBuilder jslt() {
return JsltHeaderNameBuilder.INSTANCE;
}
/**
* JSLT (camel-jslt)
* Query or transform JSON payloads using JSLT.
*
* Category: transformation
* Since: 3.1
* Maven coordinates: org.apache.camel:camel-jslt
*
* Syntax: <code>jslt:resourceUri</code>
*
* Path parameter: resourceUri (required)
* Path to the resource. You can prefix with: classpath, file, http,
* ref, or bean. classpath, file and http loads the resource using these
* protocols (classpath is default). ref will lookup the resource in the
* registry. bean will call a method on a bean to be used as the
* resource. For bean you can specify the method name after dot, eg
* bean:myBean.myMethod.
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* @param path resourceUri
* @return the dsl builder
*/
default JsltEndpointBuilder jslt(String path) {
return JsltEndpointBuilderFactory.endpointBuilder("jslt", path);
}
/**
* JSLT (camel-jslt)
* Query or transform JSON payloads using JSLT.
*
* Category: transformation
* Since: 3.1
* Maven coordinates: org.apache.camel:camel-jslt
*
* Syntax: <code>jslt:resourceUri</code>
*
* Path parameter: resourceUri (required)
* Path to the resource. You can prefix with: classpath, file, http,
* ref, or bean. classpath, file and http loads the resource using these
* protocols (classpath is default). ref will lookup the resource in the
* registry. bean will call a method on a bean to be used as the
* resource. For bean you can specify the method name after dot, eg
* bean:myBean.myMethod.
* This option can also be loaded from an existing file, by prefixing
* with file: or classpath: followed by the location of the file.
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path resourceUri
* @return the dsl builder
*/
default JsltEndpointBuilder jslt(String componentName, String path) {
return JsltEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the JSLT component.
*/
public static
|
JsltBuilders
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/ser/GenericTypeSerializationTest.java
|
{
"start": 10246,
"end": 10313
}
|
interface ____<T> {
T index();
}
public static
|
Indexed
|
java
|
apache__logging-log4j2
|
log4j-core-test/src/test/java/org/apache/logging/log4j/core/async/BasicAsyncLoggerContextSelectorTest.java
|
{
"start": 1484,
"end": 3991
}
|
class ____ {
private static final String FQCN = BasicAsyncLoggerContextSelectorTest.class.getName();
@BeforeAll
static void beforeClass() {
System.setProperty(Constants.LOG4J_CONTEXT_SELECTOR, BasicAsyncLoggerContextSelector.class.getName());
}
@AfterAll
static void afterClass() {
System.clearProperty(Constants.LOG4J_CONTEXT_SELECTOR);
}
@Test
void testContextReturnsAsyncLoggerContext() {
final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector();
final LoggerContext context = selector.getContext(FQCN, null, false);
assertInstanceOf(AsyncLoggerContext.class, context);
}
@Test
void testContext2ReturnsAsyncLoggerContext() {
final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector();
final LoggerContext context = selector.getContext(FQCN, null, false, null);
assertInstanceOf(AsyncLoggerContext.class, context);
}
@Test
void testLoggerContextsReturnsAsyncLoggerContext() {
final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector();
List<LoggerContext> list = selector.getLoggerContexts();
assertEquals(1, list.size());
assertInstanceOf(AsyncLoggerContext.class, list.get(0));
selector.getContext(FQCN, null, false);
list = selector.getLoggerContexts();
assertEquals(1, list.size());
assertInstanceOf(AsyncLoggerContext.class, list.get(0));
}
@Test
void testContextNameIsAsyncDefault() {
final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector();
final LoggerContext context = selector.getContext(FQCN, null, false);
assertEquals("AsyncDefault", context.getName());
}
@Test
void testDependentOnClassLoader() {
final BasicAsyncLoggerContextSelector selector = new BasicAsyncLoggerContextSelector();
assertFalse(selector.isClassLoaderDependent());
}
@Test
void testFactoryIsNotDependentOnClassLoader() {
assertFalse(LogManager.getFactory().isClassLoaderDependent());
}
@Test
void testLogManagerShutdown() {
final LoggerContext context = (LoggerContext) LogManager.getContext();
assertEquals(LifeCycle.State.STARTED, context.getState());
LogManager.shutdown();
assertEquals(LifeCycle.State.STOPPED, context.getState());
}
}
|
BasicAsyncLoggerContextSelectorTest
|
java
|
apache__commons-lang
|
src/main/java/org/apache/commons/lang3/builder/ToStringStyle.java
|
{
"start": 1666,
"end": 2384
}
|
class ____ be used to set the individual settings. Thus most styles can
* be achieved without subclassing.
* </p>
*
* <p>
* If required, a subclass can override as many or as few of the methods as it requires. Each object type (from {@code boolean} to {@code long} to
* {@link Object} to {@code int[]}) has its own methods to output it. Most have two versions, detail and summary.
*
* <p>
* For example, the detail version of the array based methods will output the whole array, whereas the summary method will just output the array length.
* </p>
*
* <p>
* If you want to format the output of certain objects, such as dates, you must create a subclass and override a method.
* </p>
*
* <pre>
* public
|
can
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/physical/batch/BatchPhysicalMatchRule.java
|
{
"start": 1603,
"end": 2463
}
|
class ____ extends CommonPhysicalMatchRule {
public static final RelOptRule INSTANCE = new BatchPhysicalMatchRule();
private BatchPhysicalMatchRule() {
super(
FlinkLogicalMatch.class,
FlinkConventions.LOGICAL(),
FlinkConventions.BATCH_PHYSICAL(),
"BatchPhysicalMatchRule");
}
@Override
public RelNode convert(RelNode rel) {
return super.convert(rel, FlinkConventions.BATCH_PHYSICAL());
}
@Override
protected RelNode convertToPhysicalMatch(
RelOptCluster cluster,
RelTraitSet traitSet,
RelNode convertInput,
MatchRecognize matchRecognize,
RelDataType rowType) {
return new BatchPhysicalMatch(cluster, traitSet, convertInput, matchRecognize, rowType);
}
}
|
BatchPhysicalMatchRule
|
java
|
google__guava
|
guava-gwt/src-super/com/google/common/util/concurrent/super/com/google/common/util/concurrent/ListenableFuture.java
|
{
"start": 2517,
"end": 2806
}
|
interface ____<T extends @Nullable Object> {
<V extends @Nullable Object> IThenable<V> then(
@JsOptional @Nullable IThenOnFulfilledCallbackFn<? super T, ? extends V> onFulfilled,
@JsOptional @Nullable IThenOnRejectedCallbackFn<? extends V> onRejected);
@JsFunction
|
IThenable
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/inject/MissingRuntimeRetentionTest.java
|
{
"start": 8967,
"end": 9037
}
|
interface ____ {}
""")
.doTest();
}
}
|
TestAnnotation
|
java
|
apache__logging-log4j2
|
log4j-1.2-api/src/main/java/org/apache/log4j/builders/filter/LevelRangeFilterBuilder.java
|
{
"start": 1882,
"end": 4833
}
|
class ____ extends AbstractBuilder<Filter> implements FilterBuilder {
private static final String LEVEL_MAX = "LevelMax";
private static final String LEVEL_MIN = "LevelMin";
private static final String ACCEPT_ON_MATCH = "AcceptOnMatch";
public LevelRangeFilterBuilder() {}
public LevelRangeFilterBuilder(final String prefix, final Properties props) {
super(prefix, props);
}
@Override
public Filter parse(final Element filterElement, final XmlConfiguration config) {
final AtomicReference<String> levelMax = new AtomicReference<>();
final AtomicReference<String> levelMin = new AtomicReference<>();
final AtomicBoolean acceptOnMatch = new AtomicBoolean();
forEachElement(filterElement.getElementsByTagName("param"), currentElement -> {
if (currentElement.getTagName().equals("param")) {
switch (getNameAttributeKey(currentElement)) {
case LEVEL_MAX:
levelMax.set(getValueAttribute(currentElement));
break;
case LEVEL_MIN:
levelMin.set(getValueAttribute(currentElement));
break;
case ACCEPT_ON_MATCH:
acceptOnMatch.set(getBooleanValueAttribute(currentElement));
break;
}
}
});
return createFilter(levelMax.get(), levelMin.get(), acceptOnMatch.get());
}
@Override
public Filter parse(final PropertiesConfiguration config) {
final String levelMax = getProperty(LEVEL_MAX);
final String levelMin = getProperty(LEVEL_MIN);
final boolean acceptOnMatch = getBooleanProperty(ACCEPT_ON_MATCH);
return createFilter(levelMax, levelMin, acceptOnMatch);
}
private Filter createFilter(final String levelMax, final String levelMin, final boolean acceptOnMatch) {
Level max = Level.OFF;
Level min = Level.ALL;
if (levelMax != null) {
max = OptionConverter.toLevel(levelMax, org.apache.log4j.Level.OFF).getVersion2Level();
}
if (levelMin != null) {
min = OptionConverter.toLevel(levelMin, org.apache.log4j.Level.ALL).getVersion2Level();
}
final org.apache.logging.log4j.core.Filter.Result onMatch = acceptOnMatch
? org.apache.logging.log4j.core.Filter.Result.ACCEPT
: org.apache.logging.log4j.core.Filter.Result.NEUTRAL;
// XXX: LOG4J2-2315
// log4j1 order: ALL < TRACE < DEBUG < ... < FATAL < OFF
// log4j2 order: ALL > TRACE > DEBUG > ... > FATAL > OFF
// So we create as LevelRangeFilter.createFilter(minLevel=max, maxLevel=min, ...)
return FilterWrapper.adapt(
LevelRangeFilter.createFilter(max, min, onMatch, org.apache.logging.log4j.core.Filter.Result.DENY));
}
}
|
LevelRangeFilterBuilder
|
java
|
micronaut-projects__micronaut-core
|
management/src/main/java/io/micronaut/management/health/aggregator/DefaultHealthAggregator.java
|
{
"start": 2169,
"end": 6047
}
|
class ____ implements HealthAggregator<HealthResult> {
private static final Logger LOG = LoggerFactory.getLogger(DefaultHealthAggregator.class);
private final ApplicationConfiguration applicationConfiguration;
/**
* Default constructor.
*
* @param applicationConfiguration The application configuration.
*/
public DefaultHealthAggregator(ApplicationConfiguration applicationConfiguration) {
this.applicationConfiguration = applicationConfiguration;
}
@Override
public Publisher<HealthResult> aggregate(HealthIndicator[] indicators, HealthLevelOfDetail healthLevelOfDetail) {
Flux<HealthResult> results = aggregateResults(indicators);
Mono<HealthResult> result = results.collectList().map(list -> {
HealthStatus overallStatus = calculateOverallStatus(list);
return buildResult(overallStatus, aggregateDetails(list), healthLevelOfDetail);
});
return result.flux();
}
@Override
public Publisher<HealthResult> aggregate(String name, Publisher<HealthResult> results) {
Mono<HealthResult> result = Flux.from(results).collectList().map(list -> {
HealthStatus overallStatus = calculateOverallStatus(list);
Object details = aggregateDetails(list);
return HealthResult.builder(name, overallStatus).details(details).build();
});
return result.flux();
}
/**
* @param results A list of {@link HealthResult}
* @return The calculated overall health status
*/
protected HealthStatus calculateOverallStatus(List<HealthResult> results) {
return results.stream()
.map(HealthResult::getStatus)
.sorted()
.distinct()
.reduce((a, b) -> b)
.orElse(HealthStatus.UNKNOWN);
}
/**
* @param indicators An array of {@link HealthIndicator}
* @return The aggregated results from all health indicators
*/
protected Flux<HealthResult> aggregateResults(HealthIndicator[] indicators) {
return Flux.merge(
Arrays.stream(indicators)
.map(HealthIndicator::getResult)
.collect(Collectors.toList())
);
}
/**
* @param results A list of health results
* @return The aggregated details for the results
*/
protected Object aggregateDetails(List<HealthResult> results) {
Map<String, Object> aggregatedDetails = CollectionUtils.newHashMap(results.size());
results.forEach(r -> {
var name = r.getName();
var details = r.getDetails();
var status = r.getStatus();
aggregatedDetails.put(name, buildResult(status, details, HealthLevelOfDetail.STATUS_DESCRIPTION_DETAILS));
if (LOG.isTraceEnabled()) {
LOG.trace("Health result for {}: status {}, details {}", name, status, details != null ? details : "{}");
} else if (LOG.isDebugEnabled()) {
LOG.debug("Health result for {}: status {}", name, status);
}
});
return aggregatedDetails;
}
/**
* @param status A {@link HealthStatus}
* @param details The health status details
* @param healthLevelOfDetail The {@link HealthLevelOfDetail}
* @return A {@link Map} with the results from the health status
*/
@SuppressWarnings("MagicNumber")
protected HealthResult buildResult(HealthStatus status, Object details, HealthLevelOfDetail healthLevelOfDetail) {
if (healthLevelOfDetail == HealthLevelOfDetail.STATUS) {
return HealthResult.builder(null, status).build();
}
return HealthResult.builder(
applicationConfiguration.getName().orElse(Environment.DEFAULT_NAME),
status
).details(details).build();
}
}
|
DefaultHealthAggregator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/MissingCasesInEnumSwitchTest.java
|
{
"start": 7543,
"end": 8073
}
|
enum ____ {
ONE,
TWO,
THREE
}
void m(Case c) {
// BUG: Diagnostic contains: THREE
switch (c) {
case ONE, TWO:
System.err.println("found it!");
}
}
}
""")
.doTest();
}
@Test
public void nonExhaustive_multiArrow() {
compilationHelper
.addSourceLines(
"Test.java",
"""
|
Case
|
java
|
FasterXML__jackson-core
|
src/main/java/tools/jackson/core/json/UTF8StreamJsonParser.java
|
{
"start": 599,
"end": 152493
}
|
class ____
extends JsonParserBase
{
final static byte BYTE_LF = (byte) '\n';
private final static int FEAT_MASK_TRAILING_COMMA = JsonReadFeature.ALLOW_TRAILING_COMMA.getMask();
private final static int FEAT_MASK_ALLOW_MISSING = JsonReadFeature.ALLOW_MISSING_VALUES.getMask();
// This is the main input-code lookup table, fetched eagerly
private final static int[] _icUTF8 = CharTypes.getInputCodeUtf8();
// Latin1 encoding is not supported, but we do use 8-bit subset for
// pre-processing task, to simplify first pass, keep it fast.
protected final static int[] _icLatin1 = CharTypes.getInputCodeLatin1();
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
/**
* Symbol table that contains property names encountered so far
*/
protected final ByteQuadsCanonicalizer _symbols;
/*
/**********************************************************************
/* Parsing state
/**********************************************************************
*/
/**
* Temporary buffer used for name parsing.
*/
protected int[] _quadBuffer = new int[16];
/**
* Flag that indicates that the current token has not yet
* been fully processed, and needs to be finished for
* some access (or skipped to obtain the next token)
*/
protected boolean _tokenIncomplete;
/**
* Temporary storage for partially parsed name bytes.
*/
private int _quad1;
/**
* Temporary input pointer
*/
private int _quadPtr;
/**
* Value of {@link #_inputPtr} at the time when the first character of
* name token was read. Used for calculating token location when requested;
* combined with {@link #_currInputProcessed}, may be updated appropriately
* as needed.
*/
protected int _nameStartOffset;
protected int _nameStartRow;
protected int _nameStartCol;
/*
/**********************************************************************
/* Input buffering (from former 'StreamBasedParserBase')
/**********************************************************************
*/
protected InputStream _inputStream;
/*
/**********************************************************************
/* Current input data
/**********************************************************************
*/
/**
* Current buffer from which data is read; generally data is read into
* buffer from input source, but in some cases pre-loaded buffer
* is handed to the parser.
*/
protected byte[] _inputBuffer;
/**
* Flag that indicates whether the input buffer is recycable (and
* needs to be returned to recycler once we are done) or not.
*<p>
* If it is not, it also means that parser CANNOT modify underlying
* buffer.
*/
protected boolean _bufferRecyclable;
/*
/**********************************************************************
/* Life-cycle
/**********************************************************************
*/
/**
* Constructor called when caller wants to provide input buffer directly
* (or needs to, in case of bootstrapping having read some of contents)
* and it may or may not be recyclable use standard recycle context.
*
* @param readCtxt Object read context to use
* @param ctxt I/O context to use
* @param stdFeatures Standard stream read features enabled
* @param formatReadFeatures Format-specific read features enabled
* @param in InputStream used for reading actual content, if any; {@code null} if none
* @param sym Name canonicalizer to use
* @param inputBuffer Input buffer to read initial content from (before Reader)
* @param start Pointer in {@code inputBuffer} that has the first content character to decode
* @param end Pointer past the last content character in {@code inputBuffer}
* @param bytesPreProcessed Number of bytes that have been consumed already (by bootstrapping)
* @param bufferRecyclable Whether {@code inputBuffer} passed is managed by Jackson core
* (and thereby needs recycling)
*/
public UTF8StreamJsonParser(ObjectReadContext readCtxt, IOContext ctxt,
int stdFeatures, int formatReadFeatures,
InputStream in,
ByteQuadsCanonicalizer sym,
byte[] inputBuffer, int start, int end, int bytesPreProcessed,
boolean bufferRecyclable)
{
super(readCtxt, ctxt, stdFeatures, formatReadFeatures);
_inputStream = in;
_symbols = sym;
_inputBuffer = inputBuffer;
_inputPtr = start;
_inputEnd = end;
_currInputRowStart = start - bytesPreProcessed;
// If we have offset, need to omit that from byte offset, so:
_currInputProcessed = -start + bytesPreProcessed;
_bufferRecyclable = bufferRecyclable;
}
/*
/**********************************************************************
/* Overrides for life-cycle
/**********************************************************************
*/
@Override
public int releaseBuffered(OutputStream out) throws JacksonException
{
int count = _inputEnd - _inputPtr;
if (count < 1) {
return 0;
}
// let's just advance ptr to end
int origPtr = _inputPtr;
_inputPtr += count;
try {
out.write(_inputBuffer, origPtr, count);
} catch (IOException e) {
throw _wrapIOFailure(e);
}
return count;
}
@Override
public Object streamReadInputSource() {
return _inputStream;
}
/*
/**********************************************************************
/* Overrides, low-level reading
/**********************************************************************
*/
protected final boolean _loadMore() throws JacksonException
{
if (_inputStream != null) {
int space = _inputBuffer.length;
if (space == 0) { // only occurs when we've been closed
return false;
}
final int count;
try {
count = _inputStream.read(_inputBuffer, 0, space);
} catch (IOException e) {
throw _wrapIOFailure(e);
}
final int bufSize = _inputEnd;
_currInputProcessed += bufSize;
_currInputRowStart -= bufSize;
// 06-Sep-2023, tatu: [core#1046] Enforce max doc length limit
_streamReadConstraints.validateDocumentLength(_currInputProcessed);
if (count > 0) {
// 26-Nov-2015, tatu: Since name-offset requires it too, must offset
// this increase to avoid "moving" name-offset, resulting most likely
// in negative value, which is fine as combine value remains unchanged.
_nameStartOffset -= bufSize;
_inputPtr = 0;
_inputEnd = count;
return true;
}
_inputPtr = _inputEnd = 0;
// End of input
_closeInput();
// Should never return 0, so let's fail
if (count == 0) {
return _reportBadInputStream(_inputBuffer.length);
}
}
return false;
}
@Override
protected void _closeInput()
{
// We are not to call close() on the underlying InputStream
// unless we "own" it, or auto-closing feature is enabled.
if (_inputStream != null) {
if (_ioContext.isResourceManaged() || isEnabled(StreamReadFeature.AUTO_CLOSE_SOURCE)) {
try {
_inputStream.close();
} catch (IOException e) {
throw _wrapIOFailure(e);
}
}
_inputStream = null;
}
}
/**
* Method called to release internal buffers owned by the base
* reader. This may be called along with {@link #_closeInput} (for
* example, when explicitly closing this reader instance), or
* separately (if need be).
*/
@Override
protected void _releaseBuffers()
{
super._releaseBuffers();
// Merge found symbols, if any:
_symbols.release();
if (_bufferRecyclable) {
byte[] buf = _inputBuffer;
if (buf != null) {
// Let's not set it to null; this way should get slightly more meaningful
// error messages in case someone closes parser indirectly, without realizing.
if (buf != NO_BYTES) {
_inputBuffer = NO_BYTES;
_ioContext.releaseReadIOBuffer(buf);
}
}
}
}
/*
/**********************************************************************
/* Public API, data access
/**********************************************************************
*/
@Override
public String getString() throws JacksonException
{
if (_currToken == JsonToken.VALUE_STRING) {
if (_tokenIncomplete) {
_tokenIncomplete = false;
return _finishAndReturnString(); // only strings can be incomplete
}
return _textBuffer.contentsAsString();
}
return _getText2(_currToken);
}
@Override
public int getString(Writer writer) throws JacksonException
{
try {
JsonToken t = _currToken;
if (t == JsonToken.VALUE_STRING) {
if (_tokenIncomplete) {
_tokenIncomplete = false;
_finishString(); // only strings can be incomplete
}
return _textBuffer.contentsToWriter(writer);
}
if (t == JsonToken.PROPERTY_NAME) {
String n = _streamReadContext.currentName();
writer.write(n);
return n.length();
}
if (t != null) {
if (t.isNumeric()) {
return _textBuffer.contentsToWriter(writer);
}
char[] ch = t.asCharArray();
writer.write(ch);
return ch.length;
}
} catch (IOException e) {
throw _wrapIOFailure(e);
}
return 0;
}
// // // Let's override default impls for improved performance
@Override
public String getValueAsString() throws JacksonException
{
if (_currToken == JsonToken.VALUE_STRING) {
if (_tokenIncomplete) {
_tokenIncomplete = false;
return _finishAndReturnString(); // only strings can be incomplete
}
return _textBuffer.contentsAsString();
}
if (_currToken == JsonToken.PROPERTY_NAME) {
return currentName();
}
return super.getValueAsString(null);
}
@Override
public String getValueAsString(String defValue) throws JacksonException
{
if (_currToken == JsonToken.VALUE_STRING) {
if (_tokenIncomplete) {
_tokenIncomplete = false;
return _finishAndReturnString(); // only strings can be incomplete
}
return _textBuffer.contentsAsString();
}
if (_currToken == JsonToken.PROPERTY_NAME) {
return currentName();
}
return super.getValueAsString(defValue);
}
// since 2.6
@Override
public int getValueAsInt() throws JacksonException
{
JsonToken t = _currToken;
if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
// inlined 'getIntValue()'
if ((_numTypesValid & NR_INT) == 0) {
if (_numTypesValid == NR_UNKNOWN) {
return _parseIntValue();
}
if ((_numTypesValid & NR_INT) == 0) {
convertNumberToInt();
}
}
return _numberInt;
}
return super.getValueAsInt(0);
}
// since 2.6
@Override
public int getValueAsInt(int defValue) throws JacksonException
{
JsonToken t = _currToken;
if ((t == JsonToken.VALUE_NUMBER_INT) || (t == JsonToken.VALUE_NUMBER_FLOAT)) {
// inlined 'getIntValue()'
if ((_numTypesValid & NR_INT) == 0) {
if (_numTypesValid == NR_UNKNOWN) {
return _parseIntValue();
}
if ((_numTypesValid & NR_INT) == 0) {
convertNumberToInt();
}
}
return _numberInt;
}
return super.getValueAsInt(defValue);
}
protected final String _getText2(JsonToken t) throws JacksonException
{
if (t == null) {
return null;
}
switch (t.id()) {
case ID_PROPERTY_NAME:
return _streamReadContext.currentName();
case ID_STRING:
// fall through
case ID_NUMBER_INT:
case ID_NUMBER_FLOAT:
return _textBuffer.contentsAsString();
default:
return t.asString();
}
}
@Override
public char[] getStringCharacters() throws JacksonException
{
if (_currToken != null) { // null only before/after document
switch (_currToken.id()) {
case ID_PROPERTY_NAME:
return currentNameInBuffer();
case ID_STRING:
if (_tokenIncomplete) {
_tokenIncomplete = false;
_finishString(); // only strings can be incomplete
}
// fall through
case ID_NUMBER_INT:
case ID_NUMBER_FLOAT:
return _textBuffer.getTextBuffer();
default:
return _currToken.asCharArray();
}
}
return null;
}
@Override
public int getStringLength() throws JacksonException
{
if (_currToken != null) { // null only before/after document
switch (_currToken.id()) {
case ID_PROPERTY_NAME:
return _streamReadContext.currentName().length();
case ID_STRING:
if (_tokenIncomplete) {
_tokenIncomplete = false;
_finishString(); // only strings can be incomplete
}
// fall through
case ID_NUMBER_INT:
case ID_NUMBER_FLOAT:
return _textBuffer.size();
default:
return _currToken.asCharArray().length;
}
}
return 0;
}
@Override
public int getStringOffset() throws JacksonException
{
// Most have offset of 0, only some may have other values:
if (_currToken != null) {
switch (_currToken.id()) {
case ID_PROPERTY_NAME:
return 0;
case ID_STRING:
if (_tokenIncomplete) {
_tokenIncomplete = false;
_finishString(); // only strings can be incomplete
}
// fall through
case ID_NUMBER_INT:
case ID_NUMBER_FLOAT:
return _textBuffer.getTextOffset();
default:
}
}
return 0;
}
@Override
public byte[] getBinaryValue(Base64Variant b64variant) throws JacksonException
{
if (_currToken != JsonToken.VALUE_STRING &&
(_currToken != JsonToken.VALUE_EMBEDDED_OBJECT || _binaryValue == null)) {
return _reportError("Current token ("+_currToken+") not VALUE_STRING or VALUE_EMBEDDED_OBJECT, cannot access as binary");
}
// To ensure that we won't see inconsistent data, better clear up state...
if (_tokenIncomplete) {
try {
_binaryValue = _decodeBase64(b64variant);
} catch (IllegalArgumentException iae) {
throw _constructReadException("Failed to decode VALUE_STRING as base64 ("+b64variant+"): "+iae.getMessage());
}
// let's clear incomplete only now; allows for accessing other textual content in error cases
_tokenIncomplete = false;
} else { // may actually require conversion...
if (_binaryValue == null) {
@SuppressWarnings("resource")
ByteArrayBuilder builder = _getByteArrayBuilder();
_decodeBase64(getString(), builder, b64variant);
_binaryValue = builder.toByteArray();
}
}
return _binaryValue;
}
@Override
public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws JacksonException
{
// if we have already read the token, just use whatever we may have
if (!_tokenIncomplete || _currToken != JsonToken.VALUE_STRING) {
byte[] b = getBinaryValue(b64variant);
try {
out.write(b);
} catch (IOException e) {
throw _wrapIOFailure(e);
}
return b.length;
}
// otherwise do "real" incremental parsing...
byte[] buf = _ioContext.allocBase64Buffer();
try {
return _readBinary(b64variant, out, buf);
} catch (IOException e) {
throw _wrapIOFailure(e);
} finally {
_ioContext.releaseBase64Buffer(buf);
}
}
protected int _readBinary(Base64Variant b64variant, OutputStream out,
byte[] buffer) throws IOException
{
int outputPtr = 0;
final int outputEnd = buffer.length - 3;
int outputCount = 0;
while (true) {
// first, we'll skip preceding white space, if any
int ch;
do {
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
} while (ch <= INT_SPACE);
int bits = b64variant.decodeBase64Char(ch);
if (bits < 0) { // reached the end, fair and square?
if (ch == INT_QUOTE) {
break;
}
bits = _decodeBase64Escape(b64variant, ch, 0);
if (bits < 0) { // white space to skip
continue;
}
}
// enough room? If not, flush
if (outputPtr > outputEnd) {
outputCount += outputPtr;
out.write(buffer, 0, outputPtr);
outputPtr = 0;
}
int decodedData = bits;
// then second base64 char; can't get padding yet, nor ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
bits = _decodeBase64Escape(b64variant, ch, 1);
}
decodedData = (decodedData << 6) | bits;
// third base64 char; can be padding, but not ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
// First branch: can get padding (-> 1 byte)
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
// as per [JACKSON-631], could also just be 'missing' padding
if (ch == INT_QUOTE) {
decodedData >>= 4;
buffer[outputPtr++] = (byte) decodedData;
if (b64variant.requiresPaddingOnRead()) {
--_inputPtr; // to keep parser state bit more consistent
_handleBase64MissingPadding(b64variant);
}
break;
}
bits = _decodeBase64Escape(b64variant, ch, 2);
}
if (bits == Base64Variant.BASE64_VALUE_PADDING) {
// Ok, must get padding
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
if (!b64variant.usesPaddingChar(ch)) {
if (_decodeBase64Escape(b64variant, ch, 3) != Base64Variant.BASE64_VALUE_PADDING) {
return _reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'");
}
}
// Got 12 bits, only need 8, need to shift
decodedData >>= 4;
buffer[outputPtr++] = (byte) decodedData;
continue;
}
}
// Nope, 2 or 3 bytes
decodedData = (decodedData << 6) | bits;
// fourth and last base64 char; can be padding, but not ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
// as per [JACKSON-631], could also just be 'missing' padding
if (ch == INT_QUOTE) {
decodedData >>= 2;
buffer[outputPtr++] = (byte) (decodedData >> 8);
buffer[outputPtr++] = (byte) decodedData;
if (b64variant.requiresPaddingOnRead()) {
--_inputPtr; // to keep parser state bit more consistent
_handleBase64MissingPadding(b64variant);
}
break;
}
bits = _decodeBase64Escape(b64variant, ch, 3);
}
if (bits == Base64Variant.BASE64_VALUE_PADDING) {
/* With padding we only get 2 bytes; but we have
* to shift it a bit so it is identical to triplet
* case with partial output.
* 3 chars gives 3x6 == 18 bits, of which 2 are
* dummies, need to discard:
*/
decodedData >>= 2;
buffer[outputPtr++] = (byte) (decodedData >> 8);
buffer[outputPtr++] = (byte) decodedData;
continue;
}
}
// otherwise, our triplet is now complete
decodedData = (decodedData << 6) | bits;
buffer[outputPtr++] = (byte) (decodedData >> 16);
buffer[outputPtr++] = (byte) (decodedData >> 8);
buffer[outputPtr++] = (byte) decodedData;
}
_tokenIncomplete = false;
if (outputPtr > 0) {
outputCount += outputPtr;
out.write(buffer, 0, outputPtr);
}
return outputCount;
}
/*
/**********************************************************************
/* Public API, traversal, basic
/**********************************************************************
*/
/**
* @return Next token from the stream, if any found, or null
* to indicate end-of-input
*/
@Override
public JsonToken nextToken() throws JacksonException
{
/* First: property names are special -- we will always tokenize
* (part of) value along with property name to simplify
* state handling. If so, can and need to use secondary token:
*/
if (_currToken == JsonToken.PROPERTY_NAME) {
return _nextAfterName();
}
// But if we didn't already have a name, and (partially?) decode number,
// need to ensure no numeric information is leaked
_numTypesValid = NR_UNKNOWN;
if (_tokenIncomplete) {
_skipString(); // only strings can be partial
}
int i = _skipWSOrEnd();
if (i < 0) { // end-of-input
// Close/release things like input source, symbol table and recyclable buffers
close();
return _updateTokenToNull();
}
// clear any data retained so far
_binaryValue = null;
// Closing scope?
if (i == INT_RBRACKET) {
_closeArrayScope();
return _updateToken(JsonToken.END_ARRAY);
}
if (i == INT_RCURLY) {
_closeObjectScope();
return _updateToken(JsonToken.END_OBJECT);
}
// Nope: do we then expect a comma?
if (_streamReadContext.expectComma()) {
if (i != INT_COMMA) {
return _reportUnexpectedChar(i, "was expecting comma to separate "+_streamReadContext.typeDesc()+" entries");
}
i = _skipWS();
// Was that a trailing comma?
if ((_formatReadFeatures & FEAT_MASK_TRAILING_COMMA) != 0) {
if ((i == INT_RBRACKET) || (i == INT_RCURLY)) {
return _closeScope(i);
}
}
}
// And should we now have a name? Always true for Object contexts
// since the intermediate 'expect-value' state is never retained.
if (!_streamReadContext.inObject()) {
_updateLocation();
return _nextTokenNotInObject(i);
}
// So first parse the property name itself:
_updateNameLocation();
String n = _parseName(i);
_streamReadContext.setCurrentName(n);
_updateToken(JsonToken.PROPERTY_NAME);
i = _skipColon();
_updateLocation();
// Ok: we must have a value... what is it? Strings are very common, check first:
if (i == INT_QUOTE) {
_tokenIncomplete = true;
_nextToken = JsonToken.VALUE_STRING;
return _currToken;
}
JsonToken t;
switch (i) {
case '-':
t = _parseSignedNumber(true);
break;
case '+':
if (isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
t = _parseSignedNumber(false);
} else {
t = _handleUnexpectedValue(i);
}
break;
case '.': // [core#611]:
t = _parseFloatThatStartsWithPeriod(false, false);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
t = _parseUnsignedNumber(i);
break;
case 'f':
_matchFalse();
t = JsonToken.VALUE_FALSE;
break;
case 'n':
_matchNull();
t = JsonToken.VALUE_NULL;
break;
case 't':
_matchTrue();
t = JsonToken.VALUE_TRUE;
break;
case '[':
t = JsonToken.START_ARRAY;
break;
case '{':
t = JsonToken.START_OBJECT;
break;
default:
t = _handleUnexpectedValue(i);
}
_nextToken = t;
return _currToken;
}
private final JsonToken _nextTokenNotInObject(int i) throws JacksonException
{
if (i == INT_QUOTE) {
_tokenIncomplete = true;
return _updateToken(JsonToken.VALUE_STRING);
}
switch (i) {
case '[':
createChildArrayContext(_tokenInputRow, _tokenInputCol);
return _updateToken(JsonToken.START_ARRAY);
case '{':
createChildObjectContext(_tokenInputRow, _tokenInputCol);
return _updateToken(JsonToken.START_OBJECT);
case 't':
_matchTrue();
return _updateToken(JsonToken.VALUE_TRUE);
case 'f':
_matchFalse();
return _updateToken(JsonToken.VALUE_FALSE);
case 'n':
_matchNull();
return _updateToken(JsonToken.VALUE_NULL);
case '-':
return _updateToken(_parseSignedNumber(true));
case '+':
if (!isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
return _updateToken(_handleUnexpectedValue(i));
}
return _updateToken(_parseSignedNumber(false));
case '.': // [core#611]:
return _updateToken(_parseFloatThatStartsWithPeriod(false, false));
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return _updateToken(_parseUnsignedNumber(i));
}
return _updateToken(_handleUnexpectedValue(i));
}
private final JsonToken _nextAfterName() throws JacksonException
{
_nameCopied = false; // need to invalidate if it was copied
JsonToken t = _nextToken;
_nextToken = null;
// !!! 16-Nov-2015, tatu: TODO: fix [databind#37], copy next location to current here
// Also: may need to start new context?
if (t == JsonToken.START_ARRAY) {
createChildArrayContext(_tokenInputRow, _tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
createChildObjectContext(_tokenInputRow, _tokenInputCol);
}
return _updateToken(t);
}
@Override
public void finishToken() throws JacksonException {
if (_tokenIncomplete) {
_tokenIncomplete = false;
_finishString(); // only strings can be incomplete
}
}
/*
/**********************************************************************
/* Public API, traversal, nextName() variants
/**********************************************************************
*/
@Override
public String nextName() throws JacksonException
{
// // // Note: this is almost a verbatim copy of nextToken()
_numTypesValid = NR_UNKNOWN;
if (_currToken == JsonToken.PROPERTY_NAME) {
_nextAfterName();
return null;
}
if (_tokenIncomplete) {
_skipString();
}
int i = _skipWSOrEnd();
if (i < 0) {
close();
_updateTokenToNull();
return null;
}
_binaryValue = null;
if (i == INT_RBRACKET) {
_closeArrayScope();
_updateToken(JsonToken.END_ARRAY);
return null;
}
if (i == INT_RCURLY) {
_closeObjectScope();
_updateToken(JsonToken.END_OBJECT);
return null;
}
// Nope: do we then expect a comma?
if (_streamReadContext.expectComma()) {
if (i != INT_COMMA) {
return _reportUnexpectedChar(i, "was expecting comma to separate "+_streamReadContext.typeDesc()+" entries");
}
i = _skipWS();
// Was that a trailing comma?
if ((_formatReadFeatures & FEAT_MASK_TRAILING_COMMA) != 0) {
if ((i == INT_RBRACKET) || (i == INT_RCURLY)) {
_closeScope(i);
return null;
}
}
}
if (!_streamReadContext.inObject()) {
_updateLocation();
_nextTokenNotInObject(i);
return null;
}
_updateNameLocation();
final String nameStr = _parseName(i);
_streamReadContext.setCurrentName(nameStr);
_updateToken(JsonToken.PROPERTY_NAME);
i = _skipColon();
_updateLocation();
if (i == INT_QUOTE) {
_tokenIncomplete = true;
_nextToken = JsonToken.VALUE_STRING;
return nameStr;
}
JsonToken t;
switch (i) {
case '-':
t = _parseSignedNumber(true);
break;
case '+':
if (isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
t = _parseSignedNumber(false);
} else {
t = _handleUnexpectedValue(i);
}
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
t = _parseUnsignedNumber(i);
break;
case 'f':
_matchFalse();
t = JsonToken.VALUE_FALSE;
break;
case 'n':
_matchNull();
t = JsonToken.VALUE_NULL;
break;
case 't':
_matchTrue();
t = JsonToken.VALUE_TRUE;
break;
case '[':
t = JsonToken.START_ARRAY;
break;
case '{':
t = JsonToken.START_OBJECT;
break;
default:
t = _handleUnexpectedValue(i);
}
_nextToken = t;
return nameStr;
}
@Override
public boolean nextName(SerializableString str) throws JacksonException
{
// // // Note: most of code below is copied from nextToken()
_numTypesValid = NR_UNKNOWN;
if (_currToken == JsonToken.PROPERTY_NAME) { // can't have name right after name
_nextAfterName();
return false;
}
if (_tokenIncomplete) {
_skipString();
}
int i = _skipWSOrEnd();
if (i < 0) { // end-of-input
close();
_updateTokenToNull();
return false;
}
_binaryValue = null;
// Closing scope?
if (i == INT_RBRACKET) {
_closeArrayScope();
_updateToken(JsonToken.END_ARRAY);
return false;
}
if (i == INT_RCURLY) {
_closeObjectScope();
_updateToken(JsonToken.END_OBJECT);
return false;
}
// Nope: do we then expect a comma?
if (_streamReadContext.expectComma()) {
if (i != INT_COMMA) {
return _reportUnexpectedChar(i, "was expecting comma to separate "+_streamReadContext.typeDesc()+" entries");
}
i = _skipWS();
// Was that a trailing comma?
if ((_formatReadFeatures & FEAT_MASK_TRAILING_COMMA) != 0) {
if ((i == INT_RBRACKET) || (i == INT_RCURLY)) {
_closeScope(i);
return false;
}
}
}
if (!_streamReadContext.inObject()) {
_updateLocation();
_nextTokenNotInObject(i);
return false;
}
// // // This part differs, name parsing
_updateNameLocation();
if (i == INT_QUOTE) {
// when doing literal match, must consider escaping:
byte[] nameBytes = str.asQuotedUTF8();
final int len = nameBytes.length;
// 22-May-2014, tatu: Actually, let's require 4 more bytes for faster skipping
// of colon that follows name
if ((_inputPtr + len + 4) < _inputEnd) { // maybe...
// first check length match by
final int end = _inputPtr+len;
if (_inputBuffer[end] == INT_QUOTE) {
int offset = 0;
int ptr = _inputPtr;
while (true) {
if (ptr == end) { // yes, match!
_streamReadContext.setCurrentName(str.getValue());
i = _skipColonFast(ptr+1);
_isNextTokenNameYes(i);
return true;
}
if (nameBytes[offset] != _inputBuffer[ptr]) {
break;
}
++offset;
++ptr;
}
}
}
}
return _isNextTokenNameMaybe(i, str);
}
@Override
public int nextNameMatch(PropertyNameMatcher matcher) throws JacksonException
{
// // // Note: this is almost a verbatim copy of nextToken()
_numTypesValid = NR_UNKNOWN;
if (_currToken == JsonToken.PROPERTY_NAME) {
_nextAfterName();
return PropertyNameMatcher.MATCH_ODD_TOKEN;
}
if (_tokenIncomplete) {
_skipString();
}
int i = _skipWSOrEnd();
if (i < 0) {
close();
_updateTokenToNull();
return PropertyNameMatcher.MATCH_ODD_TOKEN;
}
_binaryValue = null;
if (i == INT_RBRACKET) {
_closeArrayScope();
_updateToken(JsonToken.END_ARRAY);
return PropertyNameMatcher.MATCH_ODD_TOKEN;
}
if (i == INT_RCURLY) {
_closeObjectScope();
_updateToken(JsonToken.END_OBJECT);
return PropertyNameMatcher.MATCH_END_OBJECT;
}
// Nope: do we then expect a comma?
if (_streamReadContext.expectComma()) {
if (i != INT_COMMA) {
return _reportUnexpectedChar(i, "was expecting comma to separate "+_streamReadContext.typeDesc()+" entries");
}
i = _skipWS();
// Was that a trailing comma?
if ((_formatReadFeatures & FEAT_MASK_TRAILING_COMMA) != 0) {
boolean isEndObject = (i == INT_RCURLY);
if (isEndObject || (i == INT_RBRACKET)) {
_closeScope(i);
return isEndObject ? PropertyNameMatcher.MATCH_END_OBJECT : PropertyNameMatcher.MATCH_ODD_TOKEN;
}
}
}
if (!_streamReadContext.inObject()) {
_updateLocation();
_nextTokenNotInObject(i);
return PropertyNameMatcher.MATCH_ODD_TOKEN;
}
_updateNameLocation();
String name;
int match = _matchName(matcher, i);
if (match >= 0) { // gotcha! (expected case)
_inputPtr = _quadPtr;
name = matcher.nameLookup()[match];
} else {
// !!! TODO 12-Dec-2017, tatu: Should probably try to use symbol table
// for cases where quads were decoded ok, but no match?
/*
if (match == PropertyNameMatcher.MATCH_UNKNOWN_NAME) {
throw new RuntimeException("No name match!");
}
*/
name = _parseName(i);
match = matcher.matchName(name);
}
_streamReadContext.setCurrentName(name);
_updateToken(JsonToken.PROPERTY_NAME);
// Otherwise, try again...
i = _skipColon();
_updateLocation();
if (i == INT_QUOTE) { // optimize commonest case, String value
_tokenIncomplete = true;
_nextToken = JsonToken.VALUE_STRING;
return match;
}
JsonToken t;
switch (i) {
case '-':
t = _parseSignedNumber(true);
break;
case '+':
if (isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
t = _parseSignedNumber(false);
} else {
t = _handleUnexpectedValue(i);
}
break;
case '.': // [core#611]:
t = _parseFloatThatStartsWithPeriod(false, false);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
t = _parseUnsignedNumber(i);
break;
case 'f':
_matchFalse();
t = JsonToken.VALUE_FALSE;
break;
case 'n':
_matchNull();
t = JsonToken.VALUE_NULL;
break;
case 't':
_matchTrue();
t = JsonToken.VALUE_TRUE;
break;
case '[':
t = JsonToken.START_ARRAY;
break;
case '{':
t = JsonToken.START_OBJECT;
break;
default:
t = _handleUnexpectedValue(i);
}
_nextToken = t;
return match;
}
// Variant called when we know there's at least 4 more bytes available
private final int _skipColonFast(int ptr) throws JacksonException
{
int i = _inputBuffer[ptr++];
if (i == INT_COLON) { // common case, no leading space
i = _inputBuffer[ptr++];
if (i > INT_SPACE) { // nor trailing
if (i != INT_SLASH && i != INT_HASH) {
_inputPtr = ptr;
return i;
}
} else if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[ptr++];
if (i > INT_SPACE) {
if (i != INT_SLASH && i != INT_HASH) {
_inputPtr = ptr;
return i;
}
}
}
_inputPtr = ptr-1;
return _skipColon2(true); // true -> skipped colon
}
if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[ptr++];
}
if (i == INT_COLON) {
i = _inputBuffer[ptr++];
if (i > INT_SPACE) {
if (i != INT_SLASH && i != INT_HASH) {
_inputPtr = ptr;
return i;
}
} else if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[ptr++];
if (i > INT_SPACE) {
if (i != INT_SLASH && i != INT_HASH) {
_inputPtr = ptr;
return i;
}
}
}
_inputPtr = ptr-1;
return _skipColon2(true);
}
_inputPtr = ptr-1;
return _skipColon2(false);
}
private final void _isNextTokenNameYes(int i) throws JacksonException
{
_updateToken(JsonToken.PROPERTY_NAME);
_updateLocation();
switch (i) {
case '"':
_tokenIncomplete = true;
_nextToken = JsonToken.VALUE_STRING;
return;
case '[':
_nextToken = JsonToken.START_ARRAY;
return;
case '{':
_nextToken = JsonToken.START_OBJECT;
return;
case 't':
_matchTrue();
_nextToken = JsonToken.VALUE_TRUE;
return;
case 'f':
_matchFalse();
_nextToken = JsonToken.VALUE_FALSE;
return;
case 'n':
_matchNull();
_nextToken = JsonToken.VALUE_NULL;
return;
case '-':
_nextToken = _parseSignedNumber(true);
return;
case '+':
if (isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
_nextToken = _parseSignedNumber(false);
} else {
_nextToken = _handleUnexpectedValue(i);
}
return;
case '.': // [core#611]
_nextToken = _parseFloatThatStartsWithPeriod(false, false);
return;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
_nextToken = _parseUnsignedNumber(i);
return;
}
_nextToken = _handleUnexpectedValue(i);
}
private final boolean _isNextTokenNameMaybe(int i, SerializableString str) throws JacksonException
{
// // // and this is back to standard nextToken()
String n = _parseName(i);
_streamReadContext.setCurrentName(n);
final boolean match = n.equals(str.getValue());
_updateToken(JsonToken.PROPERTY_NAME);
i = _skipColon();
_updateLocation();
// Ok: we must have a value... what is it? Strings are very common, check first:
if (i == INT_QUOTE) {
_tokenIncomplete = true;
_nextToken = JsonToken.VALUE_STRING;
return match;
}
JsonToken t;
switch (i) {
case '[':
t = JsonToken.START_ARRAY;
break;
case '{':
t = JsonToken.START_OBJECT;
break;
case 't':
_matchTrue();
t = JsonToken.VALUE_TRUE;
break;
case 'f':
_matchFalse();
t = JsonToken.VALUE_FALSE;
break;
case 'n':
_matchNull();
t = JsonToken.VALUE_NULL;
break;
case '-':
t = _parseSignedNumber(true);
break;
case '+':
if (isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS)) {
t = _parseSignedNumber(false);
} else {
t = _handleUnexpectedValue(i);
}
break;
case '.': // [core#611]
t = _parseFloatThatStartsWithPeriod(false, false);
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
t = _parseUnsignedNumber(i);
break;
default:
t = _handleUnexpectedValue(i);
}
_nextToken = t;
return match;
}
protected final int _matchName(PropertyNameMatcher matcher, int i) throws JacksonException
{
if (i != INT_QUOTE) {
return -1;
}
// First: can we optimize out bounds checks for first rounds of processing?
int qptr = _inputPtr;
if ((qptr + 13) > _inputEnd) { // Need up to 12 chars, plus one trailing (quote)
return -1;
}
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
int q = input[qptr++] & 0xFF;
if (codes[q] != 0) {
if (q == INT_QUOTE) { // special case, ""
return matcher.matchName("");
}
return -1;
}
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// 12-Dec-2017, tatu: we would need something like this for "null masking", to handle
// special case of trailing "null chars": but for now it does not seem necessary.
// So cross that bridge if we ever get there
// q = _padLastQuadNoCheck(q, (-1 << 8));
} else {
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q = _padLastQuadNoCheck(q, (-1 << 16));
} else {
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q = _padLastQuadNoCheck(q, (-1 << 24));
} else {
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] == 0) {
_quad1 = q;
return _matchMediumName(matcher, qptr, i);
}
if (i != INT_QUOTE) {
return -1;
}
}
}
}
_quadPtr = qptr;
//System.err.printf("_matchName(0x%08x): %d\n", q, matcher.matchByQuad(q));
return matcher.matchByQuad(q);
}
protected final int _matchMediumName(PropertyNameMatcher matcher, int qptr, int q2) throws JacksonException
{
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
// Ok, got 5 name bytes so far, with `q2` last one we got
int i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q2 = _padLastQuadNoCheck(q2, (-1 << 8));
} else {
q2 = (q2 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q2 = _padLastQuadNoCheck(q2, (-1 << 16));
} else {
q2 = (q2 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q2 = _padLastQuadNoCheck(q2, (-1 << 24));
} else {
q2 = (q2 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] == 0) {
return _matchMediumName2(matcher, qptr, i, q2);
}
if (i != INT_QUOTE) {
return -1;
}
}
}
}
_quadPtr = qptr;
//System.err.printf("_matchMediumName(0x%08x,0x%08x): %d\n", _quad1, q2, matcher.matchByQuad(_quad1, q2));
return matcher.matchByQuad(_quad1, q2);
}
protected final int _matchMediumName2(PropertyNameMatcher matcher, int qptr,
int q3, final int q2) throws JacksonException
{
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
// Got 9 name bytes so far, q3 being the last
int i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q3 = _padLastQuadNoCheck(q3, (-1 << 8));
} else {
q3 = (q3 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q3 = _padLastQuadNoCheck(q3, (-1 << 16));
} else {
q3 = (q3 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// q3 = _padLastQuadNoCheck(q3, (-1 << 24));
} else {
q3 = (q3 << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] == 0) {
_quadBuffer[0] = _quad1;
_quadBuffer[1] = q2;
_quadBuffer[2] = q3;
return _matchLongName(matcher, qptr, i);
}
if (i != INT_QUOTE) {
return -1;
}
}
}
}
_quadPtr = qptr;
return matcher.matchByQuad(_quad1, q2, q3);
}
protected final int _matchLongName(PropertyNameMatcher matcher, int qptr,
int q) throws JacksonException
{
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
int qlen = 3;
while ((qptr + 4) <= _inputEnd) {
int i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// [core#1491]: Need to include partial quad in matching
_quadBuffer[qlen++] = q;
_quadPtr = qptr;
return matcher.matchByQuad(_quadBuffer, qlen);
}
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// [core#1491]: Need to include partial quad in matching
_quadBuffer[qlen++] = q;
_quadPtr = qptr;
return matcher.matchByQuad(_quadBuffer, qlen);
}
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// [core#1491]: Need to include partial quad in matching
_quadBuffer[qlen++] = q;
_quadPtr = qptr;
return matcher.matchByQuad(_quadBuffer, qlen);
}
q = (q << 8) | i;
i = input[qptr++] & 0xFF;
if (codes[i] != 0) {
if (i != INT_QUOTE) {
return -1;
}
// [core#1491]: Need to include partial quad in matching
_quadBuffer[qlen++] = q;
_quadPtr = qptr;
return matcher.matchByQuad(_quadBuffer, qlen);
}
// Nope, no end in sight. Need to grow quad array etc
if (qlen >= _quadBuffer.length) {
_quadBuffer = growArrayBy(_quadBuffer, qlen);
}
_quadBuffer[qlen++] = q;
q = i;
}
// Let's offline if we hit buffer boundary (otherwise would need to [try to]
// align input, which is bit complicated and may not always be possible)
return -1;
}
// 12-Dec-2017, tatu: Might need this to cover case of trailing "null chars"
// (Unicode character point 0); but since we have fallback lookup, does not
// actually look like this is necessary for our fast patch.
/*
private final static int _padLastQuadNoCheck(int q, int mask) {
return q;
}
*/
/*
/**********************************************************************
/* Public API, traversal, nextXxxValue() variants
/**********************************************************************
*/
@Override
public String nextStringValue() throws JacksonException
{
// two distinct cases; either got name and we know next type, or 'other'
if (_currToken == JsonToken.PROPERTY_NAME) { // mostly copied from '_nextAfterName'
_nameCopied = false;
JsonToken t = _nextToken;
_nextToken = null;
_updateToken(t);
if (t == JsonToken.VALUE_STRING) {
if (_tokenIncomplete) {
_tokenIncomplete = false;
return _finishAndReturnString();
}
return _textBuffer.contentsAsString();
}
if (t == JsonToken.START_ARRAY) {
createChildArrayContext(_tokenInputRow, _tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
createChildObjectContext(_tokenInputRow, _tokenInputCol);
}
return null;
}
// !!! TODO: optimize this case as well
return (nextToken() == JsonToken.VALUE_STRING) ? getString() : null;
}
@Override
public int nextIntValue(int defaultValue) throws JacksonException
{
// two distinct cases; either got name and we know next type, or 'other'
if (_currToken == JsonToken.PROPERTY_NAME) { // mostly copied from '_nextAfterName'
_nameCopied = false;
JsonToken t = _nextToken;
_nextToken = null;
_updateToken(t);
if (t == JsonToken.VALUE_NUMBER_INT) {
return getIntValue();
}
if (t == JsonToken.START_ARRAY) {
createChildArrayContext(_tokenInputRow, _tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
createChildObjectContext(_tokenInputRow, _tokenInputCol);
}
return defaultValue;
}
// !!! TODO: optimize this case as well
return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
}
@Override
public long nextLongValue(long defaultValue) throws JacksonException
{
// two distinct cases; either got name and we know next type, or 'other'
if (_currToken == JsonToken.PROPERTY_NAME) { // mostly copied from '_nextAfterName'
_nameCopied = false;
JsonToken t = _nextToken;
_nextToken = null;
_updateToken(t);
if (t == JsonToken.VALUE_NUMBER_INT) {
return getLongValue();
}
if (t == JsonToken.START_ARRAY) {
createChildArrayContext(_tokenInputRow, _tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
createChildObjectContext(_tokenInputRow, _tokenInputCol);
}
return defaultValue;
}
// !!! TODO: optimize this case as well
return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
}
@Override
public Boolean nextBooleanValue() throws JacksonException
{
// two distinct cases; either got name and we know next type, or 'other'
if (_currToken == JsonToken.PROPERTY_NAME) { // mostly copied from '_nextAfterName'
_nameCopied = false;
JsonToken t = _nextToken;
_nextToken = null;
_updateToken(t);
if (t == JsonToken.VALUE_TRUE) {
return Boolean.TRUE;
}
if (t == JsonToken.VALUE_FALSE) {
return Boolean.FALSE;
}
if (t == JsonToken.START_ARRAY) {
createChildArrayContext(_tokenInputRow, _tokenInputCol);
} else if (t == JsonToken.START_OBJECT) {
createChildObjectContext(_tokenInputRow, _tokenInputCol);
}
return null;
}
JsonToken t = nextToken();
if (t == JsonToken.VALUE_TRUE) {
return Boolean.TRUE;
}
if (t == JsonToken.VALUE_FALSE) {
return Boolean.FALSE;
}
return null;
}
/*
/**********************************************************************
/* Internal methods, number parsing
/**********************************************************************
*/
protected final JsonToken _parseFloatThatStartsWithPeriod(final boolean neg,
final boolean hasSign)
throws JacksonException
{
// [core#611]: allow optionally leading decimal point
if (!isEnabled(JsonReadFeature.ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS)) {
return _handleUnexpectedValue(INT_PERIOD);
}
final char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
int outPtr = 0;
// [core#784]: Include sign character ('+' or '-') in textual representation
if (hasSign) {
outBuf[outPtr++] = neg ? '-' : '+';
}
return _parseFloat(outBuf, outPtr, INT_PERIOD, neg, 0);
}
/**
* Initial parsing method for number values. It needs to be able
* to parse enough input to be able to determine whether the
* value is to be considered a simple integer value, or a more
* generic decimal value: latter of which needs to be expressed
* as a floating point number. The basic rule is that if the number
* has no fractional or exponential part, it is an integer; otherwise
* a floating point number.
*<p>
* Because much of input has to be processed in any case, no partial
* parsing is done: all input text will be stored for further
* processing. However, actual numeric value conversion will be
* deferred, since it is usually the most complicated and costliest
* part of processing.
*
* @param c The first non-null digit character of the number to parse
*
* @return Type of token decoded, usually {@link JsonToken#VALUE_NUMBER_INT}
* or {@link JsonToken#VALUE_NUMBER_FLOAT}
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems
*/
protected JsonToken _parseUnsignedNumber(int c) throws JacksonException
{
char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
// One special case: if first char is 0, must not be followed by a digit
if (c == INT_0) {
c = _verifyNoLeadingZeroes();
}
// Ok: we can first just add digit we saw first:
outBuf[0] = (char) c;
int intLen = 1;
int outPtr = 1;
// And then figure out how far we can read without further checks
// for either input or output
final int end = Math.min(_inputEnd, _inputPtr + outBuf.length - 1); // 1 == outPtr
// With this, we have a nice and tight loop:
while (true) {
if (_inputPtr >= end) { // split across boundary, offline
return _parseNumber2(outBuf, outPtr, false, intLen);
}
c = _inputBuffer[_inputPtr++] & 0xFF;
if (c < INT_0 || c > INT_9) {
break;
}
++intLen;
outBuf[outPtr++] = (char) c;
}
if (c == INT_PERIOD || (c | 0x20) == INT_e) { // ~ '.eE'
return _parseFloat(outBuf, outPtr, c, false, intLen);
}
--_inputPtr; // to push back trailing char (comma etc)
_textBuffer.setCurrentLength(outPtr);
// As per #105, need separating space between root values; check here
if (_streamReadContext.inRoot()) {
_verifyRootSpace(c);
}
// And there we have it!
return resetInt(false, intLen);
}
private final JsonToken _parseSignedNumber(boolean negative) throws JacksonException
{
char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
int outPtr = 0;
// [core#784]: Include sign character ('+' or '-') in textual representation
outBuf[outPtr++] = negative ? '-' : '+';
// Must have something after sign too
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
int c = _inputBuffer[_inputPtr++] & 0xFF;
// Note: must be followed by a digit
if (c <= INT_0) {
// One special case: if first char is 0, must not be followed by a digit
if (c != INT_0) {
if (c == INT_PERIOD) {
return _parseFloatThatStartsWithPeriod(negative, true);
}
return _handleInvalidNumberStart(c, negative, true);
}
c = _verifyNoLeadingZeroes();
} else if (c > INT_9) {
return _handleInvalidNumberStart(c, negative, true);
}
// Ok: we can first just add digit we saw first:
outBuf[outPtr++] = (char) c;
int intLen = 1;
// And then figure out how far we can read without further checks
// for either input or output
final int end = Math.min(_inputEnd, _inputPtr + outBuf.length - outPtr);
// With this, we have a nice and tight loop:
while (true) {
if (_inputPtr >= end) {
// Long enough to be split across boundary, so:
return _parseNumber2(outBuf, outPtr, negative, intLen);
}
c = _inputBuffer[_inputPtr++] & 0xFF;
if (c < INT_0 || c > INT_9) {
break;
}
++intLen;
outBuf[outPtr++] = (char) c;
}
if (c == INT_PERIOD || (c | 0x20) == INT_e) { // ~ '.eE'
return _parseFloat(outBuf, outPtr, c, negative, intLen);
}
--_inputPtr; // to push back trailing char (comma etc)
_textBuffer.setCurrentLength(outPtr);
// As per #105, need separating space between root values; check here
if (_streamReadContext.inRoot()) {
_verifyRootSpace(c);
}
// And there we have it!
return resetInt(negative, intLen);
}
// Method called to handle parsing when input is split across buffer boundary
// (or output is longer than segment used to store it)
private final JsonToken _parseNumber2(char[] outBuf, int outPtr, boolean negative,
int intPartLength) throws JacksonException
{
// Ok, parse the rest
while (true) {
if (_inputPtr >= _inputEnd && !_loadMore()) {
_textBuffer.setCurrentLength(outPtr);
return resetInt(negative, intPartLength);
}
int c = _inputBuffer[_inputPtr++] & 0xFF;
if (c > INT_9 || c < INT_0) {
if (c == INT_PERIOD || (c | 0x20) == INT_e) { // ~ '.eE'
return _parseFloat(outBuf, outPtr, c, negative, intPartLength);
}
break;
}
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
++intPartLength;
}
--_inputPtr; // to push back trailing char (comma etc)
_textBuffer.setCurrentLength(outPtr);
// As per #105, need separating space between root values; check here
if (_streamReadContext.inRoot()) {
_verifyRootSpace(_inputBuffer[_inputPtr] & 0xFF);
}
// And there we have it!
return resetInt(negative, intPartLength);
}
// Method called when we have seen one zero, and want to ensure
// it is not followed by another
private final int _verifyNoLeadingZeroes() throws JacksonException
{
// Ok to have plain "0"
if (_inputPtr >= _inputEnd && !_loadMore()) {
return INT_0;
}
int ch = _inputBuffer[_inputPtr] & 0xFF;
// if not followed by a number (probably '.'); return zero as is, to be included
if (ch < INT_0 || ch > INT_9) {
return INT_0;
}
// Optionally may accept leading zeroes:
if (!isEnabled(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)) {
return _reportInvalidNumber("Leading zeroes not allowed");
}
// if so, just need to skip either all zeroes (if followed by number); or all but one (if non-number)
++_inputPtr; // Leading zero to be skipped
if (ch == INT_0) {
while (_inputPtr < _inputEnd || _loadMore()) {
ch = _inputBuffer[_inputPtr] & 0xFF;
if (ch < INT_0 || ch > INT_9) { // followed by non-number; retain one zero
return INT_0;
}
++_inputPtr; // skip previous zeroes
if (ch != INT_0) { // followed by other number; return
break;
}
}
}
return ch;
}
private final JsonToken _parseFloat(char[] outBuf, int outPtr, int c,
boolean negative, int integerPartLength) throws JacksonException
{
int fractLen = 0;
boolean eof = false;
// And then see if we get other parts
if (c == INT_PERIOD) { // yes, fraction
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
fract_loop:
while (true) {
if (_inputPtr >= _inputEnd && !_loadMore()) {
eof = true;
break fract_loop;
}
c = _inputBuffer[_inputPtr++] & 0xFF;
if (c < INT_0 || c > INT_9) {
break fract_loop;
}
++fractLen;
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
}
// must be followed by sequence of ints, one minimum
if (fractLen == 0) {
if (!isEnabled(JsonReadFeature.ALLOW_TRAILING_DECIMAL_POINT_FOR_NUMBERS)) {
return _reportUnexpectedNumberChar(c, "Decimal point not followed by a digit");
}
}
}
int expLen = 0;
if ((c | 0x20) == INT_e) { // ~ 'eE' exponent?
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
// Not optional, can require that we get one more char
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
c = _inputBuffer[_inputPtr++] & 0xFF;
// Sign indicator?
if (c == '-' || c == '+') {
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
// Likewise, non optional:
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
c = _inputBuffer[_inputPtr++] & 0xFF;
}
exp_loop:
while (c >= INT_0 && c <= INT_9) {
++expLen;
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
outBuf[outPtr++] = (char) c;
if (_inputPtr >= _inputEnd && !_loadMore()) {
eof = true;
break exp_loop;
}
c = _inputBuffer[_inputPtr++] & 0xFF;
}
// must be followed by sequence of ints, one minimum
if (expLen == 0) {
return _reportUnexpectedNumberChar(c, "Exponent indicator not followed by a digit");
}
}
// Ok; unless we hit end-of-input, need to push last char read back
if (!eof) {
--_inputPtr;
// As per [core#105], need separating space between root values; check here
if (_streamReadContext.inRoot()) {
_verifyRootSpace(c);
}
}
_textBuffer.setCurrentLength(outPtr);
// And there we have it!
return resetFloat(negative, integerPartLength, fractLen, expLen);
}
/**
* Method called to ensure that a root-value is followed by a space
* token.
*<p>
* NOTE: caller MUST ensure there is at least one character available;
* and that input pointer is AT given char (not past)
*
* @param ch First character of likely white space to skip
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems (invalid white space)
*/
private final void _verifyRootSpace(int ch) throws JacksonException
{
// caller had pushed it back, before calling; reset
++_inputPtr;
// TODO? Handle UTF-8 char decoding for error reporting
switch (ch) {
case ' ':
case '\t':
return;
case '\r':
// 29-Oct-2022, tatu: [core#834] While issue is only relevant for char-backed
// sources, let's unify handling to keep behavior uniform.
// _skipCR();
--_inputPtr;
return;
case '\n':
++_currInputRow;
_currInputRowStart = _inputPtr;
return;
}
_reportMissingRootWS(ch);
}
/*
/**********************************************************************
/* Internal methods, secondary parsing
/**********************************************************************
*/
protected final String _parseName(int i) throws JacksonException
{
if (i != INT_QUOTE) {
return _handleOddName(i);
}
// First: can we optimize out bounds checks?
if ((_inputPtr + 13) > _inputEnd) { // Need up to 12 chars, plus one trailing (quote)
return slowParseName();
}
// If so, can also unroll loops nicely
/* 25-Nov-2008, tatu: This may seem weird, but here we do
* NOT want to worry about UTF-8 decoding. Rather, we'll
* assume that part is ok (if not it will get caught
* later on), and just handle quotes and backslashes here.
*/
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
int q = input[_inputPtr++] & 0xFF;
if (codes[q] == 0) {
i = input[_inputPtr++] & 0xFF;
if (codes[i] == 0) {
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] == 0) {
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] == 0) {
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] == 0) {
_quad1 = q;
return parseMediumName(i);
}
if (i == INT_QUOTE) { // 4 byte/char case or broken
return findName(q, 4);
}
return parseName(q, i, 4);
}
if (i == INT_QUOTE) { // 3 byte/char case or broken
return findName(q, 3);
}
return parseName(q, i, 3);
}
if (i == INT_QUOTE) { // 2 byte/char case or broken
return findName(q, 2);
}
return parseName(q, i, 2);
}
if (i == INT_QUOTE) { // one byte/char case or broken
return findName(q, 1);
}
return parseName(q, i, 1);
}
if (q == INT_QUOTE) { // special case, ""
return "";
}
return parseName(0, q, 0); // quoting or invalid char
}
protected final String parseMediumName(int q2) throws JacksonException
{
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
// Ok, got 5 name bytes so far
int i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 5 bytes
return findName(_quad1, q2, 1);
}
return parseName(_quad1, q2, i, 1); // quoting or invalid char
}
q2 = (q2 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 6 bytes
return findName(_quad1, q2, 2);
}
return parseName(_quad1, q2, i, 2);
}
q2 = (q2 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 7 bytes
return findName(_quad1, q2, 3);
}
return parseName(_quad1, q2, i, 3);
}
q2 = (q2 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 8 bytes
return findName(_quad1, q2, 4);
}
return parseName(_quad1, q2, i, 4);
}
return parseMediumName2(i, q2);
}
protected final String parseMediumName2(int q3, final int q2) throws JacksonException
{
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
// Got 9 name bytes so far
int i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 9 bytes
return findName(_quad1, q2, q3, 1);
}
return parseName(_quad1, q2, q3, i, 1);
}
q3 = (q3 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 10 bytes
return findName(_quad1, q2, q3, 2);
}
return parseName(_quad1, q2, q3, i, 2);
}
q3 = (q3 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 11 bytes
return findName(_quad1, q2, q3, 3);
}
return parseName(_quad1, q2, q3, i, 3);
}
q3 = (q3 << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) { // 12 bytes
return findName(_quad1, q2, q3, 4);
}
return parseName(_quad1, q2, q3, i, 4);
}
return parseLongName(i, q2, q3);
}
protected final String parseLongName(int q, final int q2, int q3) throws JacksonException
{
_quadBuffer[0] = _quad1;
_quadBuffer[1] = q2;
_quadBuffer[2] = q3;
// As explained above, will ignore UTF-8 encoding at this point
final byte[] input = _inputBuffer;
final int[] codes = _icLatin1;
int qlen = 3;
while ((_inputPtr + 4) <= _inputEnd) {
int i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) {
return findName(_quadBuffer, qlen, q, 1);
}
return parseEscapedName(_quadBuffer, qlen, q, i, 1);
}
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) {
return findName(_quadBuffer, qlen, q, 2);
}
return parseEscapedName(_quadBuffer, qlen, q, i, 2);
}
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) {
return findName(_quadBuffer, qlen, q, 3);
}
return parseEscapedName(_quadBuffer, qlen, q, i, 3);
}
q = (q << 8) | i;
i = input[_inputPtr++] & 0xFF;
if (codes[i] != 0) {
if (i == INT_QUOTE) {
return findName(_quadBuffer, qlen, q, 4);
}
return parseEscapedName(_quadBuffer, qlen, q, i, 4);
}
// Nope, no end in sight. Need to grow quad array etc
if (qlen >= _quadBuffer.length) {
_quadBuffer = _growNameDecodeBuffer(_quadBuffer, qlen);
}
_quadBuffer[qlen++] = q;
q = i;
}
/* Let's offline if we hit buffer boundary (otherwise would
* need to [try to] align input, which is bit complicated
* and may not always be possible)
*/
return parseEscapedName(_quadBuffer, qlen, 0, q, 0);
}
// Method called when not even first 8 bytes are guaranteed
// to come consecutively. Happens rarely, so this is offlined;
// plus we'll also do full checks for escaping etc.
protected String slowParseName() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _reportInvalidEOF(": was expecting closing '\"' for name", JsonToken.PROPERTY_NAME);
}
}
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i == INT_QUOTE) { // special case, ""
return "";
}
return parseEscapedName(_quadBuffer, 0, 0, i, 0);
}
private final String parseName(int q1, int ch, int lastQuadBytes) throws JacksonException {
return parseEscapedName(_quadBuffer, 0, q1, ch, lastQuadBytes);
}
private final String parseName(int q1, int q2, int ch, int lastQuadBytes) throws JacksonException {
_quadBuffer[0] = q1;
return parseEscapedName(_quadBuffer, 1, q2, ch, lastQuadBytes);
}
private final String parseName(int q1, int q2, int q3, int ch, int lastQuadBytes) throws JacksonException {
_quadBuffer[0] = q1;
_quadBuffer[1] = q2;
return parseEscapedName(_quadBuffer, 2, q3, ch, lastQuadBytes);
}
// Slower parsing method which is generally branched to when an escape
// sequence is detected (or alternatively for long names, one crossing
// input buffer boundary). Needs to be able to handle more exceptional
// cases, gets slower, and hence is offlined to a separate method.
protected final String parseEscapedName(int[] quads, int qlen, int currQuad, int ch,
int currQuadBytes) throws JacksonException
{
// This may seem weird, but here we do not want to worry about
// UTF-8 decoding yet. Rather, we'll assume that part is ok (if not it will get
// caught later on), and just handle quotes and backslashes here.
final int[] codes = _icLatin1;
while (true) {
if (codes[ch] != 0) {
if (ch == INT_QUOTE) { // we are done
break;
}
// Unquoted white space?
if (ch != INT_BACKSLASH) {
// As per [JACKSON-208], call can now return:
_throwUnquotedSpace(ch, "name");
} else {
// Nope, escape sequence
ch = _decodeEscaped();
}
// Oh crap. May need to UTF-8 (re-)encode it, if it's beyond
// 7-bit ASCII. Gets pretty messy. If this happens often, may
// want to use different name canonicalization to avoid these hits.
if (ch > 127) {
// Ok, we'll need room for first byte right away
if (currQuadBytes >= 4) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = 0;
currQuadBytes = 0;
}
if (ch < 0x800) { // 2-byte
currQuad = (currQuad << 8) | (0xc0 | (ch >> 6));
++currQuadBytes;
// Second byte gets output below:
} else { // 3 bytes; no need to worry about surrogates here
currQuad = (currQuad << 8) | (0xe0 | (ch >> 12));
++currQuadBytes;
// need room for middle byte?
if (currQuadBytes >= 4) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = 0;
currQuadBytes = 0;
}
currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f));
++currQuadBytes;
}
// And same last byte in both cases, gets output below:
ch = 0x80 | (ch & 0x3f);
}
}
// Ok, we have one more byte to add at any rate:
if (currQuadBytes < 4) {
++currQuadBytes;
currQuad = (currQuad << 8) | ch;
} else {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _reportInvalidEOF(" in property name", JsonToken.PROPERTY_NAME);
}
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
}
if (currQuadBytes > 0) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = _padLastQuad(currQuad, currQuadBytes);
}
String name = _symbols.findName(quads, qlen);
if (name == null) {
name = addName(quads, qlen, currQuadBytes);
}
return name;
}
/**
* Method called when we see non-white space character other
* than double quote, when expecting a property name.
* In standard mode will just throw an exception; but
* in non-standard modes may be able to parse name.
*
* @param ch First undecoded character of possible "odd name" to decode
*
* @return Name decoded, if allowed and successful
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems (invalid name)
*/
protected String _handleOddName(int ch) throws JacksonException
{
// First: may allow single quotes
if (ch == INT_APOS && isEnabled(JsonReadFeature.ALLOW_SINGLE_QUOTES)) {
return _parseAposName();
}
// Allow unquoted names only if feature enabled:
if (!isEnabled(JsonReadFeature.ALLOW_UNQUOTED_PROPERTY_NAMES)) {
char c = (char) _decodeCharForError(ch);
return _reportUnexpectedChar(c, "was expecting double-quote to start property name");
}
/* Also: note that although we use a different table here,
* it does NOT handle UTF-8 decoding. It'll just pass those
* high-bit codes as acceptable for later decoding.
*/
final int[] codes = CharTypes.getInputCodeUtf8JsNames();
// Also: must start with a valid character...
if (codes[ch] != 0) {
return _reportUnexpectedChar(ch, "was expecting either valid name character (for unquoted name) or double-quote (for quoted) to start property name");
}
// Ok, now; instead of ultra-optimizing parsing here (as with regular
// JSON names), let's just use the generic "slow" variant.
// Can measure its impact later on if need be.
int[] quads = _quadBuffer;
int qlen = 0;
int currQuad = 0;
int currQuadBytes = 0;
while (true) {
// Ok, we have one more byte to add at any rate:
if (currQuadBytes < 4) {
++currQuadBytes;
currQuad = (currQuad << 8) | ch;
} else {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _reportInvalidEOF(" in property name", JsonToken.PROPERTY_NAME);
}
}
ch = _inputBuffer[_inputPtr] & 0xFF;
if (codes[ch] != 0) {
break;
}
++_inputPtr;
}
if (currQuadBytes > 0) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
}
String name = _symbols.findName(quads, qlen);
if (name == null) {
name = addName(quads, qlen, currQuadBytes);
}
return name;
}
// Parsing to support apostrope-quoted names. Plenty of duplicated code;
// main reason being to try to avoid slowing down fast path
// for valid JSON -- more alternatives, more code, generally
// bit slower execution.
protected String _parseAposName() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _reportInvalidEOF(": was expecting closing '\'' for property name", JsonToken.PROPERTY_NAME);
}
}
int ch = _inputBuffer[_inputPtr++] & 0xFF;
if (ch == INT_APOS) { // special case, ''
return "";
}
int[] quads = _quadBuffer;
int qlen = 0;
int currQuad = 0;
int currQuadBytes = 0;
// Copied from parseEscapedName, with minor mods:
final int[] codes = _icLatin1;
while (true) {
if (ch == INT_APOS) {
break;
}
// additional check to skip handling of double-quotes
if ((codes[ch] != 0) && (ch != INT_QUOTE)) {
if (ch != '\\') {
// Unquoted white space?
// As per [JACKSON-208], call can now return:
_throwUnquotedSpace(ch, "name");
} else {
// Nope, escape sequence
ch = _decodeEscaped();
}
// as per main code, inefficient but will have to do
if (ch > 127) {
// Ok, we'll need room for first byte right away
if (currQuadBytes >= 4) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = 0;
currQuadBytes = 0;
}
if (ch < 0x800) { // 2-byte
currQuad = (currQuad << 8) | (0xc0 | (ch >> 6));
++currQuadBytes;
// Second byte gets output below:
} else { // 3 bytes; no need to worry about surrogates here
currQuad = (currQuad << 8) | (0xe0 | (ch >> 12));
++currQuadBytes;
// need room for middle byte?
if (currQuadBytes >= 4) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = 0;
currQuadBytes = 0;
}
currQuad = (currQuad << 8) | (0x80 | ((ch >> 6) & 0x3f));
++currQuadBytes;
}
// And same last byte in both cases, gets output below:
ch = 0x80 | (ch & 0x3f);
}
}
// Ok, we have one more byte to add at any rate:
if (currQuadBytes < 4) {
++currQuadBytes;
currQuad = (currQuad << 8) | ch;
} else {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = currQuad;
currQuad = ch;
currQuadBytes = 1;
}
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _reportInvalidEOF(" in property name", JsonToken.PROPERTY_NAME);
}
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
}
if (currQuadBytes > 0) {
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = _padLastQuad(currQuad, currQuadBytes);
}
String name = _symbols.findName(quads, qlen);
if (name == null) {
name = addName(quads, qlen, currQuadBytes);
}
return name;
}
/*
/**********************************************************************
/* Internal methods, symbol (name) handling
/**********************************************************************
*/
private final String findName(int q1, int lastQuadBytes) throws StreamReadException
{
q1 = _padLastQuad(q1, lastQuadBytes);
// Usually we'll find it from the canonical symbol table already
String name = _symbols.findName(q1);
if (name != null) {
return name;
}
// If not, more work. We'll need add stuff to buffer
_quadBuffer[0] = q1;
return addName(_quadBuffer, 1, lastQuadBytes);
}
private final String findName(int q1, int q2, int lastQuadBytes) throws StreamReadException
{
q2 = _padLastQuad(q2, lastQuadBytes);
// Usually we'll find it from the canonical symbol table already
String name = _symbols.findName(q1, q2);
if (name != null) {
return name;
}
// If not, more work. We'll need add stuff to buffer
_quadBuffer[0] = q1;
_quadBuffer[1] = q2;
return addName(_quadBuffer, 2, lastQuadBytes);
}
private final String findName(int q1, int q2, int q3, int lastQuadBytes) throws StreamReadException
{
q3 = _padLastQuad(q3, lastQuadBytes);
String name = _symbols.findName(q1, q2, q3);
if (name != null) {
return name;
}
int[] quads = _quadBuffer;
quads[0] = q1;
quads[1] = q2;
quads[2] = _padLastQuad(q3, lastQuadBytes);
return addName(quads, 3, lastQuadBytes);
}
private final String findName(int[] quads, int qlen, int lastQuad, int lastQuadBytes)
throws StreamReadException
{
if (qlen >= quads.length) {
_quadBuffer = quads = _growNameDecodeBuffer(quads, quads.length);
}
quads[qlen++] = _padLastQuad(lastQuad, lastQuadBytes);
String name = _symbols.findName(quads, qlen);
if (name == null) {
return addName(quads, qlen, lastQuadBytes);
}
return name;
}
/* This is the main workhorse method used when we take a symbol
* table miss. It needs to demultiplex individual bytes, decode
* multi-byte chars (if any), and then construct Name instance
* and add it to the symbol table.
*/
private final String addName(int[] quads, int qlen, int lastQuadBytes)
throws StreamReadException
{
/* Ok: must decode UTF-8 chars. No other validation is
* needed, since unescaping has been done earlier as necessary
* (as well as error reporting for unescaped control chars)
*/
// 4 bytes per quad, except last one maybe less
final int byteLen = (qlen << 2) - 4 + lastQuadBytes;
_streamReadConstraints.validateNameLength(byteLen);
/* And last one is not correctly aligned (leading zero bytes instead
* need to shift a bit, instead of trailing). Only need to shift it
* for UTF-8 decoding; need revert for storage (since key will not
* be aligned, to optimize lookup speed)
*/
int lastQuad;
if (lastQuadBytes < 4) {
lastQuad = quads[qlen-1];
// 8/16/24 bit left shift
quads[qlen-1] = (lastQuad << ((4 - lastQuadBytes) << 3));
} else {
lastQuad = 0;
}
// Need some working space, TextBuffer works well:
char[] cbuf = _textBuffer.emptyAndGetCurrentSegment();
int cix = 0;
for (int ix = 0; ix < byteLen; ) {
int ch = quads[ix >> 2]; // current quad, need to shift+mask
int byteIx = (ix & 3);
ch = (ch >> ((3 - byteIx) << 3)) & 0xFF;
++ix;
if (ch > 127) { // multi-byte
int needed;
if ((ch & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF)
ch &= 0x1F;
needed = 1;
} else if ((ch & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF)
ch &= 0x0F;
needed = 2;
} else if ((ch & 0xF8) == 0xF0) { // 4 bytes; double-char with surrogates and all...
ch &= 0x07;
needed = 3;
} else { // 5- and 6-byte chars not valid json chars
return _reportInvalidInitial(ch);
}
if ((ix + needed) > byteLen) {
_reportInvalidEOF(" in property name", JsonToken.PROPERTY_NAME);
}
// Ok, always need at least one more:
int ch2 = quads[ix >> 2]; // current quad, need to shift+mask
byteIx = (ix & 3);
ch2 = (ch2 >> ((3 - byteIx) << 3));
++ix;
if ((ch2 & 0xC0) != 0x080) {
_reportInvalidOther(ch2);
}
ch = (ch << 6) | (ch2 & 0x3F);
if (needed > 1) {
ch2 = quads[ix >> 2];
byteIx = (ix & 3);
ch2 = (ch2 >> ((3 - byteIx) << 3));
++ix;
if ((ch2 & 0xC0) != 0x080) {
_reportInvalidOther(ch2);
}
ch = (ch << 6) | (ch2 & 0x3F);
// [jackson-core#363]: Surrogates (0xD800 - 0xDFFF) are illegal in UTF-8 for 3-byte sequences
if (needed == 2) {
if (ch >= 0xD800 && ch <= 0xDFFF) {
_reportInvalidUTF8Surrogate(ch);
}
} else { // 4 bytes? (need surrogates on output)
ch2 = quads[ix >> 2];
byteIx = (ix & 3);
ch2 = (ch2 >> ((3 - byteIx) << 3));
++ix;
if ((ch2 & 0xC0) != 0x080) {
_reportInvalidOther(ch2 & 0xFF);
}
ch = (ch << 6) | (ch2 & 0x3F);
}
}
if (needed > 2) { // surrogate pair? once again, let's output one here, one later on
ch -= 0x10000; // to normalize it starting with 0x0
if (cix >= cbuf.length) {
cbuf = _textBuffer.expandCurrentSegment();
}
cbuf[cix++] = (char) (0xD800 + (ch >> 10));
ch = 0xDC00 | (ch & 0x03FF);
}
}
if (cix >= cbuf.length) {
cbuf = _textBuffer.expandCurrentSegment();
}
cbuf[cix++] = (char) ch;
}
// Ok. Now we have the character array, and can construct the String
String baseName = new String(cbuf, 0, cix);
// And finally, un-align if necessary
if (lastQuadBytes < 4) {
quads[qlen-1] = lastQuad;
}
return _symbols.addName(baseName, quads, qlen);
}
// Helper method needed to fix [jackson-core#148], masking of 0x00 character
private final static int _padLastQuad(int q, int bytes) {
return (bytes == 4) ? q : (q | (-1 << (bytes << 3)));
}
/*
/**********************************************************************
/* Internal methods, String value parsing
/**********************************************************************
*/
protected void _loadMoreGuaranteed() throws JacksonException {
if (!_loadMore()) { _reportInvalidEOF(); }
}
protected void _finishString() throws JacksonException
{
// First, single tight loop for ASCII content, not split across input buffer boundary:
int ptr = _inputPtr;
if (ptr >= _inputEnd) {
_loadMoreGuaranteed();
ptr = _inputPtr;
}
int outPtr = 0;
char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
final int[] codes = _icUTF8;
final int max = Math.min(_inputEnd, (ptr + outBuf.length));
final byte[] inputBuffer = _inputBuffer;
while (ptr < max) {
int c = inputBuffer[ptr] & 0xFF;
if (codes[c] != 0) {
if (c == INT_QUOTE) {
_inputPtr = ptr+1;
_textBuffer.setCurrentLength(outPtr);
return;
}
break;
}
++ptr;
outBuf[outPtr++] = (char) c;
}
_inputPtr = ptr;
_finishString2(outBuf, outPtr);
}
protected String _finishAndReturnString() throws JacksonException
{
// First, single tight loop for ASCII content, not split across input buffer boundary:
int ptr = _inputPtr;
if (ptr >= _inputEnd) {
_loadMoreGuaranteed();
ptr = _inputPtr;
}
int outPtr = 0;
char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
final int[] codes = _icUTF8;
final int max = Math.min(_inputEnd, (ptr + outBuf.length));
final byte[] inputBuffer = _inputBuffer;
while (ptr < max) {
int c = inputBuffer[ptr] & 0xFF;
if (codes[c] != 0) {
if (c == INT_QUOTE) {
_inputPtr = ptr+1;
return _textBuffer.setCurrentAndReturn(outPtr);
}
break;
}
++ptr;
outBuf[outPtr++] = (char) c;
}
_inputPtr = ptr;
_finishString2(outBuf, outPtr);
return _textBuffer.contentsAsString();
}
private final void _finishString2(char[] outBuf, int outPtr)
throws JacksonException
{
int c;
// Here we do want to do full decoding, hence:
final int[] codes = _icUTF8;
final byte[] inputBuffer = _inputBuffer;
main_loop:
while (true) {
// Then the tight ASCII non-funny-char loop:
ascii_loop:
while (true) {
int ptr = _inputPtr;
if (ptr >= _inputEnd) {
_loadMoreGuaranteed();
ptr = _inputPtr;
}
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
final int max = Math.min(
_inputEnd,
InternalJacksonUtil.addOverflowSafe(ptr, outBuf.length - outPtr));
while (ptr < max) {
c = inputBuffer[ptr++] & 0xFF;
if (codes[c] != 0) {
_inputPtr = ptr;
break ascii_loop;
}
outBuf[outPtr++] = (char) c;
}
_inputPtr = ptr;
}
// Ok: end marker, escape or multi-byte?
if (c == INT_QUOTE) {
break main_loop;
}
switch (codes[c]) {
case 1: // backslash
c = _decodeEscaped();
break;
case 2: // 2-byte UTF
c = _decodeUtf8_2(c);
break;
case 3: // 3-byte UTF
if ((_inputEnd - _inputPtr) >= 2) {
c = _decodeUtf8_3fast(c);
} else {
c = _decodeUtf8_3(c);
}
break;
case 4: // 4-byte UTF
c = _decodeUtf8_4(c);
// Let's add first part right away:
outBuf[outPtr++] = (char) (0xD800 | (c >> 10));
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
c = 0xDC00 | (c & 0x3FF);
// And let the other char output down below
break;
default:
if (c < INT_SPACE) {
// As per [JACKSON-208], call can now return:
_throwUnquotedSpace(c, "string value");
} else {
// Is this good enough error message?
_reportInvalidChar(c);
}
}
// Need more room?
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
// Ok, let's add char to output:
outBuf[outPtr++] = (char) c;
}
_textBuffer.setCurrentLength(outPtr);
}
/**
* Method called to skim through rest of unparsed String value,
* if it is not needed. This can be done bit faster if contents
* need not be stored for future access.
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems (invalid String value)
*/
protected void _skipString() throws JacksonException
{
_tokenIncomplete = false;
// Need to be fully UTF-8 aware here:
final int[] codes = _icUTF8;
final byte[] inputBuffer = _inputBuffer;
main_loop:
while (true) {
int c;
ascii_loop:
while (true) {
int ptr = _inputPtr;
int max = _inputEnd;
if (ptr >= max) {
_loadMoreGuaranteed();
ptr = _inputPtr;
max = _inputEnd;
}
while (ptr < max) {
c = inputBuffer[ptr++] & 0xFF;
if (codes[c] != 0) {
_inputPtr = ptr;
break ascii_loop;
}
}
_inputPtr = ptr;
}
// Ok: end marker, escape or multi-byte?
if (c == INT_QUOTE) {
break main_loop;
}
switch (codes[c]) {
case 1: // backslash
_decodeEscaped();
break;
case 2: // 2-byte UTF
_skipUtf8_2();
break;
case 3: // 3-byte UTF
_skipUtf8_3();
break;
case 4: // 4-byte UTF
_skipUtf8_4(c);
break;
default:
if (c < INT_SPACE) {
_throwUnquotedSpace(c, "string value");
} else {
// Is this good enough error message?
_reportInvalidChar(c);
}
}
}
}
/**
* Method for handling cases where first non-space character
* of an expected value token is not legal for standard JSON content.
*
* @param c First undecoded character of possible "odd value" to decode
*
* @return Type of value decoded, if allowed and successful
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems
*/
protected JsonToken _handleUnexpectedValue(int c) throws JacksonException
{
// Most likely an error, unless we are to allow single-quote-strings
switch (c) {
/* This check proceeds only if `Feature.ALLOW_MISSING_VALUES` is enabled;
* it is for missing values. In case of missing values in an array the next token
* will be either ',' or ']'. This case, decrements the already incremented _inputPtr
* in the buffer in case of comma (`,`) so that the existing flow goes back to checking
* the next token which will be comma again and it parsing continues.
* Also the case returns NULL as current token in case of ',' or ']'.
*/
case ']':
if (!_streamReadContext.inArray()) {
break;
}
// fall through
case ',':
// 28-Mar-2016: [core#116]: If Feature.ALLOW_MISSING_VALUES is enabled
// we may allow "missing values", that is, encountering a trailing
// comma or closing marker where value would be expected
// 11-May-2020, tatu: [core#616] No commas in root level
if (!_streamReadContext.inRoot()) {
if ((_formatReadFeatures & FEAT_MASK_ALLOW_MISSING) != 0) {
--_inputPtr;
return JsonToken.VALUE_NULL;
}
}
// fall through
case '}':
// Error: neither is valid at this point; valid closers have
// been handled earlier
_reportUnexpectedChar(c, "expected a value");
case '\'':
if (isEnabled(JsonReadFeature.ALLOW_SINGLE_QUOTES)) {
return _handleApos();
}
break;
case 'N':
_matchToken("NaN", 1);
if (isEnabled(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS)) {
return resetAsNaN("NaN", Double.NaN);
}
_reportError("Non-standard token 'NaN': enable `JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS` to allow");
break;
case 'I':
_matchToken("Infinity", 1);
if (isEnabled(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS)) {
return resetAsNaN("Infinity", Double.POSITIVE_INFINITY);
}
_reportError("Non-standard token 'Infinity': enable `JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS` to allow");
break;
case '+': // note: '-' is taken as number
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
_reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_INT);
}
}
return _handleInvalidNumberStart(_inputBuffer[_inputPtr++] & 0xFF, false, true);
}
// [core#77] Try to decode most likely token
if (Character.isJavaIdentifierStart(c)) {
_reportInvalidToken(""+((char) c), _validJsonTokenList());
}
// but if it doesn't look like a token:
_reportUnexpectedChar(c, "expected a valid value "+_validJsonValueList());
return null;
}
protected JsonToken _handleApos() throws JacksonException
{
int c = 0;
// Otherwise almost verbatim copy of _finishString()
int outPtr = 0;
char[] outBuf = _textBuffer.emptyAndGetCurrentSegment();
// Here we do want to do full decoding, hence:
final int[] codes = _icUTF8;
final byte[] inputBuffer = _inputBuffer;
main_loop:
while (true) {
// Then the tight ascii non-funny-char loop:
ascii_loop:
while (true) {
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
int max = _inputEnd;
{
final int max2 =
InternalJacksonUtil.addOverflowSafe(_inputPtr, outBuf.length - outPtr);
if (max2 < max) {
max = max2;
}
}
while (_inputPtr < max) {
c = inputBuffer[_inputPtr++] & 0xFF;
if (c == INT_APOS) {
break main_loop;
}
if ((codes[c] != 0)
// 13-Oct-2021, tatu: [core#721] Alas, regular quote is included as
// special, need to ignore here
&& (c != INT_QUOTE)) {
break ascii_loop;
}
outBuf[outPtr++] = (char) c;
}
}
switch (codes[c]) {
case 1: // backslash
c = _decodeEscaped();
break;
case 2: // 2-byte UTF
c = _decodeUtf8_2(c);
break;
case 3: // 3-byte UTF
if ((_inputEnd - _inputPtr) >= 2) {
c = _decodeUtf8_3fast(c);
} else {
c = _decodeUtf8_3(c);
}
break;
case 4: // 4-byte UTF
c = _decodeUtf8_4(c);
// Let's add first part right away:
outBuf[outPtr++] = (char) (0xD800 | (c >> 10));
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
c = 0xDC00 | (c & 0x3FF);
// And let the other char output down below
break;
default:
if (c < INT_SPACE) {
_throwUnquotedSpace(c, "string value");
}
// Is this good enough error message?
_reportInvalidChar(c);
}
// Need more room?
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
// Ok, let's add char to output:
outBuf[outPtr++] = (char) c;
}
_textBuffer.setCurrentLength(outPtr);
return JsonToken.VALUE_STRING;
}
/*
/**********************************************************************
/* Internal methods, well-known token decoding
/**********************************************************************
*/
// Method called if expected numeric value (due to leading sign) does not
// look like a number
protected JsonToken _handleInvalidNumberStart(int ch, final boolean neg) throws JacksonException
{
return _handleInvalidNumberStart(ch, neg, false);
}
protected JsonToken _handleInvalidNumberStart(int ch, final boolean neg, final boolean hasSign) throws JacksonException
{
while (ch == 'I') {
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
_reportInvalidEOFInValue(JsonToken.VALUE_NUMBER_FLOAT); // possibly?
}
}
ch = _inputBuffer[_inputPtr++];
String match;
if (ch == 'N') {
match = neg ? "-INF" :"+INF";
} else if (ch == 'n') {
match = neg ? "-Infinity" :"+Infinity";
} else {
break;
}
_matchToken(match, 3);
if (isEnabled(JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS)) {
return resetAsNaN(match, neg ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY);
}
return _reportError("Non-standard token '%s': enable `JsonReadFeature.ALLOW_NON_NUMERIC_NUMBERS` to allow",
match);
}
if (!isEnabled(JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS) && hasSign && !neg) {
return _reportUnexpectedNumberChar('+', "JSON spec does not allow numbers to have plus signs: enable `JsonReadFeature.ALLOW_LEADING_PLUS_SIGN_FOR_NUMBERS` to allow");
}
final String message = neg ?
"expected digit (0-9) to follow minus sign, for valid numeric value" :
"expected digit (0-9) for valid numeric value";
return _reportUnexpectedNumberChar(ch, message);
}
// NOTE: first character already decoded
protected final void _matchTrue() throws JacksonException
{
int ptr = _inputPtr;
if ((ptr + 3) < _inputEnd) {
byte[] buf = _inputBuffer;
if ((buf[ptr++] == 'r')
&& (buf[ptr++] == 'u')
&& (buf[ptr++] == 'e')) {
int ch = buf[ptr] & 0xFF;
if (ch < INT_0 || (ch | 0x20) == INT_RCURLY) { // < '0' || ~ '}]' expected/allowed chars
_inputPtr = ptr;
return;
}
}
}
_matchToken2("true", 1);
}
protected final void _matchFalse() throws JacksonException
{
int ptr = _inputPtr;
if ((ptr + 4) < _inputEnd) {
byte[] buf = _inputBuffer;
if ((buf[ptr++] == 'a')
&& (buf[ptr++] == 'l')
&& (buf[ptr++] == 's')
&& (buf[ptr++] == 'e')) {
int ch = buf[ptr] & 0xFF;
if (ch < INT_0 || (ch | 0x20) == INT_RCURLY) { // < '0' || ~ '}]' expected/allowed chars
_inputPtr = ptr;
return;
}
}
}
_matchToken2("false", 1);
}
protected final void _matchNull() throws JacksonException
{
int ptr = _inputPtr;
if ((ptr + 3) < _inputEnd) {
byte[] buf = _inputBuffer;
if ((buf[ptr++] == 'u')
&& (buf[ptr++] == 'l')
&& (buf[ptr++] == 'l')) {
int ch = buf[ptr] & 0xFF;
if (ch < INT_0 || (ch | 0x20) == INT_RCURLY) { // < '0' || ~ '}]' expected/allowed chars
_inputPtr = ptr;
return;
}
}
}
_matchToken2("null", 1);
}
protected final void _matchToken(String matchStr, int i) throws JacksonException
{
final int len = matchStr.length();
if ((_inputPtr + len) >= _inputEnd) {
_matchToken2(matchStr, i);
return;
}
do {
if (_inputBuffer[_inputPtr] != matchStr.charAt(i)) {
_reportInvalidToken(matchStr.substring(0, i));
}
++_inputPtr;
} while (++i < len);
int ch = _inputBuffer[_inputPtr] & 0xFF;
if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars
_checkMatchEnd(matchStr, i, ch);
}
}
private final void _matchToken2(String matchStr, int i) throws JacksonException
{
final int len = matchStr.length();
do {
if (((_inputPtr >= _inputEnd) && !_loadMore())
|| (_inputBuffer[_inputPtr] != matchStr.charAt(i))) {
_reportInvalidToken(matchStr.substring(0, i));
}
++_inputPtr;
} while (++i < len);
// but let's also ensure we either get EOF, or non-alphanum char...
if (_inputPtr >= _inputEnd && !_loadMore()) {
return;
}
int ch = _inputBuffer[_inputPtr] & 0xFF;
if (ch >= '0' && ch != ']' && ch != '}') { // expected/allowed chars
_checkMatchEnd(matchStr, i, ch);
}
}
private final void _checkMatchEnd(String matchStr, int i, int ch) throws JacksonException {
// but actually only alphanums are problematic
char c = (char) _decodeCharForError(ch);
if (Character.isJavaIdentifierPart(c)) {
_reportInvalidToken(matchStr.substring(0, i));
}
}
/*
/**********************************************************************
/* Internal methods, ws skipping, escape/unescape
/**********************************************************************
*/
private final int _skipWS() throws JacksonException
{
while (_inputPtr < _inputEnd) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
--_inputPtr;
return _skipWS2();
}
return i;
}
if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB) {
_reportInvalidSpace(i);
}
}
}
return _skipWS2();
}
private final int _skipWS2() throws JacksonException
{
while (_inputPtr < _inputEnd || _loadMore()) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH) {
_skipComment();
continue;
}
if (i == INT_HASH) {
if (_skipYAMLComment()) {
continue;
}
}
return i;
}
if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB) {
_reportInvalidSpace(i);
}
}
}
throw _constructReadException("Unexpected end-of-input within/between "+_streamReadContext.typeDesc()+" entries");
}
private final int _skipWSOrEnd() throws JacksonException
{
// Let's handle first character separately since it is likely that
// it is either non-whitespace; or we have longer run of white space
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
return _eofAsNextChar();
}
}
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
--_inputPtr;
return _skipWSOrEnd2();
}
return i;
}
if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB && !_isAllowedCtrlCharRS(i)) {
_reportInvalidSpace(i);
}
}
while (_inputPtr < _inputEnd) {
i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
--_inputPtr;
return _skipWSOrEnd2();
}
return i;
}
if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB && !_isAllowedCtrlCharRS(i)) {
_reportInvalidSpace(i);
}
}
}
return _skipWSOrEnd2();
}
private final int _skipWSOrEnd2() throws JacksonException
{
while ((_inputPtr < _inputEnd) || _loadMore()) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH) {
_skipComment();
continue;
}
if (i == INT_HASH) {
if (_skipYAMLComment()) {
continue;
}
}
return i;
} else if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB) {
_reportInvalidSpace(i);
}
}
}
// We ran out of input...
return _eofAsNextChar();
}
private final int _skipColon() throws JacksonException
{
if ((_inputPtr + 4) >= _inputEnd) {
return _skipColon2(false);
}
// Fast path: colon with optional single-space/tab before and/or after:
int i = _inputBuffer[_inputPtr];
if (i == INT_COLON) { // common case, no leading space
i = _inputBuffer[++_inputPtr];
if (i > INT_SPACE) { // nor trailing
if (i == INT_SLASH || i == INT_HASH) {
return _skipColon2(true);
}
++_inputPtr;
return i;
}
if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[++_inputPtr];
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
return _skipColon2(true);
}
++_inputPtr;
return i;
}
}
return _skipColon2(true); // true -> skipped colon
}
if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[++_inputPtr];
}
if (i == INT_COLON) {
i = _inputBuffer[++_inputPtr];
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
return _skipColon2(true);
}
++_inputPtr;
return i;
}
if (i == INT_SPACE || i == INT_TAB) {
i = _inputBuffer[++_inputPtr];
if (i > INT_SPACE) {
if (i == INT_SLASH || i == INT_HASH) {
return _skipColon2(true);
}
++_inputPtr;
return i;
}
}
return _skipColon2(true);
}
return _skipColon2(false);
}
private final int _skipColon2(boolean gotColon) throws JacksonException
{
while (_inputPtr < _inputEnd || _loadMore()) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
if (i > INT_SPACE) {
if (i == INT_SLASH) {
_skipComment();
continue;
}
if (i == INT_HASH) {
if (_skipYAMLComment()) {
continue;
}
}
if (gotColon) {
return i;
}
if (i != INT_COLON) {
_reportUnexpectedChar(i, "was expecting a colon to separate property name and value");
}
gotColon = true;
} else if (i != INT_SPACE) {
if (i == INT_LF) {
++_currInputRow;
_currInputRowStart = _inputPtr;
} else if (i == INT_CR) {
_skipCR();
} else if (i != INT_TAB) {
_reportInvalidSpace(i);
}
}
}
_reportInvalidEOF(" within/between "+_streamReadContext.typeDesc()+" entries",
null);
return -1;
}
private final void _skipComment() throws JacksonException
{
if (!isEnabled(JsonReadFeature.ALLOW_JAVA_COMMENTS)) {
_reportUnexpectedChar('/', "maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)");
}
// First: check which comment (if either) it is:
if (_inputPtr >= _inputEnd && !_loadMore()) {
_reportInvalidEOF(" in a comment", null);
}
int c = _inputBuffer[_inputPtr++] & 0xFF;
if (c == INT_SLASH) {
_skipLine();
} else if (c == INT_ASTERISK) {
_skipCComment();
} else {
_reportUnexpectedChar(c, "was expecting either '*' or '/' for a comment");
}
}
private final void _skipCComment() throws JacksonException
{
// Need to be UTF-8 aware here to decode content (for skipping)
final int[] codes = CharTypes.getInputCodeComment();
// Ok: need the matching '*/'
main_loop:
while ((_inputPtr < _inputEnd) || _loadMore()) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
int code = codes[i];
if (code != 0) {
switch (code) {
case '*':
if (_inputPtr >= _inputEnd && !_loadMore()) {
break main_loop;
}
if (_inputBuffer[_inputPtr] == INT_SLASH) {
++_inputPtr;
return;
}
break;
case INT_LF:
++_currInputRow;
_currInputRowStart = _inputPtr;
break;
case INT_CR:
_skipCR();
break;
case 2: // 2-byte UTF
_skipUtf8_2();
break;
case 3: // 3-byte UTF
_skipUtf8_3();
break;
case 4: // 4-byte UTF
_skipUtf8_4(i);
break;
default: // e.g. -1
// Is this good enough error message?
_reportInvalidChar(i);
}
}
}
_reportInvalidEOF(" in a comment", null);
}
private final boolean _skipYAMLComment() throws JacksonException
{
if (!isEnabled(JsonReadFeature.ALLOW_YAML_COMMENTS)) {
return false;
}
_skipLine();
return true;
}
// Method for skipping contents of an input line; usually for CPP
// and YAML style comments.
private final void _skipLine() throws JacksonException
{
// Ok: need to find EOF or linefeed
final int[] codes = CharTypes.getInputCodeComment();
while ((_inputPtr < _inputEnd) || _loadMore()) {
int i = _inputBuffer[_inputPtr++] & 0xFF;
int code = codes[i];
if (code != 0) {
switch (code) {
case INT_LF:
++_currInputRow;
_currInputRowStart = _inputPtr;
return;
case INT_CR:
_skipCR();
return;
case '*': // nop for these comments
break;
case 2: // 2-byte UTF
_skipUtf8_2();
break;
case 3: // 3-byte UTF
_skipUtf8_3();
break;
case 4: // 4-byte UTF
_skipUtf8_4(i);
break;
default: // e.g. -1
if (code < 0) {
// Is this good enough error message?
_reportInvalidChar(i);
}
}
}
}
}
@Override
protected char _decodeEscaped() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
_reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING);
}
}
int c = _inputBuffer[_inputPtr++];
switch (c) {
// First, ones that are mapped
case 'b':
return '\b';
case 't':
return '\t';
case 'n':
return '\n';
case 'f':
return '\f';
case 'r':
return '\r';
// And these are to be returned as they are
case '"':
case '/':
case '\\':
return (char) c;
case 'u': // and finally hex-escaped
break;
default:
return _handleUnrecognizedCharacterEscape((char) _decodeCharForError(c));
}
// Ok, a hex escape. Need 4 characters
int value = 0;
for (int i = 0; i < 4; ++i) {
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) {
_reportInvalidEOF(" in character escape sequence", JsonToken.VALUE_STRING);
}
}
int ch = _inputBuffer[_inputPtr++];
int digit = CharTypes.charToHex(ch);
if (digit < 0) {
_reportUnexpectedChar(ch & 0xFF, "expected a hex-digit for character escape sequence");
}
value = (value << 4) | digit;
}
return (char) value;
}
protected int _decodeCharForError(int firstByte) throws JacksonException
{
int c = firstByte & 0xFF;
if (c > 0x7F) { // if >= 0, is ascii and fine as is
int needed;
// Ok; if we end here, we got multi-byte combination
if ((c & 0xE0) == 0xC0) { // 2 bytes (0x0080 - 0x07FF)
c &= 0x1F;
needed = 1;
} else if ((c & 0xF0) == 0xE0) { // 3 bytes (0x0800 - 0xFFFF)
c &= 0x0F;
needed = 2;
} else if ((c & 0xF8) == 0xF0) {
// 4 bytes; double-char with surrogates and all...
c &= 0x07;
needed = 3;
} else {
_reportInvalidInitial(c & 0xFF);
needed = 1; // never gets here
}
int d = nextByte();
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF);
}
c = (c << 6) | (d & 0x3F);
if (needed > 1) { // needed == 1 means 2 bytes total
d = nextByte(); // 3rd byte
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF);
}
c = (c << 6) | (d & 0x3F);
if (needed > 2) { // 4 bytes? (need surrogates)
d = nextByte();
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF);
}
c = (c << 6) | (d & 0x3F);
}
}
}
return c;
}
/*
/**********************************************************************
/* Internal methods,UTF8 decoding
/**********************************************************************
*/
private final int _decodeUtf8_2(int c) throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
int d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
return ((c & 0x1F) << 6) | (d & 0x3F);
}
private final int _decodeUtf8_3(int c1) throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
c1 &= 0x0F;
int d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
int c = (c1 << 6) | (d & 0x3F);
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
c = (c << 6) | (d & 0x3F);
// [jackson-core#363]: Surrogates (0xD800 - 0xDFFF) are illegal in UTF-8
if (c >= 0xD800 && c <= 0xDFFF) {
_reportInvalidUTF8Surrogate(c);
}
return c;
}
private final int _decodeUtf8_3fast(int c1) throws JacksonException
{
c1 &= 0x0F;
int d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
int c = (c1 << 6) | (d & 0x3F);
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
c = (c << 6) | (d & 0x3F);
// [jackson-core#363]: Surrogates (0xD800 - 0xDFFF) are illegal in UTF-8
if (c >= 0xD800 && c <= 0xDFFF) {
_reportInvalidUTF8Surrogate(c);
}
return c;
}
// @return Character value <b>minus 0x10000</c>; this so that caller
// can readily expand it to actual surrogates
private final int _decodeUtf8_4(int c) throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
int d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
c = ((c & 0x07) << 6) | (d & 0x3F);
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
c = (c << 6) | (d & 0x3F);
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
/* note: won't change it to negative here, since caller
* already knows it'll need a surrogate
*/
return ((c << 6) | (d & 0x3F)) - 0x10000;
}
private final void _skipUtf8_2() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
int c = _inputBuffer[_inputPtr++];
if ((c & 0xC0) != 0x080) {
_reportInvalidOther(c & 0xFF, _inputPtr);
}
}
/* Alas, can't heavily optimize skipping, since we still have to
* do validity checks...
*/
private final void _skipUtf8_3() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
//c &= 0x0F;
int c = _inputBuffer[_inputPtr++];
if ((c & 0xC0) != 0x080) {
_reportInvalidOther(c & 0xFF, _inputPtr);
}
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
c = _inputBuffer[_inputPtr++];
if ((c & 0xC0) != 0x080) {
_reportInvalidOther(c & 0xFF, _inputPtr);
}
}
private final void _skipUtf8_4(int c) throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
int d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
d = _inputBuffer[_inputPtr++];
if ((d & 0xC0) != 0x080) {
_reportInvalidOther(d & 0xFF, _inputPtr);
}
}
/*
/**********************************************************************
/* Internal methods, input loading
/**********************************************************************
*/
// We actually need to check the character value here
// (to see if we have \n following \r).
protected final void _skipCR() throws JacksonException
{
if (_inputPtr < _inputEnd || _loadMore()) {
if (_inputBuffer[_inputPtr] == BYTE_LF) {
++_inputPtr;
}
}
++_currInputRow;
_currInputRowStart = _inputPtr;
}
private int nextByte() throws JacksonException
{
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
return _inputBuffer[_inputPtr++] & 0xFF;
}
/*
/**********************************************************************
/* Internal methods, error reporting
/**********************************************************************
*/
protected <T> T _reportInvalidToken(String matchedPart, int ptr) throws JacksonException {
_inputPtr = ptr;
return _reportInvalidToken(matchedPart, _validJsonTokenList());
}
protected <T> T _reportInvalidToken(String matchedPart) throws JacksonException {
return _reportInvalidToken(matchedPart, _validJsonTokenList());
}
protected <T> T _reportInvalidToken(String matchedPart, String msg) throws JacksonException
{
/* Let's just try to find what appears to be the token, using
* regular Java identifier character rules. It's just a heuristic,
* nothing fancy here (nor fast).
*/
// [core#1180]: Construct JsonLocation at token start BEFORE _loadMore() may change buffer state
final int tokenStartPtr = _inputPtr - matchedPart.length();
final int col = tokenStartPtr - _currInputRowStart + 1; // 1-based
final TokenStreamLocation loc = new TokenStreamLocation(_contentReference(),
_currInputProcessed + tokenStartPtr, -1L, // bytes, chars
_currInputRow, col);
StringBuilder sb = new StringBuilder(matchedPart);
while ((_inputPtr < _inputEnd) || _loadMore()) {
int i = _inputBuffer[_inputPtr++];
char c = (char) _decodeCharForError(i);
if (!Character.isJavaIdentifierPart(c)) {
// 11-Jan-2016, tatu: note: we will fully consume the character,
// included or not, so if recovery was possible, it'd be off-by-one...
// 04-Apr-2021, tatu: ... and the reason we can't do much about it is
// because it may be multi-byte UTF-8 character (and even if saved
// offset, on buffer boundary it would not work, still)
break;
}
sb.append(c);
if (sb.length() >= _ioContext.errorReportConfiguration().getMaxErrorTokenLength()) {
sb.append("...");
break;
}
}
final String fullMsg = String.format("Unrecognized token '%s': was expecting %s", sb, msg);
throw _constructReadException(fullMsg, loc);
}
protected <T> T _reportInvalidChar(int c) throws StreamReadException
{
// Either invalid WS or illegal UTF-8 start char
if (c < INT_SPACE) {
_reportInvalidSpace(c);
}
return _reportInvalidInitial(c);
}
protected <T> T _reportInvalidInitial(int mask) throws StreamReadException {
return _reportError("Invalid UTF-8 start byte 0x"+Integer.toHexString(mask));
}
protected <T> T _reportInvalidOther(int mask) throws StreamReadException {
return _reportError("Invalid UTF-8 middle byte 0x"+Integer.toHexString(mask));
}
protected <T> T _reportInvalidOther(int mask, int ptr) throws StreamReadException
{
_inputPtr = ptr;
return _reportInvalidOther(mask);
}
/*
/**********************************************************************
/* Internal methods, binary access
/**********************************************************************
*/
/**
* Efficient handling for incremental parsing of base64-encoded
* textual content.
*
* @param b64variant Type of base64 encoding expected in context
*
* @return Fully decoded value of base64 content
*
* @throws JacksonIOException for low-level read issues
* @throws StreamReadException for decoding problems (invalid content)
*/
@SuppressWarnings("resource")
protected final byte[] _decodeBase64(Base64Variant b64variant) throws JacksonException
{
ByteArrayBuilder builder = _getByteArrayBuilder();
while (true) {
// first, we'll skip preceding white space, if any
int ch;
do {
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
} while (ch <= INT_SPACE);
int bits = b64variant.decodeBase64Char(ch);
if (bits < 0) { // reached the end, fair and square?
if (ch == INT_QUOTE) {
return builder.toByteArray();
}
bits = _decodeBase64Escape(b64variant, ch, 0);
if (bits < 0) { // white space to skip
continue;
}
}
int decodedData = bits;
// then second base64 char; can't get padding yet, nor ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
bits = _decodeBase64Escape(b64variant, ch, 1);
}
decodedData = (decodedData << 6) | bits;
// third base64 char; can be padding, but not ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
// First branch: can get padding (-> 1 byte)
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
// could also just be 'missing' padding
if (ch == INT_QUOTE) {
decodedData >>= 4;
builder.append(decodedData);
if (b64variant.requiresPaddingOnRead()) {
--_inputPtr; // to keep parser state bit more consistent
_handleBase64MissingPadding(b64variant);
}
return builder.toByteArray();
}
bits = _decodeBase64Escape(b64variant, ch, 2);
}
if (bits == Base64Variant.BASE64_VALUE_PADDING) {
// Ok, must get padding
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
if (!b64variant.usesPaddingChar(ch)) {
if (_decodeBase64Escape(b64variant, ch, 3) != Base64Variant.BASE64_VALUE_PADDING) {
_reportInvalidBase64Char(b64variant, ch, 3, "expected padding character '"+b64variant.getPaddingChar()+"'");
}
}
// Got 12 bits, only need 8, need to shift
decodedData >>= 4;
builder.append(decodedData);
continue;
}
}
// Nope, 2 or 3 bytes
decodedData = (decodedData << 6) | bits;
// fourth and last base64 char; can be padding, but not ws
if (_inputPtr >= _inputEnd) {
_loadMoreGuaranteed();
}
ch = _inputBuffer[_inputPtr++] & 0xFF;
bits = b64variant.decodeBase64Char(ch);
if (bits < 0) {
if (bits != Base64Variant.BASE64_VALUE_PADDING) {
// could also just be 'missing' padding
if (ch == INT_QUOTE) {
decodedData >>= 2;
builder.appendTwoBytes(decodedData);
if (b64variant.requiresPaddingOnRead()) {
--_inputPtr; // to keep parser state bit more consistent
_handleBase64MissingPadding(b64variant);
}
return builder.toByteArray();
}
bits = _decodeBase64Escape(b64variant, ch, 3);
}
if (bits == Base64Variant.BASE64_VALUE_PADDING) {
// With padding we only get 2 bytes; but we have to shift it
// a bit so it is identical to triplet case with partial output.
// 3 chars gives 3x6 == 18 bits, of which 2 are dummies, need to discard:
decodedData >>= 2;
builder.appendTwoBytes(decodedData);
continue;
}
}
// otherwise, our triplet is now complete
decodedData = (decodedData << 6) | bits;
builder.appendThreeBytes(decodedData);
}
}
/*
/**********************************************************************
/* Improved location updating
/**********************************************************************
*/
@Override
public TokenStreamLocation currentTokenLocation()
{
if (_currToken == JsonToken.PROPERTY_NAME) {
long total = _currInputProcessed + (_nameStartOffset-1);
return new TokenStreamLocation(_contentReference(),
total, -1L, _nameStartRow, _nameStartCol);
}
return new TokenStreamLocation(_contentReference(),
_tokenInputTotal-1, -1L, _tokenInputRow, _tokenInputCol);
}
@Override
public TokenStreamLocation currentLocation()
{
int col = _inputPtr - _currInputRowStart + 1; // 1-based
return new TokenStreamLocation(_contentReference(),
_currInputProcessed + _inputPtr, -1L, // bytes, chars
_currInputRow, col);
}
@Override // @since 2.17
protected TokenStreamLocation _currentLocationMinusOne() {
final int prevInputPtr = _inputPtr - 1;
final int col = prevInputPtr - _currInputRowStart + 1; // 1-based
return new TokenStreamLocation(_contentReference(),
_currInputProcessed + prevInputPtr, -1L, // bytes, chars
_currInputRow, col);
}
private final void _updateLocation()
{
_tokenInputRow = _currInputRow;
final int ptr = _inputPtr;
_tokenInputTotal = _currInputProcessed + ptr;
_tokenInputCol = ptr - _currInputRowStart;
}
private final void _updateNameLocation()
{
_nameStartRow = _currInputRow;
final int ptr = _inputPtr;
_nameStartOffset = ptr;
_nameStartCol = ptr - _currInputRowStart;
}
/*
/**********************************************************************
/* Internal methods, other
/**********************************************************************
*/
private final JsonToken _closeScope(int i) throws StreamReadException {
if (i == INT_RCURLY) {
_closeObjectScope();
return _updateToken(JsonToken.END_OBJECT);
}
_closeArrayScope();
return _updateToken(JsonToken.END_ARRAY);
}
private final void _closeArrayScope() throws StreamReadException {
_updateLocation();
if (!_streamReadContext.inArray()) {
_reportMismatchedEndMarker(']', '}');
}
_streamReadContext = _streamReadContext.clearAndGetParent();
}
private final void _closeObjectScope() throws StreamReadException {
_updateLocation();
if (!_streamReadContext.inObject()) {
_reportMismatchedEndMarker('}', ']');
}
_streamReadContext = _streamReadContext.clearAndGetParent();
}
}
|
UTF8StreamJsonParser
|
java
|
quarkusio__quarkus
|
independent-projects/qute/core/src/main/java/io/quarkus/qute/HtmlEscaper.java
|
{
"start": 2307,
"end": 3674
}
|
class ____ still have to perform a null check vs String, which means
// we can have a branch misprediction there.
// Here we anticipate such cost and if this method is going to be inlined we could still
// correctly predict if the subsequent null check is going to be taken or not.
if (replacementId == 0) {
return null;
}
return REPLACEMENTS[replacementId];
}
public HtmlEscaper(List<String> escapedContentTypes) {
this.escapedContentTypes = escapedContentTypes;
}
@Override
public boolean appliesTo(Origin origin, Object result) {
if (result instanceof RawString) {
return false;
}
Optional<Variant> variant = origin.getVariant();
if (variant.isPresent()) {
return requiresDefaultEscaping(variant.get());
}
return false;
}
private boolean requiresDefaultEscaping(Variant variant) {
String contentType = variant.getContentType();
if (contentType == null) {
return false;
}
for (String escaped : escapedContentTypes) {
if (contentType.startsWith(escaped)) {
return true;
}
}
return false;
}
@Override
protected String replacementFor(char c) {
return replacementOf(c);
}
}
|
we
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseParser.java
|
{
"start": 17637,
"end": 18121
}
|
class ____ extends ParserRuleContext {
public StatementContext(ParserRuleContext parent, int invokingState) {
super(parent, invokingState);
}
@Override
public int getRuleIndex() {
return RULE_statement;
}
public StatementContext() {}
public void copyFrom(StatementContext ctx) {
super.copyFrom(ctx);
}
}
@SuppressWarnings("CheckReturnValue")
public static
|
StatementContext
|
java
|
apache__flink
|
flink-table/flink-table-common/src/test/java/org/apache/flink/table/connector/ProjectionTest.java
|
{
"start": 1465,
"end": 7650
}
|
class ____ {
@Test
void testTopLevelProject() {
assertThat(
Projection.of(new int[] {2, 1})
.project(
ROW(
FIELD("f0", BIGINT()),
FIELD("f1", STRING()),
FIELD("f2", INT()))))
.isEqualTo(ROW(FIELD("f2", INT()), FIELD("f1", STRING())));
}
@Test
void testNestedProject() {
final DataType thirdLevelRow =
ROW(FIELD("c0", BOOLEAN()), FIELD("c1", DOUBLE()), FIELD("c2", INT()));
final DataType secondLevelRow =
ROW(FIELD("b0", BOOLEAN()), FIELD("b1", thirdLevelRow), FIELD("b2", INT()));
final DataType topLevelRow =
ROW(FIELD("a0", INT()), FIELD("a1", secondLevelRow), FIELD("a1_b1_c0", INT()));
assertThat(Projection.of(new int[][] {{0}, {1, 1, 0}}).project(topLevelRow))
.isEqualTo(ROW(FIELD("a0", INT()), FIELD("a1_b1_c0", BOOLEAN())));
assertThat(Projection.of(new int[][] {{1, 1}, {0}}).project(topLevelRow))
.isEqualTo(ROW(FIELD("a1_b1", thirdLevelRow), FIELD("a0", INT())));
assertThat(
Projection.of(new int[][] {{1, 1, 2}, {1, 1, 1}, {1, 1, 0}})
.project(topLevelRow))
.isEqualTo(
ROW(
FIELD("a1_b1_c2", INT()),
FIELD("a1_b1_c1", DOUBLE()),
FIELD("a1_b1_c0", BOOLEAN())));
assertThat(Projection.of(new int[][] {{1, 1, 0}, {2}}).project(topLevelRow))
.isEqualTo(ROW(FIELD("a1_b1_c0", BOOLEAN()), FIELD("a1_b1_c0_$0", INT())));
}
@Test
void testIsNested() {
assertThat(Projection.of(new int[] {2, 1}).isNested()).isFalse();
assertThat(Projection.of(new int[][] {new int[] {1}, new int[] {3}}).isNested()).isFalse();
assertThat(
Projection.of(new int[][] {new int[] {1}, new int[] {1, 2}, new int[] {3}})
.isNested())
.isTrue();
}
@Test
void testDifference() {
assertThat(
Projection.of(new int[] {4, 1, 0, 3, 2})
.difference(Projection.of(new int[] {4, 2})))
.isEqualTo(Projection.of(new int[] {1, 0, 2}));
assertThat(
Projection.of(
new int[][] {
new int[] {4},
new int[] {1, 3},
new int[] {0},
new int[] {3, 1},
new int[] {2}
})
.difference(Projection.of(new int[] {4, 2})))
.isEqualTo(
Projection.of(
new int[][] {new int[] {1, 3}, new int[] {0}, new int[] {2, 1}}));
assertThatThrownBy(
() ->
Projection.of(new int[] {1, 2, 3, 4})
.difference(
Projection.of(
new int[][] {
new int[] {2}, new int[] {3, 4}
})))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void testComplement() {
assertThat(Projection.of(new int[] {4, 1, 2}).complement(5))
.isEqualTo(Projection.of(new int[] {0, 3}));
assertThat(
Projection.of(new int[][] {new int[] {4}, new int[] {1}, new int[] {2}})
.complement(5))
.isEqualTo(Projection.of(new int[] {0, 3}));
assertThatThrownBy(
() ->
Projection.of(
new int[][] {
new int[] {4}, new int[] {1, 3}, new int[] {2}
})
.complement(10))
.isInstanceOf(IllegalStateException.class);
}
@Test
void testToTopLevelIndexes() {
assertThat(Projection.of(new int[] {1, 2, 3, 4}).toTopLevelIndexes())
.isEqualTo(new int[] {1, 2, 3, 4});
assertThat(
Projection.of(new int[][] {new int[] {4}, new int[] {1}, new int[] {2}})
.toTopLevelIndexes())
.isEqualTo(new int[] {4, 1, 2});
assertThatThrownBy(
() ->
Projection.of(
new int[][] {
new int[] {4}, new int[] {1, 3}, new int[] {2}
})
.toTopLevelIndexes())
.isInstanceOf(IllegalStateException.class);
}
@Test
void testToNestedIndexes() {
assertThat(Projection.of(new int[] {1, 2, 3, 4}).toNestedIndexes())
.isEqualTo(
new int[][] {new int[] {1}, new int[] {2}, new int[] {3}, new int[] {4}});
assertThat(
Projection.of(new int[][] {new int[] {4}, new int[] {1, 3}, new int[] {2}})
.toNestedIndexes())
.isEqualTo(new int[][] {new int[] {4}, new int[] {1, 3}, new int[] {2}});
}
@Test
void testEquals() {
assertThat(Projection.of(new int[][] {new int[] {1}, new int[] {2}, new int[] {3}}))
.isEqualTo(Projection.of(new int[] {1, 2, 3}));
}
}
|
ProjectionTest
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/AbstractWasbTestBase.java
|
{
"start": 1662,
"end": 5476
}
|
class ____ extends AbstractWasbTestWithTimeout
implements AzureTestConstants {
protected static final Logger LOG =
LoggerFactory.getLogger(AbstractWasbTestBase.class);
protected NativeAzureFileSystem fs;
protected AzureBlobStorageTestAccount testAccount;
@BeforeEach
public void setUp() throws Exception {
AzureBlobStorageTestAccount account = createTestAccount();
assumeNotNull(account, "test account");
bindToTestAccount(account);
}
@AfterEach
public void tearDown() throws Exception {
describe("closing test account and filesystem");
testAccount = cleanupTestAccount(testAccount);
IOUtils.closeStream(fs);
fs = null;
}
/**
* Create the configuration to use when creating a test account.
* Subclasses can override this to tune the test account configuration.
* @return a configuration.
*/
public Configuration createConfiguration() {
return AzureBlobStorageTestAccount.createTestConfiguration();
}
/**
* Create the test account.
* Subclasses must implement this.
* @return the test account.
* @throws Exception
*/
protected abstract AzureBlobStorageTestAccount createTestAccount()
throws Exception;
/**
* Get the test account.
* @return the current test account.
*/
protected AzureBlobStorageTestAccount getTestAccount() {
return testAccount;
}
/**
* Get the filesystem
* @return the current filesystem.
*/
protected NativeAzureFileSystem getFileSystem() {
return fs;
}
/**
* Get the configuration used to create the filesystem
* @return the configuration of the test FS
*/
protected Configuration getConfiguration() {
return getFileSystem().getConf();
}
/**
* Bind to a new test account; closing any existing one.
* This updates the test account returned in {@link #getTestAccount()}
* and the filesystem in {@link #getFileSystem()}.
* @param account new test account
*/
protected void bindToTestAccount(AzureBlobStorageTestAccount account) {
// clean any existing test account
cleanupTestAccount(testAccount);
IOUtils.closeStream(fs);
testAccount = account;
if (testAccount != null) {
fs = testAccount.getFileSystem();
}
}
/**
* Return a path to a blob which will be unique for this fork.
* @param filepath filepath
* @return a path under the default blob directory
* @throws IOException
*/
protected Path blobPath(String filepath) throws IOException {
return blobPathForTests(getFileSystem(), filepath);
}
/**
* Create a path under the test path provided by
* the FS contract.
* @param filepath path string in
* @return a path qualified by the test filesystem
* @throws IOException IO problems
*/
protected Path path(String filepath) throws IOException {
return pathForTests(getFileSystem(), filepath);
}
/**
* Return a path bonded to this method name, unique to this fork during
* parallel execution.
* @return a method name unique to (fork, method).
* @throws IOException IO problems
*/
protected Path methodPath() throws IOException {
return path(methodName.getMethodName());
}
/**
* Return a blob path bonded to this method name, unique to this fork during
* parallel execution.
* @return a method name unique to (fork, method).
* @throws IOException IO problems
*/
protected Path methodBlobPath() throws IOException {
return blobPath(methodName.getMethodName());
}
/**
* Describe a test in the logs.
* @param text text to print
* @param args arguments to format in the printing
*/
protected void describe(String text, Object... args) {
LOG.info("\n\n{}: {}\n",
methodName.getMethodName(),
String.format(text, args));
}
}
|
AbstractWasbTestBase
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/InterruptedExceptionSwallowedTest.java
|
{
"start": 5607,
"end": 6083
}
|
class ____ extends ThrowingParent {}
// BUG: Diagnostic contains:
void test() throws Exception {
try (ThrowingChild t = new ThrowingChild()) {}
}
}
""")
.doTest();
}
@Test
public void thrownByClose_swallowedSilently() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import java.util.concurrent.Future;
|
ThrowingChild
|
java
|
apache__camel
|
components/camel-bindy/src/main/java/org/apache/camel/dataformat/bindy/annotation/FixedLengthRecord.java
|
{
"start": 1243,
"end": 3653
}
|
interface ____ {
/**
* Name describing the record (optional)
*
* @return String
*/
String name() default "";
/**
* Character to be used to add a carriage return after each record (optional). Possible values: WINDOWS, UNIX, MAC,
* or custom. This option is used only during marshalling, whereas unmarshalling uses system default JDK provided
* line delimiter unless eol is customized.
*
* @return String
*/
String crlf() default "WINDOWS";
/**
* Character to be used to process considering end of line after each record while unmarshalling (optional -
* default: "", which helps default JDK provided line delimiter to be used unless any other line delimiter provided)
* This option is used only during unmarshalling, where marshalling uses system default provided line delimiter as
* "WINDOWS" unless any other value is provided.
*
* @return String
*/
String eol() default "";
/**
* The char to pad with.
*
* @return the char to pad with if the record is set to a fixed length;
*/
char paddingChar() default ' ';
/**
* The fixed length of the record (number of characters). It means that the record will always be that long padded
* with {#paddingChar()}'s
*
* @return the length of the record.
*/
int length() default 0;
/**
* Indicates that the record(s) of this type may be preceded by a single header record at the beginning of in the
* file
*/
Class<?> header() default void.class;
/**
* Indicates that the record(s) of this type may be followed by a single footer record at the end of the file
*/
Class<?> footer() default void.class;
/**
* Configures the data format to skip marshalling / unmarshalling of the header record. Configure this parameter on
* the primary record (e.g., not the header or footer).
*/
boolean skipHeader() default false;
/**
* Configures the data format to skip marshalling / unmarshalling of the footer record. Configure this parameter on
* the primary record (e.g., not the header or footer).
*/
boolean skipFooter() default false;
/**
* Indicates that characters beyond the last mapped filed can be ignored when unmarshalling / parsing. This
* annotation is associated to the root
|
FixedLengthRecord
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/time/DurationGetTemporalUnitTest.java
|
{
"start": 1288,
"end": 2080
}
|
class ____ {
private static final long seconds = Duration.ZERO.get(ChronoUnit.SECONDS);
private static final long nanos = Duration.ZERO.get(ChronoUnit.NANOS);
// BUG: Diagnostic contains: Duration.ZERO.toDays();
private static final long days = Duration.ZERO.get(ChronoUnit.DAYS);
}
""")
.doTest();
}
@Test
public void durationGetTemporalUnitStaticImport() {
helper
.addSourceLines(
"TestClass.java",
"""
import static java.time.temporal.ChronoUnit.MILLIS;
import static java.time.temporal.ChronoUnit.NANOS;
import static java.time.temporal.ChronoUnit.SECONDS;
import java.time.Duration;
public
|
TestClass
|
java
|
spring-projects__spring-framework
|
spring-r2dbc/src/main/java/org/springframework/r2dbc/core/binding/AnonymousBindMarkers.java
|
{
"start": 1385,
"end": 2151
}
|
class ____ implements BindMarkers {
private static final AtomicIntegerFieldUpdater<AnonymousBindMarkers> COUNTER_INCREMENTER =
AtomicIntegerFieldUpdater.newUpdater(AnonymousBindMarkers.class, "counter");
private final String placeholder;
// access via COUNTER_INCREMENTER
@SuppressWarnings("unused")
private volatile int counter;
/**
* Create a new {@link AnonymousBindMarkers} instance for the given {@code placeholder}.
* @param placeholder parameter bind marker
*/
AnonymousBindMarkers(String placeholder) {
this.placeholder = placeholder;
}
@Override
public BindMarker next() {
int index = COUNTER_INCREMENTER.getAndIncrement(this);
return new IndexedBindMarkers.IndexedBindMarker(this.placeholder, index);
}
}
|
AnonymousBindMarkers
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/test/java/io/vertx/tests/deployment/AbstractVerticleTest.java
|
{
"start": 699,
"end": 1172
}
|
class ____ extends VertxTestBase {
MyAbstractVerticle verticle = new MyAbstractVerticle();
@Test
public void testFieldsSet() {
JsonObject config = new JsonObject().put("foo", "bar");
vertx.deployVerticle(verticle, new DeploymentOptions().setConfig(config)).onComplete(onSuccess(res -> {
assertEquals(res, verticle.getDeploymentID());
assertEquals(config, verticle.getConfig());
testComplete();
}));
await();
}
|
AbstractVerticleTest
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/execution/Environment.java
|
{
"start": 6111,
"end": 10524
}
|
class ____. */
UserCodeClassLoader getUserCodeClassLoader();
Map<String, Future<Path>> getDistributedCacheEntries();
BroadcastVariableManager getBroadcastVariableManager();
TaskStateManager getTaskStateManager();
GlobalAggregateManager getGlobalAggregateManager();
/**
* Get the {@link ExternalResourceInfoProvider} which contains infos of available external
* resources.
*
* @return {@link ExternalResourceInfoProvider} which contains infos of available external
* resources
*/
ExternalResourceInfoProvider getExternalResourceInfoProvider();
/**
* Return the registry for accumulators which are periodically sent to the job manager.
*
* @return the registry
*/
AccumulatorRegistry getAccumulatorRegistry();
/**
* Returns the registry for {@link InternalKvState} instances.
*
* @return KvState registry
*/
TaskKvStateRegistry getTaskKvStateRegistry();
/**
* Confirms that the invokable has successfully completed all steps it needed to for the
* checkpoint with the give checkpoint-ID. This method does not include any state in the
* checkpoint.
*
* @param checkpointId ID of this checkpoint
* @param checkpointMetrics metrics for this checkpoint
*/
void acknowledgeCheckpoint(long checkpointId, CheckpointMetrics checkpointMetrics);
/**
* Confirms that the invokable has successfully completed all required steps for the checkpoint
* with the give checkpoint-ID. This method does include the given state in the checkpoint.
*
* @param checkpointId ID of this checkpoint
* @param checkpointMetrics metrics for this checkpoint
* @param subtaskState All state handles for the checkpointed state
*/
void acknowledgeCheckpoint(
long checkpointId, CheckpointMetrics checkpointMetrics, TaskStateSnapshot subtaskState);
/**
* Declines a checkpoint. This tells the checkpoint coordinator that this task will not be able
* to successfully complete a certain checkpoint.
*
* @param checkpointId The ID of the declined checkpoint.
* @param checkpointException The exception why the checkpoint was declined.
*/
void declineCheckpoint(long checkpointId, CheckpointException checkpointException);
/**
* Marks task execution failed for an external reason (a reason other than the task code itself
* throwing an exception). If the task is already in a terminal state (such as FINISHED,
* CANCELED, FAILED), or if the task is already canceling this does nothing. Otherwise it sets
* the state to FAILED, and, if the invokable code is running, starts an asynchronous thread
* that aborts that code.
*
* <p>This method never blocks.
*/
void failExternally(Throwable cause);
// --------------------------------------------------------------------------------------------
// Fields relevant to the I/O system. Should go into Task
// --------------------------------------------------------------------------------------------
ResultPartitionWriter getWriter(int index);
ResultPartitionWriter[] getAllWriters();
IndexedInputGate getInputGate(int index);
IndexedInputGate[] getAllInputGates();
TaskEventDispatcher getTaskEventDispatcher();
TaskManagerActions getTaskManagerActions();
// --------------------------------------------------------------------------------------------
// Fields set in the StreamTask to provide access to mailbox and other runtime resources
// --------------------------------------------------------------------------------------------
default void setMainMailboxExecutor(MailboxExecutor mainMailboxExecutor) {}
default MailboxExecutor getMainMailboxExecutor() {
throw new UnsupportedOperationException();
}
default void setAsyncOperationsThreadPool(ExecutorService executorService) {}
default ExecutorService getAsyncOperationsThreadPool() {
throw new UnsupportedOperationException();
}
default void setCheckpointStorageAccess(CheckpointStorageAccess checkpointStorageAccess) {}
default CheckpointStorageAccess getCheckpointStorageAccess() {
throw new UnsupportedOperationException();
}
ChannelStateWriteRequestExecutorFactory getChannelStateExecutorFactory();
}
|
loader
|
java
|
spring-projects__spring-framework
|
spring-jms/src/main/java/org/springframework/jms/config/JmsListenerEndpoint.java
|
{
"start": 986,
"end": 1631
}
|
interface ____ {
/**
* Return the id of this endpoint.
*/
String getId();
/**
* Set up the specified message listener container with the model
* defined by this endpoint.
* <p>This endpoint must provide the requested missing option(s) of
* the specified container to make it usable. Usually, this is about
* setting the {@code destination} and the {@code messageListener} to
* use but an implementation may override any default setting that
* was already set.
* @param listenerContainer the listener container to configure
*/
void setupListenerContainer(MessageListenerContainer listenerContainer);
}
|
JmsListenerEndpoint
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/main/java/org/hibernate/envers/internal/entities/mapper/relation/lazy/initializor/BasicCollectionInitializor.java
|
{
"start": 697,
"end": 2375
}
|
class ____<T extends Collection> extends AbstractCollectionInitializor<T> {
protected final Class<? extends T> collectionClass;
private final MiddleComponentData elementComponentData;
public BasicCollectionInitializor(
EnversService enversService,
AuditReaderImplementor versionsReader,
RelationQueryGenerator queryGenerator,
Object primaryKey, Number revision, boolean removed,
Class<? extends T> collectionClass,
MiddleComponentData elementComponentData) {
super( enversService, versionsReader, queryGenerator, primaryKey, revision, removed );
this.collectionClass = collectionClass;
this.elementComponentData = elementComponentData;
}
@Override
@SuppressWarnings("unchecked")
protected T initializeCollection(int size) {
return newObjectInstance( collectionClass );
}
@Override
@SuppressWarnings("unchecked")
protected void addToCollection(T collection, Object collectionRow) {
// collectionRow will be the actual object if retrieved from audit relation or middle table
// otherwise it will be a List
Object elementData = collectionRow;
if ( collectionRow instanceof List ) {
elementData = ( (List) collectionRow ).get( elementComponentData.getComponentIndex() );
}
// If the target entity is not audited, the elements may be the entities already, so we have to check
// if they are maps or not.
Object element;
if ( elementData instanceof Map ) {
element = elementComponentData.getComponentMapper().mapToObjectFromFullMap(
entityInstantiator,
(Map<String, Object>) elementData, null, revision
);
}
else {
element = elementData;
}
collection.add( element );
}
}
|
BasicCollectionInitializor
|
java
|
apache__maven
|
impl/maven-impl/src/main/java/org/apache/maven/impl/cache/DefaultRequestCacheFactory.java
|
{
"start": 1055,
"end": 1296
}
|
class ____ implements RequestCacheFactory {
private static final RequestCache REQUEST_CACHE = new DefaultRequestCache();
@Override
public RequestCache createCache() {
return REQUEST_CACHE;
}
}
|
DefaultRequestCacheFactory
|
java
|
elastic__elasticsearch
|
server/src/internalClusterTest/java/org/elasticsearch/search/rank/FieldBasedRerankerIT.java
|
{
"start": 10626,
"end": 16109
}
|
enum ____ {
THROWING_QUERY_PHASE_SHARD_CONTEXT,
THROWING_QUERY_PHASE_COORDINATOR_CONTEXT,
THROWING_RANK_FEATURE_PHASE_SHARD_CONTEXT,
THROWING_RANK_FEATURE_PHASE_COORDINATOR_CONTEXT;
}
protected final ThrowingRankBuilderType throwingRankBuilderType;
public static final ParseField FIELD_FIELD = new ParseField("field");
public static final ParseField THROWING_TYPE_FIELD = new ParseField("throwing-type");
static final ConstructingObjectParser<ThrowingRankBuilder, Void> PARSER = new ConstructingObjectParser<>("throwing_rank", args -> {
int rankWindowSize = args[0] == null ? DEFAULT_RANK_WINDOW_SIZE : (int) args[0];
String field = (String) args[1];
if (field == null || field.isEmpty()) {
throw new IllegalArgumentException("Field cannot be null or empty");
}
String throwingType = (String) args[2];
return new ThrowingRankBuilder(rankWindowSize, field, throwingType);
});
static {
PARSER.declareInt(optionalConstructorArg(), RANK_WINDOW_SIZE_FIELD);
PARSER.declareString(constructorArg(), FIELD_FIELD);
PARSER.declareString(constructorArg(), THROWING_TYPE_FIELD);
}
public static FieldBasedRankBuilder fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, null);
}
public ThrowingRankBuilder(final int rankWindowSize, final String field, final String throwingType) {
super(rankWindowSize, field);
this.throwingRankBuilderType = ThrowingRankBuilderType.valueOf(throwingType);
}
public ThrowingRankBuilder(StreamInput in) throws IOException {
super(in);
this.throwingRankBuilderType = in.readEnum(ThrowingRankBuilderType.class);
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
super.doWriteTo(out);
out.writeEnum(throwingRankBuilderType);
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
super.doXContent(builder, params);
builder.field(THROWING_TYPE_FIELD.getPreferredName(), throwingRankBuilderType);
}
@Override
public String getWriteableName() {
return "throwing_rank";
}
@Override
public QueryPhaseRankShardContext buildQueryPhaseShardContext(List<Query> queries, int from) {
if (this.throwingRankBuilderType == ThrowingRankBuilderType.THROWING_QUERY_PHASE_SHARD_CONTEXT)
return new QueryPhaseRankShardContext(queries, rankWindowSize()) {
@Override
public RankShardResult combineQueryPhaseResults(List<TopDocs> rankResults) {
throw new UnsupportedOperationException("qps - simulated failure");
}
};
else {
return super.buildQueryPhaseShardContext(queries, from);
}
}
@Override
public QueryPhaseRankCoordinatorContext buildQueryPhaseCoordinatorContext(int size, int from) {
if (this.throwingRankBuilderType == ThrowingRankBuilderType.THROWING_QUERY_PHASE_COORDINATOR_CONTEXT)
return new QueryPhaseRankCoordinatorContext(rankWindowSize()) {
@Override
public ScoreDoc[] rankQueryPhaseResults(
List<QuerySearchResult> querySearchResults,
SearchPhaseController.TopDocsStats topDocStats
) {
throw new UnsupportedOperationException("qpc - simulated failure");
}
};
else {
return super.buildQueryPhaseCoordinatorContext(size, from);
}
}
@Override
public RankFeaturePhaseRankShardContext buildRankFeaturePhaseShardContext() {
if (this.throwingRankBuilderType == ThrowingRankBuilderType.THROWING_RANK_FEATURE_PHASE_SHARD_CONTEXT)
return new RankFeaturePhaseRankShardContext(field) {
@Override
public RankShardResult buildRankFeatureShardResult(SearchHits hits, int shardId) {
throw new UnsupportedOperationException("rfs - simulated failure");
}
};
else {
return super.buildRankFeaturePhaseShardContext();
}
}
@Override
public RankFeaturePhaseRankCoordinatorContext buildRankFeaturePhaseCoordinatorContext(int size, int from, Client client) {
if (this.throwingRankBuilderType == ThrowingRankBuilderType.THROWING_RANK_FEATURE_PHASE_COORDINATOR_CONTEXT)
return new RankFeaturePhaseRankCoordinatorContext(size, from, rankWindowSize(), false) {
@Override
protected void computeScores(RankFeatureDoc[] featureDocs, ActionListener<float[]> scoreListener) {
throw new UnsupportedOperationException("rfc - simulated failure");
}
};
else {
return super.buildRankFeaturePhaseCoordinatorContext(size, from, client);
}
}
}
public static
|
ThrowingRankBuilderType
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/java/typeutils/TypeExtractorTest.java
|
{
"start": 49990,
"end": 52076
}
|
class ____<T> extends RichMapFunction<T, Tuple2<T, Integer>> {
private static final long serialVersionUID = 1L;
public Tuple2<T, Integer> map(T value) {
return new Tuple2<T, Integer>(value, 1);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
void testFunctionDependingPartialOnInput() {
RichMapFunction<?, ?> function =
new OneAppender<DoubleValue>() {
private static final long serialVersionUID = 1L;
};
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
function,
(TypeInformation) TypeInformation.of(new TypeHint<DoubleValue>() {}));
assertThat(ti.isTupleType()).isTrue();
assertThat(ti.getArity()).isEqualTo(2);
TupleTypeInfo<?> tti = (TupleTypeInfo<?>) ti;
assertThat(tti.getTypeAt(0) instanceof ValueTypeInfo<?>).isTrue();
ValueTypeInfo<?> vti = (ValueTypeInfo<?>) tti.getTypeAt(0);
assertThat(vti.getTypeClass()).isEqualTo(DoubleValue.class);
assertThat(tti.getTypeAt(1).isBasicType()).isTrue();
assertThat(tti.getTypeAt(1).getTypeClass()).isEqualTo(Integer.class);
}
@Test
void testFunctionDependingPartialOnInput2() {
RichMapFunction<DoubleValue, ?> function = new OneAppender<DoubleValue>();
TypeInformation<?> ti =
TypeExtractor.getMapReturnTypes(
function, new ValueTypeInfo<DoubleValue>(DoubleValue.class));
assertThat(ti.isTupleType()).isTrue();
assertThat(ti.getArity()).isEqualTo(2);
TupleTypeInfo<?> tti = (TupleTypeInfo<?>) ti;
assertThat(tti.getTypeAt(0) instanceof ValueTypeInfo<?>).isTrue();
ValueTypeInfo<?> vti = (ValueTypeInfo<?>) tti.getTypeAt(0);
assertThat(vti.getTypeClass()).isEqualTo(DoubleValue.class);
assertThat(tti.getTypeAt(1).isBasicType()).isTrue();
assertThat(tti.getTypeAt(1).getTypeClass()).isEqualTo(Integer.class);
}
public
|
OneAppender
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/convert/BeanConversionsTest.java
|
{
"start": 1259,
"end": 1330
}
|
class ____ {
public boolean boolProp;
}
static
|
BooleanBean
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/reservation/ReservationSchedulerConfiguration.java
|
{
"start": 5532,
"end": 6394
}
|
class ____ of the {@code Planner}
*/
public String getReplanner(QueuePath queue) {
return DEFAULT_RESERVATION_PLANNER_NAME;
}
/**
* Gets whether the applications should be killed or moved to the parent queue
* when the {@link ReservationDefinition} expires
* @param queue name of the queue
* @return true if application should be moved, false if they need to be
* killed
*/
public boolean getMoveOnExpiry(QueuePath queue) {
return DEFAULT_RESERVATION_MOVE_ON_EXPIRY;
}
/**
* Gets the time in milliseconds for which the {@code Planner} will verify
* the {@link Plan}s satisfy the constraints
* @param queue name of the queue
* @return the time in milliseconds for which to check constraints
*/
public long getEnforcementWindow(QueuePath queue) {
return DEFAULT_RESERVATION_ENFORCEMENT_WINDOW;
}
}
|
name
|
java
|
micronaut-projects__micronaut-core
|
core-processor/src/main/java/io/micronaut/inject/writer/EvaluatedExpressionProcessor.java
|
{
"start": 1910,
"end": 2003
}
|
class ____ writing annotation metadata with evaluated expressions.
*/
@Internal
public final
|
for
|
java
|
apache__camel
|
core/camel-support/src/main/java/org/apache/camel/support/SynchronizationAdapter.java
|
{
"start": 1121,
"end": 1773
}
|
class ____ implements SynchronizationVetoable, Ordered, Synchronization {
@Override
public void onComplete(Exchange exchange) {
onDone(exchange);
}
@Override
public void onFailure(Exchange exchange) {
onDone(exchange);
}
public void onDone(Exchange exchange) {
// noop
}
@Override
public boolean allowHandover() {
// allow by default
return true;
}
@Override
public int getOrder() {
// no particular order by default
return 0;
}
@Override
public void beforeHandover(Exchange target) {
// noop
}
}
|
SynchronizationAdapter
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/proxy/filter/encoding/CharsetConvertTest.java
|
{
"start": 841,
"end": 1747
}
|
class ____ extends TestCase {
private static final String CLIENT_ENCODEING = "gbk";
private static final String SERVER_ENCODEING = "utf-8";
public CharsetConvert charsetConvert = new CharsetConvert(CLIENT_ENCODEING, SERVER_ENCODEING);
public void testIsEmpty() {
assertTrue(charsetConvert.isEmpty(null));
assertTrue(charsetConvert.isEmpty(""));
assertTrue(!charsetConvert.isEmpty("a"));
}
public void testEncoding() {
String s = "你好";
String es = "";
String ds = "";
try {
es = new String(s.getBytes(CLIENT_ENCODEING), SERVER_ENCODEING);
ds = new String(s.getBytes(SERVER_ENCODEING), CLIENT_ENCODEING);
assertEquals(es, charsetConvert.encode(s));
assertEquals(ds, charsetConvert.decode(s));
} catch (UnsupportedEncodingException e) {
}
}
}
|
CharsetConvertTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java
|
{
"start": 7911,
"end": 74488
}
|
class ____.
*/
private static final Logger LOGGER =
LoggerFactory.getLogger(FileSystem.class);
/**
* Priority of the FileSystem shutdown hook: {@value}.
*/
public static final int SHUTDOWN_HOOK_PRIORITY = 10;
/**
* Prefix for trash directory: {@value}.
*/
public static final String TRASH_PREFIX = ".Trash";
public static final String USER_HOME_PREFIX = "/user";
/** FileSystem cache. */
static final Cache CACHE = new Cache(new Configuration());
/** The key this instance is stored under in the cache. */
private Cache.Key key;
/** Recording statistics per a FileSystem class. */
private static final Map<Class<? extends FileSystem>, Statistics>
statisticsTable = new IdentityHashMap<>();
/**
* The statistics for this file system.
*/
protected Statistics statistics;
/**
* A cache of files that should be deleted when the FileSystem is closed
* or the JVM is exited.
*/
private final Set<Path> deleteOnExit = new TreeSet<>();
/**
* Should symbolic links be resolved by {@link FileSystemLinkResolver}.
* Set to the value of
* {@link CommonConfigurationKeysPublic#FS_CLIENT_RESOLVE_REMOTE_SYMLINKS_KEY}
*/
boolean resolveSymlinks;
/**
* This method adds a FileSystem instance to the cache so that it can
* be retrieved later. It is only for testing.
* @param uri the uri to store it under
* @param conf the configuration to store it under
* @param fs the FileSystem to store
* @throws IOException if the current user cannot be determined.
*/
@VisibleForTesting
static void addFileSystemForTesting(URI uri, Configuration conf,
FileSystem fs) throws IOException {
CACHE.map.put(new Cache.Key(uri, conf), fs);
}
@VisibleForTesting
static void removeFileSystemForTesting(URI uri, Configuration conf,
FileSystem fs) throws IOException {
CACHE.map.remove(new Cache.Key(uri, conf), fs);
}
@VisibleForTesting
static int cacheSize() {
return CACHE.map.size();
}
/**
* Get a FileSystem instance based on the uri, the passed in
* configuration and the user.
* @param uri of the filesystem
* @param conf the configuration to use
* @param user to perform the get as
* @return the filesystem instance
* @throws IOException failure to load
* @throws InterruptedException If the {@code UGI.doAs()} call was
* somehow interrupted.
*/
public static FileSystem get(final URI uri, final Configuration conf,
final String user) throws IOException, InterruptedException {
String ticketCachePath =
conf.get(CommonConfigurationKeys.KERBEROS_TICKET_CACHE_PATH);
UserGroupInformation ugi =
UserGroupInformation.getBestUGI(ticketCachePath, user);
return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
@Override
public FileSystem run() throws IOException {
return get(uri, conf);
}
});
}
/**
* Returns the configured FileSystem implementation.
* @param conf the configuration to use
* @return FileSystem.
* @throws IOException If an I/O error occurred.
*/
public static FileSystem get(Configuration conf) throws IOException {
return get(getDefaultUri(conf), conf);
}
/**
* Get the default FileSystem URI from a configuration.
* @param conf the configuration to use
* @return the uri of the default filesystem
*/
public static URI getDefaultUri(Configuration conf) {
URI uri =
URI.create(fixName(conf.getTrimmed(FS_DEFAULT_NAME_KEY, DEFAULT_FS)));
if (uri.getScheme() == null) {
throw new IllegalArgumentException("No scheme in default FS: " + uri);
}
return uri;
}
/**
* Set the default FileSystem URI in a configuration.
* @param conf the configuration to alter
* @param uri the new default filesystem uri
*/
public static void setDefaultUri(Configuration conf, URI uri) {
conf.set(FS_DEFAULT_NAME_KEY, uri.toString());
}
/** Set the default FileSystem URI in a configuration.
* @param conf the configuration to alter
* @param uri the new default filesystem uri
*/
public static void setDefaultUri(Configuration conf, String uri) {
setDefaultUri(conf, URI.create(fixName(uri)));
}
/**
* Initialize a FileSystem.
*
* Called after the new FileSystem instance is constructed, and before it
* is ready for use.
*
* FileSystem implementations overriding this method MUST forward it to
* their superclass, though the order in which it is done, and whether
* to alter the configuration before the invocation are options of the
* subclass.
* @param name a URI whose authority section names the host, port, etc.
* for this FileSystem
* @param conf the configuration
* @throws IOException on any failure to initialize this instance.
* @throws IllegalArgumentException if the URI is considered invalid.
*/
public void initialize(URI name, Configuration conf) throws IOException {
final String scheme;
if (name.getScheme() == null || name.getScheme().isEmpty()) {
scheme = getDefaultUri(conf).getScheme();
} else {
scheme = name.getScheme();
}
statistics = getStatistics(scheme, getClass());
resolveSymlinks = conf.getBoolean(
CommonConfigurationKeysPublic.FS_CLIENT_RESOLVE_REMOTE_SYMLINKS_KEY,
CommonConfigurationKeysPublic.FS_CLIENT_RESOLVE_REMOTE_SYMLINKS_DEFAULT);
}
/**
* Return the protocol scheme for this FileSystem.
* <p>
* This implementation throws an <code>UnsupportedOperationException</code>.
*
* @return the protocol scheme for this FileSystem.
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
*/
public String getScheme() {
throw new UnsupportedOperationException("Not implemented by the "
+ getClass().getSimpleName() + " FileSystem implementation");
}
/**
* Returns a URI which identifies this FileSystem.
*
* @return the URI of this filesystem.
*/
public abstract URI getUri();
/**
* Return a canonicalized form of this FileSystem's URI.
*
* The default implementation simply calls {@link #canonicalizeUri(URI)}
* on the filesystem's own URI, so subclasses typically only need to
* implement that method.
*
* @see #canonicalizeUri(URI)
* @return the URI of this filesystem.
*/
protected URI getCanonicalUri() {
return canonicalizeUri(getUri());
}
/**
* Canonicalize the given URI.
*
* This is implementation-dependent, and may for example consist of
* canonicalizing the hostname using DNS and adding the default
* port if not specified.
*
* The default implementation simply fills in the default port if
* not specified and if {@link #getDefaultPort()} returns a
* default port.
*
* @param uri url.
* @return URI
* @see NetUtils#getCanonicalUri(URI, int)
*/
protected URI canonicalizeUri(URI uri) {
if (uri.getPort() == -1 && getDefaultPort() > 0) {
// reconstruct the uri with the default port set
try {
uri = new URI(uri.getScheme(), uri.getUserInfo(),
uri.getHost(), getDefaultPort(),
uri.getPath(), uri.getQuery(), uri.getFragment());
} catch (URISyntaxException e) {
// Should never happen!
throw new AssertionError("Valid URI became unparseable: " +
uri);
}
}
return uri;
}
/**
* Get the default port for this FileSystem.
* @return the default port or 0 if there isn't one
*/
protected int getDefaultPort() {
return 0;
}
protected static FileSystem getFSofPath(final Path absOrFqPath,
final Configuration conf)
throws UnsupportedFileSystemException, IOException {
absOrFqPath.checkNotSchemeWithRelative();
absOrFqPath.checkNotRelative();
// Uses the default FileSystem if not fully qualified
return get(absOrFqPath.toUri(), conf);
}
/**
* Get a canonical service name for this FileSystem.
* The token cache is the only user of the canonical service name,
* and uses it to lookup this FileSystem's service tokens.
* If the file system provides a token of its own then it must have a
* canonical name, otherwise the canonical name can be null.
*
* Default implementation: If the FileSystem has child file systems
* (such as an embedded file system) then it is assumed that the FS has no
* tokens of its own and hence returns a null name; otherwise a service
* name is built using Uri and port.
*
* @return a service string that uniquely identifies this file system, null
* if the filesystem does not implement tokens
* @see SecurityUtil#buildDTServiceName(URI, int)
*/
@InterfaceAudience.Public
@InterfaceStability.Evolving
@Override
public String getCanonicalServiceName() {
return (getChildFileSystems() == null)
? SecurityUtil.buildDTServiceName(getUri(), getDefaultPort())
: null;
}
/**
* @return uri to string.
* @deprecated call {@link #getUri()} instead.
*/
@Deprecated
public String getName() { return getUri().toString(); }
/**
* @deprecated call {@link #get(URI, Configuration)} instead.
*
* @param name name.
* @param conf configuration.
* @return file system.
* @throws IOException If an I/O error occurred.
*/
@Deprecated
public static FileSystem getNamed(String name, Configuration conf)
throws IOException {
return get(URI.create(fixName(name)), conf);
}
/** Update old-format filesystem names, for back-compatibility. This should
* eventually be replaced with a checkName() method that throws an exception
* for old-format names.
*/
private static String fixName(String name) {
// convert old-format name to new-format name
if (name.equals("local")) { // "local" is now "file:///".
LOGGER.warn("\"local\" is a deprecated filesystem name."
+" Use \"file:///\" instead.");
name = "file:///";
} else if (name.indexOf('/')==-1) { // unqualified is "hdfs://"
LOGGER.warn("\""+name+"\" is a deprecated filesystem name."
+" Use \"hdfs://"+name+"/\" instead.");
name = "hdfs://"+name;
}
return name;
}
/**
* Get the local FileSystem.
* @param conf the configuration to configure the FileSystem with
* if it is newly instantiated.
* @return a LocalFileSystem
* @throws IOException if somehow the local FS cannot be instantiated.
*/
public static LocalFileSystem getLocal(Configuration conf)
throws IOException {
return (LocalFileSystem)get(LocalFileSystem.NAME, conf);
}
/**
* Get a FileSystem for this URI's scheme and authority.
* <ol>
* <li>
* If the configuration has the property
* {@code "fs.$SCHEME.impl.disable.cache"} set to true,
* a new instance will be created, initialized with the supplied URI and
* configuration, then returned without being cached.
* </li>
* <li>
* If the there is a cached FS instance matching the same URI, it will
* be returned.
* </li>
* <li>
* Otherwise: a new FS instance will be created, initialized with the
* configuration and URI, cached and returned to the caller.
* </li>
* </ol>
* @param uri uri of the filesystem.
* @param conf configrution.
* @return filesystem instance.
* @throws IOException if the FileSystem cannot be instantiated.
*/
public static FileSystem get(URI uri, Configuration conf) throws IOException {
String scheme = uri.getScheme();
String authority = uri.getAuthority();
if (scheme == null && authority == null) { // use default FS
return get(conf);
}
if (scheme != null && authority == null) { // no authority
URI defaultUri = getDefaultUri(conf);
if (scheme.equals(defaultUri.getScheme()) // if scheme matches default
&& defaultUri.getAuthority() != null) { // & default has authority
return get(defaultUri, conf); // return default
}
}
String disableCacheName = String.format("fs.%s.impl.disable.cache", scheme);
if (conf.getBoolean(disableCacheName, false)) {
LOGGER.debug("Bypassing cache to create filesystem {}", uri);
return createFileSystem(uri, conf);
}
return CACHE.get(uri, conf);
}
/**
* Returns the FileSystem for this URI's scheme and authority and the
* given user. Internally invokes {@link #newInstance(URI, Configuration)}
* @param uri uri of the filesystem.
* @param conf the configuration to use
* @param user to perform the get as
* @return filesystem instance
* @throws IOException if the FileSystem cannot be instantiated.
* @throws InterruptedException If the {@code UGI.doAs()} call was
* somehow interrupted.
*/
public static FileSystem newInstance(final URI uri, final Configuration conf,
final String user) throws IOException, InterruptedException {
String ticketCachePath =
conf.get(CommonConfigurationKeys.KERBEROS_TICKET_CACHE_PATH);
UserGroupInformation ugi =
UserGroupInformation.getBestUGI(ticketCachePath, user);
return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
@Override
public FileSystem run() throws IOException {
return newInstance(uri, conf);
}
});
}
/**
* Returns the FileSystem for this URI's scheme and authority.
* The entire URI is passed to the FileSystem instance's initialize method.
* This always returns a new FileSystem object.
* @param uri FS URI
* @param config configuration to use
* @return the new FS instance
* @throws IOException FS creation or initialization failure.
*/
public static FileSystem newInstance(URI uri, Configuration config)
throws IOException {
String scheme = uri.getScheme();
String authority = uri.getAuthority();
if (scheme == null) { // no scheme: use default FS
return newInstance(config);
}
if (authority == null) { // no authority
URI defaultUri = getDefaultUri(config);
if (scheme.equals(defaultUri.getScheme()) // if scheme matches default
&& defaultUri.getAuthority() != null) { // & default has authority
return newInstance(defaultUri, config); // return default
}
}
return CACHE.getUnique(uri, config);
}
/**
* Returns a unique configured FileSystem implementation for the default
* filesystem of the supplied configuration.
* This always returns a new FileSystem object.
* @param conf the configuration to use
* @return the new FS instance
* @throws IOException FS creation or initialization failure.
*/
public static FileSystem newInstance(Configuration conf) throws IOException {
return newInstance(getDefaultUri(conf), conf);
}
/**
* Get a unique local FileSystem object.
* @param conf the configuration to configure the FileSystem with
* @return a new LocalFileSystem object.
* @throws IOException FS creation or initialization failure.
*/
public static LocalFileSystem newInstanceLocal(Configuration conf)
throws IOException {
return (LocalFileSystem)newInstance(LocalFileSystem.NAME, conf);
}
/**
* Close all cached FileSystem instances. After this operation, they
* may not be used in any operations.
*
* @throws IOException a problem arose closing one or more filesystem.
*/
public static void closeAll() throws IOException {
debugLogFileSystemClose("closeAll", "");
CACHE.closeAll();
}
/**
* Close all cached FileSystem instances for a given UGI.
* Be sure those filesystems are not used anymore.
* @param ugi user group info to close
* @throws IOException a problem arose closing one or more filesystem.
*/
public static void closeAllForUGI(UserGroupInformation ugi)
throws IOException {
debugLogFileSystemClose("closeAllForUGI", "UGI: " + ugi);
CACHE.closeAll(ugi);
}
private static void debugLogFileSystemClose(String methodName,
String additionalInfo) {
if (LOGGER.isDebugEnabled()) {
Throwable throwable = new Throwable().fillInStackTrace();
LOGGER.debug("FileSystem.{}() by method: {}); {}", methodName,
throwable.getStackTrace()[2], additionalInfo);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("FileSystem.{}() full stack trace:", methodName,
throwable);
}
}
}
/**
* Qualify a path to one which uses this FileSystem and, if relative,
* made absolute.
* @param path to qualify.
* @return this path if it contains a scheme and authority and is absolute, or
* a new path that includes a path and authority and is fully qualified
* @see Path#makeQualified(URI, Path)
* @throws IllegalArgumentException if the path has a schema/URI different
* from this FileSystem.
*/
public Path makeQualified(Path path) {
checkPath(path);
return path.makeQualified(this.getUri(), this.getWorkingDirectory());
}
/**
* Get a new delegation token for this FileSystem.
* This is an internal method that should have been declared protected
* but wasn't historically.
* Callers should use {@link #addDelegationTokens(String, Credentials)}
*
* @param renewer the account name that is allowed to renew the token.
* @return a new delegation token or null if the FS does not support tokens.
* @throws IOException on any problem obtaining a token
*/
@InterfaceAudience.Private()
@Override
public Token<?> getDelegationToken(String renewer) throws IOException {
return null;
}
/**
* Get all the immediate child FileSystems embedded in this FileSystem.
* It does not recurse and get grand children. If a FileSystem
* has multiple child FileSystems, then it must return a unique list
* of those FileSystems. Default is to return null to signify no children.
*
* @return FileSystems that are direct children of this FileSystem,
* or null for "no children"
*/
@InterfaceAudience.LimitedPrivate({ "HDFS" })
@VisibleForTesting
public FileSystem[] getChildFileSystems() {
return null;
}
@InterfaceAudience.Private
@Override
public DelegationTokenIssuer[] getAdditionalTokenIssuers()
throws IOException {
return getChildFileSystems();
}
/**
* Create a file with the provided permission.
*
* The permission of the file is set to be the provided permission as in
* setPermission, not permission{@literal &~}umask
*
* The HDFS implementation is implemented using two RPCs.
* It is understood that it is inefficient,
* but the implementation is thread-safe. The other option is to change the
* value of umask in configuration to be 0, but it is not thread-safe.
*
* @param fs FileSystem
* @param file the name of the file to be created
* @param permission the permission of the file
* @return an output stream
* @throws IOException IO failure
*/
public static FSDataOutputStream create(FileSystem fs,
Path file, FsPermission permission) throws IOException {
// create the file with default permission
FSDataOutputStream out = fs.create(file);
// set its permission to the supplied one
fs.setPermission(file, permission);
return out;
}
/**
* Create a directory with the provided permission.
* The permission of the directory is set to be the provided permission as in
* setPermission, not permission{@literal &~}umask
*
* @see #create(FileSystem, Path, FsPermission)
*
* @param fs FileSystem handle
* @param dir the name of the directory to be created
* @param permission the permission of the directory
* @return true if the directory creation succeeds; false otherwise
* @throws IOException A problem creating the directories.
*/
public static boolean mkdirs(FileSystem fs, Path dir, FsPermission permission)
throws IOException {
// create the directory using the default permission
boolean result = fs.mkdirs(dir);
// set its permission to be the supplied one
fs.setPermission(dir, permission);
return result;
}
///////////////////////////////////////////////////////////////
// FileSystem
///////////////////////////////////////////////////////////////
protected FileSystem() {
super(null);
}
/**
* Check that a Path belongs to this FileSystem.
*
* The base implementation performs case insensitive equality checks
* of the URIs' schemes and authorities. Subclasses may implement slightly
* different checks.
* @param path to check
* @throws IllegalArgumentException if the path is not considered to be
* part of this FileSystem.
*
*/
protected void checkPath(Path path) {
Preconditions.checkArgument(path != null, "null path");
URI uri = path.toUri();
String thatScheme = uri.getScheme();
if (thatScheme == null) // fs is relative
return;
URI thisUri = getCanonicalUri();
String thisScheme = thisUri.getScheme();
//authority and scheme are not case sensitive
if (thisScheme.equalsIgnoreCase(thatScheme)) {// schemes match
String thisAuthority = thisUri.getAuthority();
String thatAuthority = uri.getAuthority();
if (thatAuthority == null && // path's authority is null
thisAuthority != null) { // fs has an authority
URI defaultUri = getDefaultUri(getConf());
if (thisScheme.equalsIgnoreCase(defaultUri.getScheme())) {
uri = defaultUri; // schemes match, so use this uri instead
} else {
uri = null; // can't determine auth of the path
}
}
if (uri != null) {
// canonicalize uri before comparing with this fs
uri = canonicalizeUri(uri);
thatAuthority = uri.getAuthority();
if (thisAuthority == thatAuthority || // authorities match
(thisAuthority != null &&
thisAuthority.equalsIgnoreCase(thatAuthority)))
return;
}
}
throw new IllegalArgumentException("Wrong FS: " + path +
", expected: " + this.getUri());
}
/**
* Return an array containing hostnames, offset and size of
* portions of the given file. For nonexistent
* file or regions, {@code null} is returned.
*
* <pre>
* if f == null :
* result = null
* elif f.getLen() {@literal <=} start:
* result = []
* else result = [ locations(FS, b) for b in blocks(FS, p, s, s+l)]
* </pre>
* This call is most helpful with and distributed filesystem
* where the hostnames of machines that contain blocks of the given file
* can be determined.
*
* The default implementation returns an array containing one element:
* <pre>
* BlockLocation( { "localhost:9866" }, { "localhost" }, 0, file.getLen())
* </pre>
*
* In HDFS, if file is three-replicated, the returned array contains
* elements like:
* <pre>
* BlockLocation(offset: 0, length: BLOCK_SIZE,
* hosts: {"host1:9866", "host2:9866, host3:9866"})
* BlockLocation(offset: BLOCK_SIZE, length: BLOCK_SIZE,
* hosts: {"host2:9866", "host3:9866, host4:9866"})
* </pre>
*
* And if a file is erasure-coded, the returned BlockLocation are logical
* block groups.
*
* Suppose we have a RS_3_2 coded file (3 data units and 2 parity units).
* 1. If the file size is less than one stripe size, say 2 * CELL_SIZE, then
* there will be one BlockLocation returned, with 0 offset, actual file size
* and 4 hosts (2 data blocks and 2 parity blocks) hosting the actual blocks.
* 3. If the file size is less than one group size but greater than one
* stripe size, then there will be one BlockLocation returned, with 0 offset,
* actual file size with 5 hosts (3 data blocks and 2 parity blocks) hosting
* the actual blocks.
* 4. If the file size is greater than one group size, 3 * BLOCK_SIZE + 123
* for example, then the result will be like:
* <pre>
* BlockLocation(offset: 0, length: 3 * BLOCK_SIZE, hosts: {"host1:9866",
* "host2:9866","host3:9866","host4:9866","host5:9866"})
* BlockLocation(offset: 3 * BLOCK_SIZE, length: 123, hosts: {"host1:9866",
* "host4:9866", "host5:9866"})
* </pre>
*
* @param file FilesStatus to get data from
* @param start offset into the given file
* @param len length for which to get locations for
* @throws IOException IO failure
* @return block location array.
*/
public BlockLocation[] getFileBlockLocations(FileStatus file,
long start, long len) throws IOException {
if (file == null) {
return null;
}
if (start < 0 || len < 0) {
throw new IllegalArgumentException("Invalid start or len parameter");
}
if (file.getLen() <= start) {
return new BlockLocation[0];
}
String[] name = {"localhost:9866"};
String[] host = {"localhost"};
return new BlockLocation[] {
new BlockLocation(name, host, 0, file.getLen()) };
}
/**
* Return an array containing hostnames, offset and size of
* portions of the given file. For a nonexistent
* file or regions, {@code null} is returned.
*
* This call is most helpful with location-aware distributed
* filesystems, where it returns hostnames of machines that
* contain the given file.
*
* A FileSystem will normally return the equivalent result
* of passing the {@code FileStatus} of the path to
* {@link #getFileBlockLocations(FileStatus, long, long)}
*
* @param p path is used to identify an FS since an FS could have
* another FS that it could be delegating the call to
* @param start offset into the given file
* @param len length for which to get locations for
* @throws FileNotFoundException when the path does not exist
* @throws IOException IO failure
* @return block location array.
*/
public BlockLocation[] getFileBlockLocations(Path p,
long start, long len) throws IOException {
if (p == null) {
throw new NullPointerException();
}
FileStatus file = getFileStatus(p);
return getFileBlockLocations(file, start, len);
}
/**
* Return a set of server default configuration values.
* @return server default configuration values
* @throws IOException IO failure
* @deprecated use {@link #getServerDefaults(Path)} instead
*/
@Deprecated
public FsServerDefaults getServerDefaults() throws IOException {
Configuration config = getConf();
// CRC32 is chosen as default as it is available in all
// releases that support checksum.
// The client trash configuration is ignored.
return new FsServerDefaults(getDefaultBlockSize(),
config.getInt("io.bytes.per.checksum", 512),
64 * 1024,
getDefaultReplication(),
config.getInt(IO_FILE_BUFFER_SIZE_KEY, IO_FILE_BUFFER_SIZE_DEFAULT),
false,
FS_TRASH_INTERVAL_DEFAULT,
DataChecksum.Type.CRC32,
"");
}
/**
* Return a set of server default configuration values.
* @param p path is used to identify an FS since an FS could have
* another FS that it could be delegating the call to
* @return server default configuration values
* @throws IOException IO failure
*/
public FsServerDefaults getServerDefaults(Path p) throws IOException {
return getServerDefaults();
}
/**
* Return the fully-qualified path of path, resolving the path
* through any symlinks or mount point.
* @param p path to be resolved
* @return fully qualified path
* @throws FileNotFoundException if the path is not present
* @throws IOException for any other error
*/
public Path resolvePath(final Path p) throws IOException {
checkPath(p);
return getFileStatus(p).getPath();
}
/**
* Opens an FSDataInputStream at the indicated Path.
* @param f the file name to open
* @param bufferSize the size of the buffer to be used.
* @throws IOException IO failure
* @return input stream.
*/
public abstract FSDataInputStream open(Path f, int bufferSize)
throws IOException;
/**
* Opens an FSDataInputStream at the indicated Path.
* @param f the file to open
* @throws IOException IO failure
* @return input stream.
*/
public FSDataInputStream open(Path f) throws IOException {
return open(f, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT));
}
/**
* Open an FSDataInputStream matching the PathHandle instance. The
* implementation may encode metadata in PathHandle to address the
* resource directly and verify that the resource referenced
* satisfies constraints specified at its construciton.
* @param fd PathHandle object returned by the FS authority.
* @throws InvalidPathHandleException If {@link PathHandle} constraints are
* not satisfied
* @throws IOException IO failure
* @throws UnsupportedOperationException If {@link #open(PathHandle, int)}
* not overridden by subclass
* @return input stream.
*/
public FSDataInputStream open(PathHandle fd) throws IOException {
return open(fd, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT));
}
/**
* Open an FSDataInputStream matching the PathHandle instance. The
* implementation may encode metadata in PathHandle to address the
* resource directly and verify that the resource referenced
* satisfies constraints specified at its construciton.
* @param fd PathHandle object returned by the FS authority.
* @param bufferSize the size of the buffer to use
* @throws InvalidPathHandleException If {@link PathHandle} constraints are
* not satisfied
* @throws IOException IO failure
* @throws UnsupportedOperationException If not overridden by subclass
* @return input stream.
*/
public FSDataInputStream open(PathHandle fd, int bufferSize)
throws IOException {
throw new UnsupportedOperationException();
}
/**
* Create a durable, serializable handle to the referent of the given
* entity.
* @param stat Referent in the target FileSystem
* @param opt If absent, assume {@link HandleOpt#path()}.
* @throws IllegalArgumentException If the FileStatus does not belong to
* this FileSystem
* @throws UnsupportedOperationException If {@link #createPathHandle}
* not overridden by subclass.
* @throws UnsupportedOperationException If this FileSystem cannot enforce
* the specified constraints.
* @return path handle.
*/
public final PathHandle getPathHandle(FileStatus stat, HandleOpt... opt) {
// method is final with a default so clients calling getPathHandle(stat)
// get the same semantics for all FileSystem implementations
if (null == opt || 0 == opt.length) {
return createPathHandle(stat, HandleOpt.path());
}
return createPathHandle(stat, opt);
}
/**
* Hook to implement support for {@link PathHandle} operations.
* @param stat Referent in the target FileSystem
* @param opt Constraints that determine the validity of the
* {@link PathHandle} reference.
* @return path handle.
*/
protected PathHandle createPathHandle(FileStatus stat, HandleOpt... opt) {
throw new UnsupportedOperationException();
}
/**
* Create an FSDataOutputStream at the indicated Path.
* Files are overwritten by default.
* @param f the file to create
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f) throws IOException {
return create(f, true);
}
/**
* Create an FSDataOutputStream at the indicated Path.
* @param f the file to create
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an exception will be thrown.
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f, boolean overwrite)
throws IOException {
return create(f, overwrite,
getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT),
getDefaultReplication(f),
getDefaultBlockSize(f));
}
/**
* Create an FSDataOutputStream at the indicated Path with write-progress
* reporting.
* Files are overwritten by default.
* @param f the file to create
* @param progress to report progress
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f, Progressable progress)
throws IOException {
return create(f, true,
getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT),
getDefaultReplication(f),
getDefaultBlockSize(f), progress);
}
/**
* Create an FSDataOutputStream at the indicated Path.
* Files are overwritten by default.
* @param f the file to create
* @param replication the replication factor
* @throws IOException IO failure
* @return output stream1
*/
public FSDataOutputStream create(Path f, short replication)
throws IOException {
return create(f, true,
getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT),
replication,
getDefaultBlockSize(f));
}
/**
* Create an FSDataOutputStream at the indicated Path with write-progress
* reporting.
* Files are overwritten by default.
* @param f the file to create
* @param replication the replication factor
* @param progress to report progress
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f, short replication,
Progressable progress) throws IOException {
return create(f, true,
getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT),
replication, getDefaultBlockSize(f), progress);
}
/**
* Create an FSDataOutputStream at the indicated Path.
* @param f the file to create
* @param overwrite if a path with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f,
boolean overwrite,
int bufferSize
) throws IOException {
return create(f, overwrite, bufferSize,
getDefaultReplication(f),
getDefaultBlockSize(f));
}
/**
* Create an {@link FSDataOutputStream} at the indicated Path
* with write-progress reporting.
*
* The frequency of callbacks is implementation-specific; it may be "none".
* @param f the path of the file to open
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param progress to report progress.
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f,
boolean overwrite,
int bufferSize,
Progressable progress
) throws IOException {
return create(f, overwrite, bufferSize,
getDefaultReplication(f),
getDefaultBlockSize(f), progress);
}
/**
* Create an FSDataOutputStream at the indicated Path.
* @param f the file name to open
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize the size of the buffer to be used.
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f,
boolean overwrite,
int bufferSize,
short replication,
long blockSize) throws IOException {
return create(f, overwrite, bufferSize, replication, blockSize, null);
}
/**
* Create an FSDataOutputStream at the indicated Path with write-progress
* reporting.
* @param f the file name to open
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize the size of the buffer to be used.
* @param progress to report progress.
* @throws IOException IO failure
* @return output stream.
*/
public FSDataOutputStream create(Path f,
boolean overwrite,
int bufferSize,
short replication,
long blockSize,
Progressable progress
) throws IOException {
return this.create(f, FsCreateModes.applyUMask(
FsPermission.getFileDefault(), FsPermission.getUMask(getConf())),
overwrite, bufferSize, replication, blockSize, progress);
}
/**
* Create an FSDataOutputStream at the indicated Path with write-progress
* reporting.
* @param f the file name to open
* @param permission file permission
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public abstract FSDataOutputStream create(Path f,
FsPermission permission,
boolean overwrite,
int bufferSize,
short replication,
long blockSize,
Progressable progress) throws IOException;
/**
* Create an FSDataOutputStream at the indicated Path with write-progress
* reporting.
* @param f the file name to open
* @param permission file permission
* @param flags {@link CreateFlag}s to use for this stream.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public FSDataOutputStream create(Path f,
FsPermission permission,
EnumSet<CreateFlag> flags,
int bufferSize,
short replication,
long blockSize,
Progressable progress) throws IOException {
return create(f, permission, flags, bufferSize, replication,
blockSize, progress, null);
}
/**
* Create an FSDataOutputStream at the indicated Path with a custom
* checksum option.
* @param f the file name to open
* @param permission file permission
* @param flags {@link CreateFlag}s to use for this stream.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @param checksumOpt checksum parameter. If null, the values
* found in conf will be used.
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public FSDataOutputStream create(Path f,
FsPermission permission,
EnumSet<CreateFlag> flags,
int bufferSize,
short replication,
long blockSize,
Progressable progress,
ChecksumOpt checksumOpt) throws IOException {
// Checksum options are ignored by default. The file systems that
// implement checksum need to override this method. The full
// support is currently only available in DFS.
return create(f, permission, flags.contains(CreateFlag.OVERWRITE),
bufferSize, replication, blockSize, progress);
}
/**
* This create has been added to support the FileContext that processes
* the permission with umask before calling this method.
* This a temporary method added to support the transition from FileSystem
* to FileContext for user applications.
*
* @param f path.
* @param absolutePermission permission.
* @param flag create flag.
* @param bufferSize buffer size.
* @param replication replication.
* @param blockSize block size.
* @param progress progress.
* @param checksumOpt check sum opt.
* @return output stream.
* @throws IOException IO failure
*/
@Deprecated
protected FSDataOutputStream primitiveCreate(Path f,
FsPermission absolutePermission,
EnumSet<CreateFlag> flag,
int bufferSize,
short replication,
long blockSize,
Progressable progress,
ChecksumOpt checksumOpt) throws IOException {
boolean pathExists = exists(f);
CreateFlag.validate(f, pathExists, flag);
// Default impl assumes that permissions do not matter and
// nor does the bytesPerChecksum hence
// calling the regular create is good enough.
// FSs that implement permissions should override this.
if (pathExists && flag.contains(CreateFlag.APPEND)) {
return append(f, bufferSize, progress);
}
return this.create(f, absolutePermission,
flag.contains(CreateFlag.OVERWRITE), bufferSize, replication,
blockSize, progress);
}
/**
* This version of the mkdirs method assumes that the permission is absolute.
* It has been added to support the FileContext that processes the permission
* with umask before calling this method.
* This a temporary method added to support the transition from FileSystem
* to FileContext for user applications.
* @param f path
* @param absolutePermission permissions
* @return true if the directory was actually created.
* @throws IOException IO failure
* @see #mkdirs(Path, FsPermission)
*/
@Deprecated
protected boolean primitiveMkdir(Path f, FsPermission absolutePermission)
throws IOException {
return this.mkdirs(f, absolutePermission);
}
/**
* This version of the mkdirs method assumes that the permission is absolute.
* It has been added to support the FileContext that processes the permission
* with umask before calling this method.
* This a temporary method added to support the transition from FileSystem
* to FileContext for user applications.
*
* @param f the path.
* @param absolutePermission permission.
* @param createParent create parent.
* @throws IOException IO failure.
*/
@Deprecated
protected void primitiveMkdir(Path f, FsPermission absolutePermission,
boolean createParent)
throws IOException {
if (!createParent) { // parent must exist.
// since the this.mkdirs makes parent dirs automatically
// we must throw exception if parent does not exist.
final FileStatus stat = getFileStatus(f.getParent());
if (stat == null) {
throw new FileNotFoundException("Missing parent:" + f);
}
if (!stat.isDirectory()) {
throw new ParentNotDirectoryException("parent is not a dir");
}
// parent does exist - go ahead with mkdir of leaf
}
// Default impl is to assume that permissions do not matter and hence
// calling the regular mkdirs is good enough.
// FSs that implement permissions should override this.
if (!this.mkdirs(f, absolutePermission)) {
throw new IOException("mkdir of "+ f + " failed");
}
}
/**
* Opens an FSDataOutputStream at the indicated Path with write-progress
* reporting. Same as create(), except fails if parent directory doesn't
* already exist.
* @param f the file name to open
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public FSDataOutputStream createNonRecursive(Path f,
boolean overwrite,
int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
return this.createNonRecursive(f, FsPermission.getFileDefault(),
overwrite, bufferSize, replication, blockSize, progress);
}
/**
* Opens an FSDataOutputStream at the indicated Path with write-progress
* reporting. Same as create(), except fails if parent directory doesn't
* already exist.
* @param f the file name to open
* @param permission file permission
* @param overwrite if a file with this name already exists, then if true,
* the file will be overwritten, and if false an error will be thrown.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public FSDataOutputStream createNonRecursive(Path f, FsPermission permission,
boolean overwrite, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
return createNonRecursive(f, permission,
overwrite ? EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE)
: EnumSet.of(CreateFlag.CREATE), bufferSize,
replication, blockSize, progress);
}
/**
* Opens an FSDataOutputStream at the indicated Path with write-progress
* reporting. Same as create(), except fails if parent directory doesn't
* already exist.
* @param f the file name to open
* @param permission file permission
* @param flags {@link CreateFlag}s to use for this stream.
* @param bufferSize the size of the buffer to be used.
* @param replication required block replication for the file.
* @param blockSize block size
* @param progress the progress reporter
* @throws IOException IO failure
* @see #setPermission(Path, FsPermission)
* @return output stream.
*/
public FSDataOutputStream createNonRecursive(Path f, FsPermission permission,
EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize,
Progressable progress) throws IOException {
throw new IOException("createNonRecursive unsupported for this filesystem "
+ this.getClass());
}
/**
* Creates the given Path as a brand-new zero-length file. If
* create fails, or if it already existed, return false.
* <i>Important: the default implementation is not atomic</i>
* @param f path to use for create
* @throws IOException IO failure
* @return if create new file success true,not false.
*/
public boolean createNewFile(Path f) throws IOException {
if (exists(f)) {
return false;
} else {
create(f, false, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT)).close();
return true;
}
}
/**
* Append to an existing file (optional operation).
* Same as
* {@code append(f, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
* IO_FILE_BUFFER_SIZE_DEFAULT), null)}
* @param f the existing file to be appended.
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
* @return output stream.
*/
public FSDataOutputStream append(Path f) throws IOException {
return append(f, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT), null);
}
/**
* Append to an existing file (optional operation).
* Same as append(f, bufferSize, null).
* @param f the existing file to be appended.
* @param bufferSize the size of the buffer to be used.
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
* @return output stream.
*/
public FSDataOutputStream append(Path f, int bufferSize) throws IOException {
return append(f, bufferSize, null);
}
/**
* Append to an existing file (optional operation).
* @param f the existing file to be appended.
* @param bufferSize the size of the buffer to be used.
* @param progress for reporting progress if it is not null.
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
* @return output stream.
*/
public abstract FSDataOutputStream append(Path f, int bufferSize,
Progressable progress) throws IOException;
/**
* Append to an existing file (optional operation).
* @param f the existing file to be appended.
* @param appendToNewBlock whether to append data to a new block
* instead of the end of the last partial block
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
* @return output stream.
*/
public FSDataOutputStream append(Path f, boolean appendToNewBlock) throws IOException {
return append(f, getConf().getInt(IO_FILE_BUFFER_SIZE_KEY,
IO_FILE_BUFFER_SIZE_DEFAULT), null, appendToNewBlock);
}
/**
* Append to an existing file (optional operation).
* This function is used for being overridden by some FileSystem like DistributedFileSystem
* @param f the existing file to be appended.
* @param bufferSize the size of the buffer to be used.
* @param progress for reporting progress if it is not null.
* @param appendToNewBlock whether to append data to a new block
* instead of the end of the last partial block
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
* @return output stream.
*/
public FSDataOutputStream append(Path f, int bufferSize,
Progressable progress, boolean appendToNewBlock) throws IOException {
return append(f, bufferSize, progress);
}
/**
* Concat existing files together.
* @param trg the path to the target destination.
* @param psrcs the paths to the sources to use for the concatenation.
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
*/
public void concat(final Path trg, final Path [] psrcs) throws IOException {
throw new UnsupportedOperationException("Not implemented by the " +
getClass().getSimpleName() + " FileSystem implementation");
}
/**
* Get the replication factor.
*
* @deprecated Use {@link #getFileStatus(Path)} instead
* @param src file name
* @return file replication
* @throws FileNotFoundException if the path does not resolve.
* @throws IOException an IO failure
*/
@Deprecated
public short getReplication(Path src) throws IOException {
return getFileStatus(src).getReplication();
}
/**
* Set the replication for an existing file.
* If a filesystem does not support replication, it will always
* return true: the check for a file existing may be bypassed.
* This is the default behavior.
* @param src file name
* @param replication new replication
* @throws IOException an IO failure.
* @return true if successful, or the feature in unsupported;
* false if replication is supported but the file does not exist,
* or is a directory
*/
public boolean setReplication(Path src, short replication)
throws IOException {
return true;
}
/**
* Renames Path src to Path dst.
* @param src path to be renamed
* @param dst new path after rename
* @throws IOException on failure
* @return true if rename is successful
*/
public abstract boolean rename(Path src, Path dst) throws IOException;
/**
* Renames Path src to Path dst
* <ul>
* <li>Fails if src is a file and dst is a directory.</li>
* <li>Fails if src is a directory and dst is a file.</li>
* <li>Fails if the parent of dst does not exist or is a file.</li>
* </ul>
* <p>
* If OVERWRITE option is not passed as an argument, rename fails
* if the dst already exists.
* </p>
* <p>
* If OVERWRITE option is passed as an argument, rename overwrites
* the dst if it is a file or an empty directory. Rename fails if dst is
* a non-empty directory.
* </p>
* Note that atomicity of rename is dependent on the file system
* implementation. Please refer to the file system documentation for
* details. This default implementation is non atomic.
* <p>
* This method is deprecated since it is a temporary method added to
* support the transition from FileSystem to FileContext for user
* applications.
* </p>
*
* @param src path to be renamed
* @param dst new path after rename
* @param options rename options.
* @throws FileNotFoundException src path does not exist, or the parent
* path of dst does not exist.
* @throws FileAlreadyExistsException dest path exists and is a file
* @throws ParentNotDirectoryException if the parent path of dest is not
* a directory
* @throws IOException on failure
*/
@Deprecated
protected void rename(final Path src, final Path dst,
final Rename... options) throws IOException {
// Default implementation
final FileStatus srcStatus = getFileLinkStatus(src);
if (srcStatus == null) {
throw new FileNotFoundException("rename source " + src + " not found.");
}
boolean overwrite = false;
if (null != options) {
for (Rename option : options) {
if (option == Rename.OVERWRITE) {
overwrite = true;
}
}
}
FileStatus dstStatus;
try {
dstStatus = getFileLinkStatus(dst);
} catch (IOException e) {
dstStatus = null;
}
if (dstStatus != null) {
if (srcStatus.isDirectory() != dstStatus.isDirectory()) {
throw new IOException("Source " + src + " Destination " + dst
+ " both should be either file or directory");
}
if (!overwrite) {
throw new FileAlreadyExistsException("rename destination " + dst
+ " already exists.");
}
// Delete the destination that is a file or an empty directory
if (dstStatus.isDirectory()) {
FileStatus[] list = listStatus(dst);
if (list != null && list.length != 0) {
throw new IOException(
"rename cannot overwrite non empty destination directory " + dst);
}
}
delete(dst, false);
} else {
final Path parent = dst.getParent();
final FileStatus parentStatus = getFileStatus(parent);
if (parentStatus == null) {
throw new FileNotFoundException("rename destination parent " + parent
+ " not found.");
}
if (!parentStatus.isDirectory()) {
throw new ParentNotDirectoryException("rename destination parent " + parent
+ " is a file.");
}
}
if (!rename(src, dst)) {
throw new IOException("rename from " + src + " to " + dst + " failed.");
}
}
/**
* Truncate the file in the indicated path to the indicated size.
* <ul>
* <li>Fails if path is a directory.</li>
* <li>Fails if path does not exist.</li>
* <li>Fails if path is not closed.</li>
* <li>Fails if new size is greater than current size.</li>
* </ul>
* @param f The path to the file to be truncated
* @param newLength The size the file is to be truncated to
*
* @return <code>true</code> if the file has been truncated to the desired
* <code>newLength</code> and is immediately available to be reused for
* write operations such as <code>append</code>, or
* <code>false</code> if a background process of adjusting the length of
* the last block has been started, and clients should wait for it to
* complete before proceeding with further file updates.
* @throws IOException IO failure
* @throws UnsupportedOperationException if the operation is unsupported
* (default).
*/
public boolean truncate(Path f, long newLength) throws IOException {
throw new UnsupportedOperationException("Not implemented by the " +
getClass().getSimpleName() + " FileSystem implementation");
}
/**
* Delete a file/directory.
* @param f the path.
* @throws IOException IO failure.
* @return if delete success true, not false.
* @deprecated Use {@link #delete(Path, boolean)} instead.
*/
@Deprecated
public boolean delete(Path f) throws IOException {
return delete(f, true);
}
/** Delete a file.
*
* @param f the path to delete.
* @param recursive if path is a directory and set to
* true, the directory is deleted else throws an exception. In
* case of a file the recursive can be set to either true or false.
* @return true if delete is successful else false.
* @throws IOException IO failure
*/
public abstract boolean delete(Path f, boolean recursive) throws IOException;
/**
* Mark a path to be deleted when its FileSystem is closed.
* When the JVM shuts down cleanly, all cached FileSystem objects will be
* closed automatically. These the marked paths will be deleted as a result.
*
* If a FileSystem instance is not cached, i.e. has been created with
* {@link #createFileSystem(URI, Configuration)}, then the paths will
* be deleted in when {@link #close()} is called on that instance.
*
* The path must exist in the filesystem at the time of the method call;
* it does not have to exist at the time of JVM shutdown.
*
* Notes
* <ol>
* <li>Clean shutdown of the JVM cannot be guaranteed.</li>
* <li>The time to shut down a FileSystem will depends on the number of
* files to delete. For filesystems where the cost of checking
* for the existence of a file/directory and the actual delete operation
* (for example: object stores) is high, the time to shutdown the JVM can be
* significantly extended by over-use of this feature.</li>
* <li>Connectivity problems with a remote filesystem may delay shutdown
* further, and may cause the files to not be deleted.</li>
* </ol>
* @param f the path to delete.
* @return true if deleteOnExit is successful, otherwise false.
* @throws IOException IO failure
*/
public boolean deleteOnExit(Path f) throws IOException {
if (!exists(f)) {
return false;
}
synchronized (deleteOnExit) {
deleteOnExit.add(f);
}
return true;
}
/**
* Cancel the scheduled deletion of the path when the FileSystem is closed.
* @param f the path to cancel deletion
* @return true if the path was found in the delete-on-exit list.
*/
public boolean cancelDeleteOnExit(Path f) {
synchronized (deleteOnExit) {
return deleteOnExit.remove(f);
}
}
/**
* Delete all paths that were marked as delete-on-exit. This recursively
* deletes all files and directories in the specified paths.
*
* The time to process this operation is {@code O(paths)}, with the actual
* time dependent on the time for existence and deletion operations to
* complete, successfully or not.
*/
protected void processDeleteOnExit() {
synchronized (deleteOnExit) {
for (Iterator<Path> iter = deleteOnExit.iterator(); iter.hasNext();) {
Path path = iter.next();
try {
if (exists(path)) {
delete(path, true);
}
}
catch (IOException e) {
LOGGER.info("Ignoring failure to deleteOnExit for path {}", path);
}
iter.remove();
}
}
}
/** Check if a path exists.
*
* It is highly discouraged to call this method back to back with other
* {@link #getFileStatus(Path)} calls, as this will involve multiple redundant
* RPC calls in HDFS.
*
* @param f source path
* @return true if the path exists
* @throws IOException IO failure
*/
public boolean exists(Path f) throws IOException {
try {
return getFileStatus(f) != null;
} catch (FileNotFoundException e) {
return false;
}
}
/** True iff the named path is a directory.
* Note: Avoid using this method. Instead reuse the FileStatus
* returned by getFileStatus() or listStatus() methods.
*
* @param f path to check
* @throws IOException IO failure
* @deprecated Use {@link #getFileStatus(Path)} instead
* @return if f is directory true, not false.
*/
@Deprecated
public boolean isDirectory(Path f) throws IOException {
try {
return getFileStatus(f).isDirectory();
} catch (FileNotFoundException e) {
return false; // f does not exist
}
}
/** True iff the named path is a regular file.
* Note: Avoid using this method. Instead reuse the FileStatus
* returned by {@link #getFileStatus(Path)} or listStatus() methods.
*
* @param f path to check
* @throws IOException IO failure
* @deprecated Use {@link #getFileStatus(Path)} instead
* @return if f is file true, not false.
*/
@Deprecated
public boolean isFile(Path f) throws IOException {
try {
return getFileStatus(f).isFile();
} catch (FileNotFoundException e) {
return false; // f does not exist
}
}
/**
* The number of bytes in a file.
* @param f the path.
* @return the number of bytes; 0 for a directory
* @deprecated Use {@link #getFileStatus(Path)} instead.
* @throws FileNotFoundException if the path does not resolve
* @throws IOException IO failure
*/
@Deprecated
public long getLength(Path f) throws IOException {
return getFileStatus(f).getLen();
}
/** Return the {@link ContentSummary} of a given {@link Path}.
* @param f path to use
* @throws FileNotFoundException if the path does not resolve
* @throws IOException IO failure
* @return content summary.
*/
public ContentSummary getContentSummary(Path f) throws IOException {
FileStatus status = getFileStatus(f);
if (status.isFile()) {
// f is a file
long length = status.getLen();
return new ContentSummary.Builder().length(length).
fileCount(1).directoryCount(0).spaceConsumed(length).build();
}
// f is a directory
long[] summary = {0, 0, 1};
for(FileStatus s : listStatus(f)) {
long length = s.getLen();
ContentSummary c = s.isDirectory() ? getContentSummary(s.getPath()) :
new ContentSummary.Builder().length(length).
fileCount(1).directoryCount(0).spaceConsumed(length).build();
summary[0] += c.getLength();
summary[1] += c.getFileCount();
summary[2] += c.getDirectoryCount();
}
return new ContentSummary.Builder().length(summary[0]).
fileCount(summary[1]).directoryCount(summary[2]).
spaceConsumed(summary[0]).build();
}
/** Return the {@link QuotaUsage} of a given {@link Path}.
* @param f path to use
* @return the quota usage
* @throws IOException IO failure
*/
public QuotaUsage getQuotaUsage(Path f) throws IOException {
return getContentSummary(f);
}
/**
* Set quota for the given {@link Path}.
*
* @param src the target path to set quota for
* @param namespaceQuota the namespace quota (i.e., # of files/directories)
* to set
* @param storagespaceQuota the storage space quota to set
* @throws IOException IO failure
*/
public void setQuota(Path src, final long namespaceQuota,
final long storagespaceQuota) throws IOException {
methodNotSupported();
}
/**
* Set per storage type quota for the given {@link Path}.
*
* @param src the target path to set storage type quota for
* @param type the storage type to set
* @param quota the quota to set for the given storage type
* @throws IOException IO failure
*/
public void setQuotaByStorageType(Path src, final StorageType type,
final long quota) throws IOException {
methodNotSupported();
}
/**
* The default filter accepts all paths.
*/
private static final PathFilter DEFAULT_FILTER = new PathFilter() {
@Override
public boolean accept(Path file) {
return true;
}
};
/**
* List the statuses of the files/directories in the given path if the path is
* a directory.
* <p>
* Does not guarantee to return the List of files/directories status in a
* sorted order.
* <p>
* Will not return null. Expect IOException upon access error.
* @param f given path
* @return the statuses of the files/directories in the given patch
* @throws FileNotFoundException when the path does not exist
* @throws IOException see specific implementation
*/
public abstract FileStatus[] listStatus(Path f) throws FileNotFoundException,
IOException;
/**
* Represents a batch of directory entries when iteratively listing a
* directory. This is a private API not meant for use by end users.
* <p>
* For internal use by FileSystem subclasses that override
* {@link FileSystem#listStatusBatch(Path, byte[])} to implement iterative
* listing.
*/
@InterfaceAudience.Private
public static
|
itself
|
java
|
apache__dubbo
|
dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.java
|
{
"start": 4561,
"end": 5168
}
|
class ____<T>
implements FactoryBean<T>,
ApplicationContextAware,
BeanClassLoaderAware,
BeanNameAware,
InitializingBean,
DisposableBean {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private transient ApplicationContext applicationContext;
private ClassLoader beanClassLoader;
// lazy proxy of reference
private Object lazyProxy;
// beanName
protected String id;
// reference key
private String key;
/**
* The
|
ReferenceBean
|
java
|
grpc__grpc-java
|
binder/src/androidTest/java/io/grpc/binder/HostServices.java
|
{
"start": 1926,
"end": 2063
}
|
interface ____ {
Server createServer(Service service, IBinderReceiver receiver);
}
@AutoValue
public abstract static
|
ServerFactory
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/operators/CombineTaskTest.java
|
{
"start": 8110,
"end": 9044
}
|
class ____
implements GroupReduceFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>>,
GroupCombineFunction<Tuple2<Integer, Integer>, Tuple2<Integer, Integer>> {
private static final long serialVersionUID = 1L;
@Override
public void reduce(
Iterable<Tuple2<Integer, Integer>> records,
Collector<Tuple2<Integer, Integer>> out) {
int key = 0;
int sum = 0;
for (Tuple2<Integer, Integer> next : records) {
key = next.f0;
sum += next.f1;
}
out.collect(new Tuple2<>(key, sum));
}
@Override
public void combine(
Iterable<Tuple2<Integer, Integer>> records,
Collector<Tuple2<Integer, Integer>> out) {
reduce(records, out);
}
}
public static final
|
MockCombiningReduceStub
|
java
|
spring-projects__spring-framework
|
spring-test/src/main/java/org/springframework/test/context/event/PrepareTestInstanceEvent.java
|
{
"start": 1124,
"end": 1261
}
|
class ____ extends TestContextEvent {
public PrepareTestInstanceEvent(TestContext source) {
super(source);
}
}
|
PrepareTestInstanceEvent
|
java
|
elastic__elasticsearch
|
server/src/test/java/org/elasticsearch/common/xcontent/yaml/YamlXContentTests.java
|
{
"start": 782,
"end": 1184
}
|
class ____ extends BaseXContentTestCase {
@Override
public XContentType xcontentType() {
return XContentType.YAML;
}
public void testBigInteger() throws Exception {
ByteArrayOutputStream os = new ByteArrayOutputStream();
XContentGenerator generator = YamlXContent.yamlXContent.createGenerator(os);
doTestBigInteger(generator, os);
}
}
|
YamlXContentTests
|
java
|
apache__maven
|
impl/maven-core/src/test/java/org/apache/maven/MavenLifecycleParticipantTest.java
|
{
"start": 2760,
"end": 6162
}
|
class ____ extends AbstractMavenLifecycleParticipant {
@Override
public void afterProjectsRead(MavenSession session) {
injectReactorDependency(session.getProjects(), "module-a", "module-b");
}
private void injectReactorDependency(List<MavenProject> projects, String moduleFrom, String moduleTo) {
for (MavenProject project : projects) {
if (moduleFrom.equals(project.getArtifactId())) {
Dependency dependency = new Dependency();
dependency.setArtifactId(moduleTo);
dependency.setGroupId(project.getGroupId());
dependency.setVersion(project.getVersion());
project.getModel().addDependency(dependency);
}
}
}
}
@Override
protected String getProjectsDirectory() {
return "src/test/projects/lifecycle-listener";
}
@Test
void testDependencyInjection() throws Exception {
PlexusContainer container = getContainer();
ComponentDescriptor<? extends AbstractMavenLifecycleParticipant> cd =
new ComponentDescriptor<>(InjectDependencyLifecycleListener.class, container.getContainerRealm());
cd.setRoleClass(AbstractMavenLifecycleParticipant.class);
container.addComponentDescriptor(cd);
Maven maven = container.lookup(Maven.class);
File pom = getProject("lifecycle-listener-dependency-injection");
MavenExecutionRequest request = createMavenExecutionRequest(pom);
request.setGoals(Arrays.asList("validate"));
MavenExecutionResult result = maven.execute(request);
assertFalse(result.hasExceptions(), result.getExceptions().toString());
MavenProject project = result.getProject();
assertEquals("bar", project.getProperties().getProperty("foo"));
ArrayList<Artifact> artifacts = new ArrayList<>(project.getArtifacts());
assertEquals(1, artifacts.size());
assertEquals(INJECTED_ARTIFACT_ID, artifacts.get(0).getArtifactId());
}
@Test
void testReactorDependencyInjection() throws Exception {
List<String> reactorOrder =
getReactorOrder("lifecycle-participant-reactor-dependency-injection", InjectReactorDependency.class);
assertEquals(Arrays.asList("parent", "module-b", "module-a"), reactorOrder);
}
private <T> List<String> getReactorOrder(String testProject, Class<T> participant) throws Exception {
PlexusContainer container = getContainer();
ComponentDescriptor<T> cd = new ComponentDescriptor<>(participant, container.getContainerRealm());
cd.setRoleClass(AbstractMavenLifecycleParticipant.class);
container.addComponentDescriptor(cd);
Maven maven = container.lookup(Maven.class);
File pom = getProject(testProject);
MavenExecutionRequest request = createMavenExecutionRequest(pom);
request.setGoals(Arrays.asList("validate"));
MavenExecutionResult result = maven.execute(request);
assertFalse(result.hasExceptions(), result.getExceptions().toString());
List<String> order = new ArrayList<>();
for (MavenProject project : result.getTopologicallySortedProjects()) {
order.add(project.getArtifactId());
}
return order;
}
}
|
InjectReactorDependency
|
java
|
apache__spark
|
sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/GetTableTypesOperation.java
|
{
"start": 1585,
"end": 3573
}
|
class ____ extends MetadataOperation {
protected static TableSchema RESULT_SET_SCHEMA = new TableSchema()
.addStringColumn("TABLE_TYPE", "Table type name.");
protected final RowSet rowSet;
private final TableTypeMapping tableTypeMapping;
protected GetTableTypesOperation(HiveSession parentSession) {
super(parentSession, OperationType.GET_TABLE_TYPES);
String tableMappingStr = getParentSession().getHiveConf()
.getVar(HiveConf.ConfVars.HIVE_SERVER2_TABLE_TYPE_MAPPING);
tableTypeMapping =
TableTypeMappingFactory.getTableTypeMapping(tableMappingStr);
rowSet = RowSetFactory.create(RESULT_SET_SCHEMA, getProtocolVersion(), false);
}
@Override
public void runInternal() throws HiveSQLException {
setState(OperationState.RUNNING);
if (isAuthV2Enabled()) {
authorizeMetaGets(HiveOperationType.GET_TABLETYPES, null);
}
try {
for (TableType type : TableType.values()) {
rowSet.addRow(new String[] {tableTypeMapping.mapToClientType(type.toString())});
}
setState(OperationState.FINISHED);
} catch (Exception e) {
setState(OperationState.ERROR);
throw new HiveSQLException(e);
}
}
/* (non-Javadoc)
* @see org.apache.hive.service.cli.Operation#getResultSetSchema()
*/
@Override
public TTableSchema getResultSetSchema() throws HiveSQLException {
assertState(OperationState.FINISHED);
return RESULT_SET_SCHEMA.toTTableSchema();
}
/* (non-Javadoc)
* @see org.apache.hive.service.cli.Operation#getNextRowSet(org.apache.hive.service.cli.FetchOrientation, long)
*/
@Override
public TRowSet getNextRowSet(FetchOrientation orientation, long maxRows) throws HiveSQLException {
assertState(OperationState.FINISHED);
validateDefaultFetchOrientation(orientation);
if (orientation.equals(FetchOrientation.FETCH_FIRST)) {
rowSet.setStartOffset(0);
}
return rowSet.extractSubset((int)maxRows).toTRowSet();
}
}
|
GetTableTypesOperation
|
java
|
apache__camel
|
components/camel-kafka/src/main/java/org/apache/camel/component/kafka/consumer/AsyncCommitManager.java
|
{
"start": 1323,
"end": 4131
}
|
class ____ extends AbstractCommitManager {
private static final Logger LOG = LoggerFactory.getLogger(AsyncCommitManager.class);
private final Consumer<?, ?> consumer;
private final OffsetCache offsetCache = new OffsetCache();
private final StateRepository<String, String> offsetRepository;
public AsyncCommitManager(Consumer<?, ?> consumer, KafkaConsumer kafkaConsumer, String threadId, String printableTopic) {
super(consumer, kafkaConsumer, threadId, printableTopic);
this.consumer = consumer;
offsetRepository = configuration.getOffsetRepository();
}
@Override
public void commit() {
if (kafkaConsumer.getEndpoint().getConfiguration().isAutoCommitEnable()) {
LOG.info("Auto commitAsync {} from {}", threadId, printableTopic);
consumer.commitAsync();
}
}
@Override
public void commit(TopicPartition partition) {
Long offset = offsetCache.getOffset(partition);
if (offset == null) {
return;
}
commitAsync(consumer, partition, offset);
}
private void commitAsync(Consumer<?, ?> consumer, TopicPartition partition, long partitionLastOffset) {
if (LOG.isDebugEnabled()) {
LOG.debug("Auto commitAsync on stop {} from topic {}", threadId, partition.topic());
}
final Map<TopicPartition, OffsetAndMetadata> topicPartitionOffsetAndMetadataMap
= Collections.singletonMap(partition, new OffsetAndMetadata(partitionLastOffset + 1));
consumer.commitAsync(topicPartitionOffsetAndMetadataMap, this::postCommitCallback);
}
@Override
public KafkaManualCommit getManualCommit(
Exchange exchange, TopicPartition partition, ConsumerRecord<Object, Object> consumerRecord) {
KafkaManualCommitFactory manualCommitFactory = kafkaConsumer.getEndpoint().getKafkaManualCommitFactory();
if (manualCommitFactory == null) {
manualCommitFactory = new DefaultKafkaManualAsyncCommitFactory();
}
return getManualCommit(exchange, partition, consumerRecord, manualCommitFactory);
}
@Override
public void recordOffset(TopicPartition partition, long partitionLastOffset) {
offsetCache.recordOffset(partition, partitionLastOffset);
}
private void postCommitCallback(Map<TopicPartition, OffsetAndMetadata> committed, Exception exception) {
if (exception == null) {
if (offsetRepository != null) {
for (var entry : committed.entrySet()) {
saveStateToOffsetRepository(entry.getKey(), entry.getValue().offset(), offsetRepository);
}
}
}
offsetCache.removeCommittedEntries(committed, exception);
}
}
|
AsyncCommitManager
|
java
|
apache__camel
|
components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/AgentConfiguration.java
|
{
"start": 5550,
"end": 5647
}
|
class ____.
*
* @param inputGuardrailClasses comma-separated list of fully qualified
|
names
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineImageViewer/ImageLoader.java
|
{
"start": 1656,
"end": 2372
}
|
interface ____ {
/**
* @param in DataInputStream pointing to an Hadoop FSImage file
* @param v Visit to apply to the FSImage file
* @param enumerateBlocks Should visitor visit each of the file blocks?
*/
public void loadImage(DataInputStream in, ImageVisitor v,
boolean enumerateBlocks) throws IOException;
/**
* Can this processor handle the specified version of FSImage file?
*
* @param version FSImage version file
* @return True if this instance can process the file
*/
public boolean canLoadVersion(int version);
/**
* Factory for obtaining version of image loader that can read
* a particular image format.
*/
@InterfaceAudience.Private
public
|
ImageLoader
|
java
|
apache__flink
|
flink-tests/src/test/java/org/apache/flink/test/state/StateHandleSerializationTest.java
|
{
"start": 1862,
"end": 3003
}
|
interface ____ must have a serial version UID
if (!clazz.isInterface()) {
assertFalse(
"Anonymous state handle classes have problematic serialization behavior: "
+ clazz,
clazz.isAnonymousClass());
try {
Field versionUidField = clazz.getDeclaredField("serialVersionUID");
// check conditions first via "if" to prevent always constructing expensive error
// messages
if (!(Modifier.isPrivate(versionUidField.getModifiers())
&& Modifier.isStatic(versionUidField.getModifiers())
&& Modifier.isFinal(versionUidField.getModifiers()))) {
fail(clazz.getName() + " - serialVersionUID is not 'private static final'");
}
} catch (NoSuchFieldException e) {
fail(
"State handle implementation '"
+ clazz.getName()
+ "' is missing the serialVersionUID");
}
}
}
}
|
types
|
java
|
quarkusio__quarkus
|
extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/typesafe/InterfaceValidationSuccessTest.java
|
{
"start": 2456,
"end": 2515
}
|
interface ____ extends NumericWrapper {
}
public
|
Count
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/array/PrimitiveArrayComparatorTestBase.java
|
{
"start": 1201,
"end": 1737
}
|
class ____<T> extends ComparatorTestBase<T> {
private final PrimitiveArrayTypeInfo<T> info;
public PrimitiveArrayComparatorTestBase(PrimitiveArrayTypeInfo<T> info) {
this.info = info;
}
@Override
protected TypeComparator<T> createComparator(boolean ascending) {
return info.createComparator(ascending, null).duplicate();
}
@Override
protected TypeSerializer<T> createSerializer() {
return info.createSerializer((SerializerConfigImpl) null);
}
}
|
PrimitiveArrayComparatorTestBase
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnMissingFilterBeanTests.java
|
{
"start": 6010,
"end": 6207
}
|
class ____ implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
}
}
}
|
OtherFilter
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/main/java/io/quarkus/resteasy/reactive/server/deployment/ResteasyReactiveScanningProcessor.java
|
{
"start": 4837,
"end": 7420
}
|
class ____ {
private static final DotName EXCEPTION = DotName.createSimple(Exception.class);
private static final DotName RUNTIME_EXCEPTION = DotName.createSimple(RuntimeException.class);
public static final Set<DotName> CONDITIONAL_BEAN_ANNOTATIONS;
static {
CONDITIONAL_BEAN_ANNOTATIONS = new HashSet<>(BuildTimeEnabledProcessor.BUILD_TIME_ENABLED_BEAN_ANNOTATIONS);
CONDITIONAL_BEAN_ANNOTATIONS.addAll(LookupConditionsProcessor.LOOKUP_BEAN_ANNOTATIONS);
}
@BuildStep
public MethodScannerBuildItem asyncSupport() {
return new MethodScannerBuildItem(new AsyncReturnTypeScanner());
}
@BuildStep
public MethodScannerBuildItem cacheControlSupport() {
return new MethodScannerBuildItem(new CacheControlScanner());
}
@BuildStep
public MethodScannerBuildItem compressionSupport(VertxHttpBuildTimeConfig httpBuildTimeConfig) {
return new MethodScannerBuildItem(new CompressionScanner(httpBuildTimeConfig));
}
@BuildStep
public ResourceInterceptorsContributorBuildItem scanForInterceptors(CombinedIndexBuildItem combinedIndexBuildItem,
ApplicationResultBuildItem applicationResultBuildItem) {
return new ResourceInterceptorsContributorBuildItem(new Consumer<ResourceInterceptors>() {
@Override
public void accept(ResourceInterceptors interceptors) {
ResteasyReactiveInterceptorScanner.scanForContainerRequestFilters(interceptors,
combinedIndexBuildItem.getIndex(),
applicationResultBuildItem.getResult());
}
});
}
@BuildStep
public List<UnwrappedExceptionBuildItem> defaultUnwrappedExceptions() {
return List.of(new UnwrappedExceptionBuildItem(ArcUndeclaredThrowableException.class),
new UnwrappedExceptionBuildItem(RollbackException.class));
}
@BuildStep
public void applicationSpecificUnwrappedExceptions(CombinedIndexBuildItem combinedIndexBuildItem,
BuildProducer<UnwrappedExceptionBuildItem> producer) {
IndexView index = combinedIndexBuildItem.getIndex();
for (AnnotationInstance instance : index.getAnnotations(UnwrapException.class)) {
AnnotationValue value = instance.value();
AnnotationValue strategyValue = instance.value("strategy");
ExceptionUnwrapStrategy strategy = toExceptionUnwrapStrategy(strategyValue);
if (value == null) {
// in this case we need to use the
|
ResteasyReactiveScanningProcessor
|
java
|
apache__camel
|
components/camel-zipfile/src/main/java/org/apache/camel/dataformat/zipfile/ZipInputStreamWrapper.java
|
{
"start": 942,
"end": 1374
}
|
class ____ extends BufferedInputStream {
ZipInputStreamWrapper(InputStream in, int size) {
super(in, size);
}
ZipInputStreamWrapper(InputStream in) {
super(in);
}
@Override
public void close() throws IOException {
InputStream input = in;
try {
in = null;
super.close();
} finally {
in = input;
}
}
}
|
ZipInputStreamWrapper
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/AMRMClient.java
|
{
"start": 2587,
"end": 4912
}
|
class ____<T extends AMRMClient.ContainerRequest> extends
AbstractService {
private static final Logger LOG =
LoggerFactory.getLogger(AMRMClient.class);
private TimelineV2Client timelineV2Client;
/**
* Create a new instance of AMRMClient.
* For usage:
* <pre>
* {@code
* AMRMClient.<T>createAMRMClientContainerRequest()
* }</pre>
* @return the newly create AMRMClient instance.
*/
@Public
public static <T extends ContainerRequest> AMRMClient<T> createAMRMClient() {
AMRMClient<T> client = new AMRMClientImpl<T>();
return client;
}
private NMTokenCache nmTokenCache;
@Private
protected AMRMClient(String name) {
super(name);
nmTokenCache = NMTokenCache.getSingleton();
}
/**
* Object to represent a single container request for resources. Scheduler
* documentation should be consulted for the specifics of how the parameters
* are honored.
*
* By default, YARN schedulers try to allocate containers at the requested
* locations but they may relax the constraints in order to expedite meeting
* allocations limits. They first relax the constraint to the same rack as the
* requested node and then to anywhere in the cluster. The relaxLocality flag
* may be used to disable locality relaxation and request containers at only
* specific locations. The following conditions apply.
* <ul>
* <li>Within a priority, all container requests must have the same value for
* locality relaxation. Either enabled or disabled.</li>
* <li>If locality relaxation is disabled, then across requests, locations at
* different network levels may not be specified. E.g. its invalid to make a
* request for a specific node and another request for a specific rack.</li>
* <li>If locality relaxation is disabled, then only within the same request,
* a node and its rack may be specified together. This allows for a specific
* rack with a preference for a specific node within that rack.</li>
* <li></li>
* </ul>
* To re-enable locality relaxation at a given priority, all pending requests
* with locality relaxation disabled must be first removed. Then they can be
* added back with locality relaxation enabled.
*
* All getters return immutable values.
*/
public static
|
AMRMClient
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ThrowsUncheckedExceptionTest.java
|
{
"start": 1526,
"end": 3008
}
|
class ____ {
// BUG: Diagnostic contains: 'public void doSomething() {'
public void doSomething() throws IllegalArgumentException {
throw new IllegalArgumentException("thrown");
}
// BUG: Diagnostic contains: 'public void doSomethingElse() {'
public void doSomethingElse() throws RuntimeException, NullPointerException {
throw new NullPointerException("thrown");
}
// BUG: Diagnostic contains: Unchecked exceptions do not need to be declared
public void doMore() throws RuntimeException, IOException {
throw new IllegalArgumentException("thrown");
}
// BUG: Diagnostic contains: Unchecked exceptions do not need to be declared
public void doEverything() throws RuntimeException, IOException, IndexOutOfBoundsException {
throw new IllegalArgumentException("thrown");
}
// BUG: Diagnostic contains: 'public void doBetter() {'
public void doBetter() throws RuntimeException, AssertionError {
throw new RuntimeException("thrown");
}
}\
""")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"ThrowsUncheckedExceptionNegativeCases.java",
"""
package com.google.errorprone.bugpatterns.testdata;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author yulissa@google.com (Yulissa Arroyo-Paredes)
*/
public
|
ThrowsUncheckedExceptionPositiveCases
|
java
|
quarkusio__quarkus
|
extensions/panache/hibernate-orm-panache-kotlin/deployment/src/main/java/io/quarkus/hibernate/orm/panache/kotlin/deployment/KotlinPanacheResourceProcessor.java
|
{
"start": 9573,
"end": 10712
}
|
class
____.produce(
ReflectiveClassBuildItem.builder(parameterType.name().toString()).methods().fields().build());
}
}
private void processCompanions(CombinedIndexBuildItem index,
BuildProducer<BytecodeTransformerBuildItem> transformers,
BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
KotlinPanacheCompanionEnhancer enhancer,
ByteCodeType baseType,
ByteCodeType type) {
Set<Type> typeParameters = new HashSet<>();
for (ClassInfo classInfo : index.getIndex().getAllKnownImplementors(baseType.dotName())) {
if (classInfo.name().equals(type.dotName())) {
continue;
}
transformers.produce(new BytecodeTransformerBuildItem(classInfo.name().toString(), enhancer));
typeParameters.addAll(resolveTypeParameters(classInfo.name(), baseType.dotName(), index.getIndex()));
}
for (Type parameterType : typeParameters) {
// Register for reflection the type parameters of the repository: this should be the entity
|
reflectiveClass
|
java
|
apache__logging-log4j2
|
log4j-core/src/main/java/org/apache/logging/log4j/core/lookup/StrSubstitutor.java
|
{
"start": 51912,
"end": 65613
}
|
class ____ not need to call this method. This method is
* called automatically by the substitution process.
* </p>
* <p>
* Writers of subclasses can override this method if they need to alter
* how each substitution occurs. The method is passed the variable's name
* and must return the corresponding value. This implementation uses the
* {@link #getVariableResolver()} with the variable's name as the key.
* </p>
*
* @param event The LogEvent, if there is one.
* @param variableName the name of the variable, not null
* @param buf the buffer where the substitution is occurring, not null
* @param startPos the start position of the variable including the prefix, valid
* @param endPos the end position of the variable including the suffix, valid
* @return the variable's value or <b>null</b> if the variable is unknown
*/
protected LookupResult resolveVariable(
final LogEvent event,
final String variableName,
final StringBuilder buf,
final int startPos,
final int endPos) {
final StrLookup resolver = getVariableResolver();
if (resolver == null) {
return null;
}
try {
return resolver.evaluate(event, variableName);
} catch (Throwable t) {
StatusLogger.getLogger().error("Resolver failed to lookup {}", variableName, t);
return null;
}
}
// Escape
// -----------------------------------------------------------------------
/**
* Returns the escape character.
*
* @return the character used for escaping variable references
*/
public char getEscapeChar() {
return this.escapeChar;
}
/**
* Sets the escape character.
* If this character is placed before a variable reference in the source
* text, this variable will be ignored.
*
* @param escapeCharacter the escape character (0 for disabling escaping)
*/
public void setEscapeChar(final char escapeCharacter) {
this.escapeChar = escapeCharacter;
}
// Prefix
// -----------------------------------------------------------------------
/**
* Gets the variable prefix matcher currently in use.
* <p>
* The variable prefix is the character or characters that identify the
* start of a variable. This prefix is expressed in terms of a matcher
* allowing advanced prefix matches.
* </p>
*
* @return the prefix matcher in use
*/
public StrMatcher getVariablePrefixMatcher() {
return prefixMatcher;
}
/**
* Sets the variable prefix matcher currently in use.
* <p>
* The variable prefix is the character or characters that identify the
* start of a variable. This prefix is expressed in terms of a matcher
* allowing advanced prefix matches.
* </p>
*
* @param prefixMatcher the prefix matcher to use, must not be null
* @return this, to enable chaining
* @throws IllegalArgumentException if the prefix matcher is null
*/
public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
if (prefixMatcher == null) {
throw new IllegalArgumentException("Parameter prefixMatcher must not be null!");
}
this.prefixMatcher = prefixMatcher;
return this;
}
/**
* Sets the variable prefix to use.
* <p>
* The variable prefix is the character or characters that identify the
* start of a variable. This method allows a single character prefix to
* be easily set.
* </p>
*
* @param prefix the prefix character to use
* @return this, to enable chaining
*/
public StrSubstitutor setVariablePrefix(final char prefix) {
return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
}
/**
* Sets the variable prefix to use.
* <p>
* The variable prefix is the character or characters that identify the
* start of a variable. This method allows a string prefix to be easily set.
* </p>
*
* @param prefix the prefix for variables, not null
* @return this, to enable chaining
* @throws IllegalArgumentException if the prefix is null
*/
public StrSubstitutor setVariablePrefix(final String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("Variable prefix must not be null!");
}
return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
}
// Suffix
// -----------------------------------------------------------------------
/**
* Gets the variable suffix matcher currently in use.
* <p>
* The variable suffix is the character or characters that identify the
* end of a variable. This suffix is expressed in terms of a matcher
* allowing advanced suffix matches.
* </p>
*
* @return the suffix matcher in use
*/
public StrMatcher getVariableSuffixMatcher() {
return suffixMatcher;
}
/**
* Sets the variable suffix matcher currently in use.
* <p>
* The variable suffix is the character or characters that identify the
* end of a variable. This suffix is expressed in terms of a matcher
* allowing advanced suffix matches.
* </p>
*
* @param suffixMatcher the suffix matcher to use, must not be null
* @return this, to enable chaining
* @throws IllegalArgumentException if the suffix matcher is null
*/
public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
if (suffixMatcher == null) {
throw new IllegalArgumentException("Parameter suffixMatcher must not be null!");
}
this.suffixMatcher = suffixMatcher;
return this;
}
/**
* Sets the variable suffix to use.
* <p>
* The variable suffix is the character or characters that identify the
* end of a variable. This method allows a single character suffix to
* be easily set.
* </p>
*
* @param suffix the suffix character to use
* @return this, to enable chaining
*/
public StrSubstitutor setVariableSuffix(final char suffix) {
return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
}
/**
* Sets the variable suffix to use.
* <p>
* The variable suffix is the character or characters that identify the
* end of a variable. This method allows a string suffix to be easily set.
* </p>
*
* @param suffix the suffix for variables, not null
* @return this, to enable chaining
* @throws IllegalArgumentException if the suffix is null
*/
public StrSubstitutor setVariableSuffix(final String suffix) {
if (suffix == null) {
throw new IllegalArgumentException("Variable suffix must not be null!");
}
return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
}
// Variable Default Value Delimiter
// -----------------------------------------------------------------------
/**
* Gets the variable default value delimiter matcher currently in use.
* <p>
* The variable default value delimiter is the character or characters that delimit the
* variable name and the variable default value. This delimiter is expressed in terms of a matcher
* allowing advanced variable default value delimiter matches.
* </p>
* <p>
* If it returns null, then the variable default value resolution is disabled.
* </p>
*
* @return the variable default value delimiter matcher in use, may be null
*/
public StrMatcher getValueDelimiterMatcher() {
return valueDelimiterMatcher;
}
/**
* Sets the variable default value delimiter matcher to use.
* <p>
* The variable default value delimiter is the character or characters that delimit the
* variable name and the variable default value. This delimiter is expressed in terms of a matcher
* allowing advanced variable default value delimiter matches.
* </p>
* <p>
* If the <code>valueDelimiterMatcher</code> is null, then the variable default value resolution
* becomes disabled.
* </p>
*
* @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
* @return this, to enable chaining
*/
public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
this.valueDelimiterMatcher = valueDelimiterMatcher;
return this;
}
/**
* Sets the variable default value delimiter to use.
* <p>
* The variable default value delimiter is the character or characters that delimit the
* variable name and the variable default value. This method allows a single character
* variable default value delimiter to be easily set.
* </p>
*
* @param valueDelimiter the variable default value delimiter character to use
* @return this, to enable chaining
*/
public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
}
/**
* Sets the variable default value delimiter to use.
* <p>
* The variable default value delimiter is the character or characters that delimit the
* variable name and the variable default value. This method allows a string
* variable default value delimiter to be easily set.
* </p>
* <p>
* If the <code>valueDelimiter</code> is null or empty string, then the variable default
* value resolution becomes disabled.
* </p>
*
* @param valueDelimiter the variable default value delimiter string to use, may be null or empty
* @return this, to enable chaining
*/
public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
if (Strings.isEmpty(valueDelimiter)) {
setValueDelimiterMatcher(null);
return this;
}
final String escapeValue = valueDelimiter.substring(0, valueDelimiter.length() - 1) + "\\"
+ valueDelimiter.substring(valueDelimiter.length() - 1);
valueEscapeDelimiterMatcher = StrMatcher.stringMatcher(escapeValue);
return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
}
// Resolver
// -----------------------------------------------------------------------
/**
* Gets the VariableResolver that is used to lookup variables.
*
* @return the VariableResolver
*/
public StrLookup getVariableResolver() {
return this.variableResolver;
}
/**
* Sets the VariableResolver that is used to lookup variables.
*
* @param variableResolver the VariableResolver
*/
public void setVariableResolver(final StrLookup variableResolver) {
if (variableResolver instanceof ConfigurationAware && this.configuration != null) {
((ConfigurationAware) variableResolver).setConfiguration(this.configuration);
}
this.variableResolver = variableResolver;
}
// Substitution support in variable names
// -----------------------------------------------------------------------
/**
* Returns a flag whether substitution is done in variable names.
*
* @return the substitution in variable names flag
*/
public boolean isEnableSubstitutionInVariables() {
return enableSubstitutionInVariables;
}
/**
* Sets a flag whether substitution is done in variable names. If set to
* <b>true</b>, the names of variables can contain other variables which are
* processed first before the original variable is evaluated, e.g.
* <code>${jre-${java.version}}</code>. The default value is <b>true</b>.
*
* @param enableSubstitutionInVariables the new value of the flag
*/
public void setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) {
this.enableSubstitutionInVariables = enableSubstitutionInVariables;
}
private char[] getChars(final StringBuilder sb) {
final char[] chars = new char[sb.length()];
sb.getChars(0, sb.length(), chars, 0);
return chars;
}
/**
* Appends a iterable placing separators between each value, but
* not before the first or after the last.
* Appending a null iterable will have no effect..
*
* @param sb StringBuilder that contains the String being constructed.
* @param iterable the iterable to append
* @param separator the separator to use, null means no separator
*/
public void appendWithSeparators(final StringBuilder sb, final Iterable<?> iterable, String separator) {
if (iterable != null) {
separator = separator == null ? Strings.EMPTY : separator;
final Iterator<?> it = iterable.iterator();
while (it.hasNext()) {
sb.append(it.next());
if (it.hasNext()) {
sb.append(separator);
}
}
}
}
@Override
public String toString() {
return "StrSubstitutor(" + variableResolver.toString() + ')';
}
@Override
public void setConfiguration(final Configuration configuration) {
this.configuration = configuration;
if (this.variableResolver instanceof ConfigurationAware) {
((ConfigurationAware) this.variableResolver).setConfiguration(this.configuration);
}
}
}
|
do
|
java
|
apache__flink
|
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/lineage/TypeDatasetFacetProvider.java
|
{
"start": 1019,
"end": 1145
}
|
interface ____ {
/**
* Returns a type dataset facet or `Optional.empty` in case an implementing
|
TypeDatasetFacetProvider
|
java
|
google__guava
|
android/guava-tests/test/com/google/common/reflect/ClassPathTest.java
|
{
"start": 2038,
"end": 18279
}
|
class ____ extends TestCase {
private static final Logger log = Logger.getLogger(ClassPathTest.class.getName());
private static final File FILE = new File(".");
public void testEquals() {
new EqualsTester()
.addEqualityGroup(classInfo(ClassPathTest.class), classInfo(ClassPathTest.class))
.addEqualityGroup(classInfo(Test.class), classInfo(Test.class, getClass().getClassLoader()))
.addEqualityGroup(
new ResourceInfo(FILE, "a/b/c.txt", getClass().getClassLoader()),
new ResourceInfo(FILE, "a/b/c.txt", getClass().getClassLoader()))
.addEqualityGroup(new ResourceInfo(FILE, "x.txt", getClass().getClassLoader()))
.testEquals();
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_emptyURLClassLoader_noParent() {
assertThat(ClassPath.getClassPathEntries(new URLClassLoader(new URL[0], null)).keySet())
.isEmpty();
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_urlClassLoader_noParent() throws Exception {
URL url1 = new URL("file:/a");
URL url2 = new URL("file:/b");
URLClassLoader classloader = new URLClassLoader(new URL[] {url1, url2}, null);
assertThat(ClassPath.getClassPathEntries(classloader))
.containsExactly(new File("/a"), classloader, new File("/b"), classloader);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_urlClassLoader_withParent() throws Exception {
URL url1 = new URL("file:/a");
URL url2 = new URL("file:/b");
URLClassLoader parent = new URLClassLoader(new URL[] {url1}, null);
URLClassLoader child = new URLClassLoader(new URL[] {url2}, parent) {};
assertThat(ClassPath.getClassPathEntries(child))
.containsExactly(new File("/a"), parent, new File("/b"), child)
.inOrder();
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_duplicateUri_parentWins() throws Exception {
URL url = new URL("file:/a");
URLClassLoader parent = new URLClassLoader(new URL[] {url}, null);
URLClassLoader child = new URLClassLoader(new URL[] {url}, parent) {};
assertThat(ClassPath.getClassPathEntries(child)).containsExactly(new File("/a"), parent);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_noParent() {
assertThat(ClassPath.getClassPathEntries(new ClassLoader(null) {})).isEmpty();
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withParent() throws Exception {
URL url = new URL("file:/a");
URLClassLoader parent = new URLClassLoader(new URL[] {url}, null);
assertThat(ClassPath.getClassPathEntries(new ClassLoader(parent) {}))
.containsExactly(new File("/a"), parent);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withParentAndGrandParent() throws Exception {
URL url1 = new URL("file:/a");
URL url2 = new URL("file:/b");
URLClassLoader grandParent = new URLClassLoader(new URL[] {url1}, null);
URLClassLoader parent = new URLClassLoader(new URL[] {url2}, grandParent);
assertThat(ClassPath.getClassPathEntries(new ClassLoader(parent) {}))
.containsExactly(new File("/a"), grandParent, new File("/b"), parent);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
public void testClassPathEntries_notURLClassLoader_withGrandParent() throws Exception {
URL url = new URL("file:/a");
URLClassLoader grandParent = new URLClassLoader(new URL[] {url}, null);
ClassLoader parent = new ClassLoader(grandParent) {};
assertThat(ClassPath.getClassPathEntries(new ClassLoader(parent) {}))
.containsExactly(new File("/a"), grandParent);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testClassPathEntries_urlClassLoader_pathWithSpace() throws Exception {
URL url = new URL("file:///c:/Documents and Settings/");
URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
assertThat(ClassPath.getClassPathEntries(classloader))
.containsExactly(new File("/c:/Documents and Settings/"), classloader);
}
@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testClassPathEntries_urlClassLoader_pathWithEscapedSpace() throws Exception {
URL url = new URL("file:///c:/Documents%20and%20Settings/");
URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
assertThat(ClassPath.getClassPathEntries(classloader))
.containsExactly(new File("/c:/Documents and Settings/"), classloader);
}
// https://github.com/google/guava/issues/2152
public void testToFile() throws Exception {
assertThat(ClassPath.toFile(new URL("file:///c:/Documents%20and%20Settings/")))
.isEqualTo(new File("/c:/Documents and Settings/"));
assertThat(ClassPath.toFile(new URL("file:///c:/Documents ~ Settings, or not/11-12 12:05")))
.isEqualTo(new File("/c:/Documents ~ Settings, or not/11-12 12:05"));
}
// https://github.com/google/guava/issues/2152
@AndroidIncompatible // works in newer Android versions but fails at the version we test with
public void testToFile_androidIncompatible() throws Exception {
assertThat(ClassPath.toFile(new URL("file:///c:\\Documents ~ Settings, or not\\11-12 12:05")))
.isEqualTo(new File("/c:\\Documents ~ Settings, or not\\11-12 12:05"));
assertThat(ClassPath.toFile(new URL("file:///C:\\Program Files\\Apache Software Foundation")))
.isEqualTo(new File("/C:\\Program Files\\Apache Software Foundation/"));
assertThat(ClassPath.toFile(new URL("file:///C:\\\u20320 \u22909"))) // Chinese Ni Hao
.isEqualTo(new File("/C:\\\u20320 \u22909"));
}
@AndroidIncompatible // Android forbids null parent ClassLoader
// https://github.com/google/guava/issues/2152
public void testJarFileWithSpaces() throws Exception {
URL url = makeJarUrlWithName("To test unescaped spaces in jar file name.jar");
URLClassLoader classloader = new URLClassLoader(new URL[] {url}, null);
assertThat(ClassPath.from(classloader).getTopLevelClasses()).isNotEmpty();
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScan_classPathCycle() throws IOException {
File jarFile = File.createTempFile("with_circular_class_path", ".jar");
try {
writeSelfReferencingJarFile(jarFile, "test.txt");
assertThat(
new ClassPath.LocationInfo(jarFile, ClassPathTest.class.getClassLoader())
.scanResources())
.hasSize(1);
} finally {
jarFile.delete();
}
}
public void testScanFromFile_fileNotExists() throws IOException {
ClassLoader classLoader = ClassPathTest.class.getClassLoader();
assertThat(
new ClassPath.LocationInfo(new File("no/such/file/anywhere"), classLoader)
.scanResources())
.isEmpty();
}
@AndroidIncompatible // ClassPath is documented as not supporting Android
public void testScanFromFile_notJarFile() throws IOException {
ClassLoader classLoader = ClassPathTest.class.getClassLoader();
File notJar = File.createTempFile("not_a_jar", "txt");
try {
assertThat(new ClassPath.LocationInfo(notJar, classLoader).scanResources()).isEmpty();
} finally {
notJar.delete();
}
}
public void testGetClassPathEntry() throws MalformedURLException, URISyntaxException {
if (isWindows()) {
return; // TODO: b/136041958 - We need to account for drive letters in the path.
}
assertEquals(
new File("/usr/test/dep.jar").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "file:/usr/test/dep.jar")
.toURI());
assertEquals(
new File("/home/build/a.jar").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "a.jar").toURI());
assertEquals(
new File("/home/build/x/y/z").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "x/y/z").toURI());
assertEquals(
new File("/home/build/x/y/z.jar").toURI(),
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "x/y/z.jar").toURI());
assertEquals(
"/home/build/x y.jar",
ClassPath.getClassPathEntry(new File("/home/build/outer.jar"), "x y.jar").getFile());
}
public void testGetClassPathFromManifest_nullManifest() {
assertThat(ClassPath.getClassPathFromManifest(new File("some.jar"), null)).isEmpty();
}
public void testGetClassPathFromManifest_noClassPath() throws IOException {
File jarFile = new File("base.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest(""))).isEmpty();
}
public void testGetClassPathFromManifest_emptyClassPath() throws IOException {
File jarFile = new File("base.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifestClasspath(""))).isEmpty();
}
public void testGetClassPathFromManifest_badClassPath() throws IOException {
File jarFile = new File("base.jar");
Manifest manifest = manifestClasspath("nosuchscheme:an_invalid^path");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest)).isEmpty();
}
public void testGetClassPathFromManifest_pathWithStrangeCharacter() throws IOException {
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:the^file.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/the^file.jar"));
}
public void testGetClassPathFromManifest_relativeDirectory() throws IOException {
File jarFile = new File("base/some.jar");
// with/relative/directory is the Class-Path value in the mf file.
Manifest manifest = manifestClasspath("with/relative/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/with/relative/dir"));
}
public void testGetClassPathFromManifest_relativeJar() throws IOException {
File jarFile = new File("base/some.jar");
// with/relative/directory is the Class-Path value in the mf file.
Manifest manifest = manifestClasspath("with/relative.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/with/relative.jar"));
}
public void testGetClassPathFromManifest_jarInCurrentDirectory() throws IOException {
File jarFile = new File("base/some.jar");
// with/relative/directory is the Class-Path value in the mf file.
Manifest manifest = manifestClasspath("current.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/current.jar"));
}
public void testGetClassPathFromManifest_absoluteDirectory() throws IOException {
if (isWindows()) {
return; // TODO: b/136041958 - We need to account for drive letters in the path.
}
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("/with/absolute/dir"));
}
public void testGetClassPathFromManifest_absoluteJar() throws IOException {
if (isWindows()) {
return; // TODO: b/136041958 - We need to account for drive letters in the path.
}
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("/with/absolute.jar"));
}
public void testGetClassPathFromManifest_multiplePaths() throws IOException {
if (isWindows()) {
return; // TODO: b/136041958 - We need to account for drive letters in the path.
}
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("file:/with/absolute.jar relative.jar relative/dir");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(
fullpath("/with/absolute.jar"),
fullpath("base/relative.jar"),
fullpath("base/relative/dir"))
.inOrder();
}
public void testGetClassPathFromManifest_leadingBlanks() throws IOException {
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath(" relative.jar");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/relative.jar"));
}
public void testGetClassPathFromManifest_trailingBlanks() throws IOException {
File jarFile = new File("base/some.jar");
Manifest manifest = manifestClasspath("relative.jar ");
assertThat(ClassPath.getClassPathFromManifest(jarFile, manifest))
.containsExactly(fullpath("base/relative.jar"));
}
public void testGetClassName() {
assertEquals("abc.d.Abc", ClassPath.getClassName("abc/d/Abc.class"));
}
public void testResourceInfo_of() {
assertEquals(ClassInfo.class, resourceInfo(ClassPathTest.class).getClass());
assertEquals(ClassInfo.class, resourceInfo(ClassPath.class).getClass());
assertEquals(ClassInfo.class, resourceInfo(Nested.class).getClass());
}
public void testGetSimpleName() {
ClassLoader classLoader = getClass().getClassLoader();
assertEquals("Foo", new ClassInfo(FILE, "Foo.class", classLoader).getSimpleName());
assertEquals("Foo", new ClassInfo(FILE, "a/b/Foo.class", classLoader).getSimpleName());
assertEquals("Foo", new ClassInfo(FILE, "a/b/Bar$Foo.class", classLoader).getSimpleName());
assertEquals("", new ClassInfo(FILE, "a/b/Bar$1.class", classLoader).getSimpleName());
assertEquals("Foo", new ClassInfo(FILE, "a/b/Bar$Foo.class", classLoader).getSimpleName());
assertEquals("", new ClassInfo(FILE, "a/b/Bar$1.class", classLoader).getSimpleName());
assertEquals("Local", new ClassInfo(FILE, "a/b/Bar$1Local.class", classLoader).getSimpleName());
}
public void testGetPackageName() {
assertEquals(
"", new ClassInfo(FILE, "Foo.class", getClass().getClassLoader()).getPackageName());
assertEquals(
"a.b", new ClassInfo(FILE, "a/b/Foo.class", getClass().getClassLoader()).getPackageName());
}
// Test that ResourceInfo.urls() returns identical content to ClassLoader.getResources()
@AndroidIncompatible
public void testGetClassPathUrls() throws Exception {
if (isWindows()) {
return; // TODO: b/136041958 - We need to account for drive letters in the path.
}
String oldPathSeparator = PATH_SEPARATOR.value();
String oldClassPath = JAVA_CLASS_PATH.value();
System.setProperty(PATH_SEPARATOR.key(), ":");
System.setProperty(
JAVA_CLASS_PATH.key(),
Joiner.on(":")
.join(
"relative/path/to/some.jar",
"/absolute/path/to/some.jar",
"relative/path/to/class/root",
"/absolute/path/to/class/root"));
try {
ImmutableList<URL> urls = ClassPath.parseJavaClassPath();
assertThat(urls.get(0).getProtocol()).isEqualTo("file");
assertThat(urls.get(0).getAuthority()).isNull();
assertThat(urls.get(0).getPath()).endsWith("/relative/path/to/some.jar");
assertThat(urls.get(1)).isEqualTo(new URL("file:///absolute/path/to/some.jar"));
assertThat(urls.get(2).getProtocol()).isEqualTo("file");
assertThat(urls.get(2).getAuthority()).isNull();
assertThat(urls.get(2).getPath()).endsWith("/relative/path/to/class/root");
assertThat(urls.get(3)).isEqualTo(new URL("file:///absolute/path/to/class/root"));
assertThat(urls).hasSize(4);
} finally {
System.setProperty(PATH_SEPARATOR.key(), oldPathSeparator);
System.setProperty(JAVA_CLASS_PATH.key(), oldClassPath);
}
}
private static
|
ClassPathTest
|
java
|
hibernate__hibernate-orm
|
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/hashcode/SetHashcodeChangeTest.java
|
{
"start": 5012,
"end": 6162
}
|
class ____ {
@Id
@GeneratedValue
private Integer id;
private String title;
@ManyToOne(fetch = FetchType.LAZY)
@JoinTable(name = "author_book",
joinColumns = @JoinColumn(name = "book_id"), inverseJoinColumns = @JoinColumn(name="author_id",nullable = false))
private Author author;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public int hashCode() {
return Objects.hash( title );
}
@Override
public boolean equals(Object object) {
if ( this == object ) {
return true;
}
if ( object == null || getClass() != object.getClass() ) {
return false;
}
Book book = (Book) object;
return Objects.equals( title, book.title );
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author=" + author +
'}';
}
}
}
|
Book
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/InconsistentCapitalizationTest.java
|
{
"start": 942,
"end": 1604
}
|
class ____ {
private final CompilationTestHelper compilationHelper =
CompilationTestHelper.newInstance(InconsistentCapitalization.class, getClass());
private final BugCheckerRefactoringTestHelper refactoringHelper =
BugCheckerRefactoringTestHelper.newInstance(InconsistentCapitalization.class, getClass());
@Test
public void negativeCases() {
compilationHelper
.addSourceLines(
"InconsistentCapitalizationNegativeCases.java",
"""
package com.google.errorprone.bugpatterns.testdata;
/** Negative cases for {@link com.google.errorprone.bugpatterns.InconsistentCapitalizationTest}. */
public
|
InconsistentCapitalizationTest
|
java
|
apache__flink
|
flink-state-backends/flink-statebackend-rocksdb/src/test/java/org/apache/flink/state/rocksdb/RocksDBStateUploaderTest.java
|
{
"start": 13352,
"end": 14991
}
|
class ____
implements CheckpointStreamFactory {
private final CheckpointStreamFactory checkpointStreamFactory;
private final int streamTotalCount;
private final AtomicInteger streamCount;
private final IOException expectedException;
private LastFailingCheckpointStateOutputStreamFactory(
CheckpointStreamFactory checkpointStreamFactory,
int streamTotalCount,
IOException expectedException) {
this.checkpointStreamFactory = checkpointStreamFactory;
this.streamTotalCount = streamTotalCount;
this.expectedException = expectedException;
this.streamCount = new AtomicInteger();
}
@Override
public CheckpointStateOutputStream createCheckpointStateOutputStream(
CheckpointedStateScope scope) throws IOException {
if (streamCount.incrementAndGet() == streamTotalCount) {
return createFailingCheckpointStateOutputStream(expectedException);
}
return checkpointStreamFactory.createCheckpointStateOutputStream(scope);
}
@Override
public boolean canFastDuplicate(
StreamStateHandle stateHandle, CheckpointedStateScope scope) {
return false;
}
@Override
public List<StreamStateHandle> duplicate(
List<StreamStateHandle> stateHandles, CheckpointedStateScope scope)
throws IOException {
throw new UnsupportedOperationException();
}
}
}
|
LastFailingCheckpointStateOutputStreamFactory
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBooleanPropertyTests.java
|
{
"start": 8295,
"end": 8426
}
|
class ____ extends BeanConfiguration {
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnBooleanProperty
static
|
WithPrefix
|
java
|
apache__dubbo
|
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/AbstractRegistryCenterTestExecutionListener.java
|
{
"start": 1527,
"end": 3984
}
|
class ____ implements TestExecutionListener {
/**
* The registry center should start
* if we want to run the test cases in the given package.
*/
private static final Set<String> PACKAGE_NAME = new HashSet<>();
/**
* Use embedded zookeeper or not.
*/
private static boolean enableEmbeddedZookeeper;
static {
// dubbo-config module
PACKAGE_NAME.add("org.apache.dubbo.config");
// dubbo-test module
PACKAGE_NAME.add("org.apache.dubbo.test");
// dubbo-registry
PACKAGE_NAME.add("org.apache.dubbo.registry");
// dubbo-remoting-zookeeper
PACKAGE_NAME.add("org.apache.dubbo.remoting.zookeeper");
// dubbo-metadata-report-zookeeper
PACKAGE_NAME.add("org.apache.dubbo.metadata.store.zookeeper");
enableEmbeddedZookeeper =
Boolean.valueOf(SystemPropertyConfigUtils.getSystemProperty(ZOOKEEPER_CONFIG_ENABLE_EMBEDDED, "true"));
}
/**
* Checks if current {@link TestPlan} need registry center.
*/
public boolean needRegistryCenter(TestPlan testPlan) {
return testPlan.getRoots().stream()
.flatMap(testIdentifier -> testPlan.getChildren(testIdentifier).stream())
.filter(testIdentifier -> testIdentifier.getSource().isPresent())
.filter(testIdentifier -> supportEmbeddedZookeeper(testIdentifier))
.count()
> 0;
}
/**
* Checks if current {@link TestIdentifier} need registry center.
*/
public boolean needRegistryCenter(TestIdentifier testIdentifier) {
return supportEmbeddedZookeeper(testIdentifier);
}
/**
* Checks if the current {@link TestIdentifier} need embedded zookeeper.
*/
private boolean supportEmbeddedZookeeper(TestIdentifier testIdentifier) {
if (!enableEmbeddedZookeeper) {
return false;
}
TestSource testSource = testIdentifier.getSource().orElse(null);
if (testSource instanceof ClassSource) {
String packageName =
((ClassSource) testSource).getJavaClass().getPackage().getName();
for (String pkgName : PACKAGE_NAME) {
if (packageName.contains(pkgName)) {
return true;
}
}
}
return false;
}
}
|
AbstractRegistryCenterTestExecutionListener
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/test/java/org/apache/camel/builder/endpoint/FileDelayTest.java
|
{
"start": 1135,
"end": 2418
}
|
class ____ extends BaseEndpointDslTest {
private static final String TEST_DATA_DIR = BaseEndpointDslTest.generateUniquePath(BaseEndpointDslTest.class);
@Override
public void doPreSetup() {
deleteDirectory(TEST_DATA_DIR);
}
@Override
public void doPostSetup() {
template.sendBodyAndHeader("file://" + TEST_DATA_DIR, "Hello World", Exchange.FILE_NAME, "hello.txt");
template.sendBodyAndHeader("file://" + TEST_DATA_DIR, "Bye World", Exchange.FILE_NAME, "bye.txt");
}
@Test
public void testDelay() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceivedInAnyOrder("Hello World", "Bye World");
mock.message(1).arrives().between(1500, 3000).millis().afterPrevious();
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new EndpointRouteBuilder() {
public void configure() throws Exception {
from(file(TEST_DATA_DIR).delay(2).timeUnit(TimeUnit.SECONDS).delete(true).maxMessagesPerPoll(1))
.convertBodyTo(String.class)
.to(mock("result"));
}
};
}
}
|
FileDelayTest
|
java
|
apache__kafka
|
clients/src/main/java/org/apache/kafka/common/requests/LeaveGroupResponse.java
|
{
"start": 1988,
"end": 5997
}
|
class ____ extends AbstractResponse {
private final LeaveGroupResponseData data;
public LeaveGroupResponse(LeaveGroupResponseData data) {
super(ApiKeys.LEAVE_GROUP);
this.data = data;
}
public LeaveGroupResponse(LeaveGroupResponseData data, short version) {
super(ApiKeys.LEAVE_GROUP);
if (version >= 3) {
this.data = data;
} else if (data.errorCode() != Errors.NONE.code()) {
this.data = new LeaveGroupResponseData().setErrorCode(data.errorCode());
} else {
if (data.members().size() != 1) {
throw new UnsupportedVersionException("LeaveGroup response version " + version +
" can only contain one member, got " + data.members().size() + " members.");
}
this.data = new LeaveGroupResponseData().setErrorCode(data.members().get(0).errorCode());
}
}
public LeaveGroupResponse(List<MemberResponse> memberResponses,
Errors topLevelError,
final int throttleTimeMs,
final short version) {
super(ApiKeys.LEAVE_GROUP);
if (version <= 2) {
// Populate member level error.
final short errorCode = getError(topLevelError, memberResponses).code();
this.data = new LeaveGroupResponseData()
.setErrorCode(errorCode);
} else {
this.data = new LeaveGroupResponseData()
.setErrorCode(topLevelError.code())
.setMembers(memberResponses);
}
if (version >= 1) {
this.data.setThrottleTimeMs(throttleTimeMs);
}
}
@Override
public int throttleTimeMs() {
return data.throttleTimeMs();
}
@Override
public void maybeSetThrottleTimeMs(int throttleTimeMs) {
data.setThrottleTimeMs(throttleTimeMs);
}
public List<MemberResponse> memberResponses() {
return data.members();
}
public Errors error() {
return getError(Errors.forCode(data.errorCode()), data.members());
}
public Errors topLevelError() {
return Errors.forCode(data.errorCode());
}
private static Errors getError(Errors topLevelError, List<MemberResponse> memberResponses) {
if (topLevelError != Errors.NONE) {
return topLevelError;
} else {
for (MemberResponse memberResponse : memberResponses) {
Errors memberError = Errors.forCode(memberResponse.errorCode());
if (memberError != Errors.NONE) {
return memberError;
}
}
return Errors.NONE;
}
}
@Override
public Map<Errors, Integer> errorCounts() {
Map<Errors, Integer> combinedErrorCounts = new EnumMap<>(Errors.class);
// Top level error.
updateErrorCounts(combinedErrorCounts, Errors.forCode(data.errorCode()));
// Member level error.
data.members().forEach(memberResponse ->
updateErrorCounts(combinedErrorCounts, Errors.forCode(memberResponse.errorCode()))
);
return combinedErrorCounts;
}
@Override
public LeaveGroupResponseData data() {
return data;
}
public static LeaveGroupResponse parse(Readable readable, short version) {
return new LeaveGroupResponse(new LeaveGroupResponseData(readable, version));
}
@Override
public boolean shouldClientThrottle(short version) {
return version >= 2;
}
@Override
public boolean equals(Object other) {
return other instanceof LeaveGroupResponse &&
((LeaveGroupResponse) other).data.equals(this.data);
}
@Override
public int hashCode() {
return Objects.hashCode(data);
}
@Override
public String toString() {
return data.toString();
}
}
|
LeaveGroupResponse
|
java
|
spring-projects__spring-framework
|
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
|
{
"start": 44635,
"end": 47475
}
|
class ____ {
@Test
void nullSafeIndexWithReferenceIndexTypeAndPrimitiveValueType() {
// Integer instead of int, since null-safe operators can return null.
String exitTypeDescriptor = CodeFlow.toDescriptor(Integer.class);
StandardEvaluationContext context = new StandardEvaluationContext();
context.addIndexAccessor(new ColorOrdinalsIndexAccessor());
context.setVariable("color", Color.GREEN);
expression = parser.parseExpression("#colorOrdinals?.[#color]");
assertCannotCompile(expression);
// Cannot compile before the indexed value type is known.
assertThat(expression.getValue(context)).isNull();
assertCannotCompile(expression);
assertThat(expression.getValue(context)).isNull();
assertThat(getAst().getExitDescriptor()).isNull();
context.setVariable("colorOrdinals", new ColorOrdinals());
assertThat(expression.getValue(context)).isEqualTo(Color.GREEN.ordinal());
assertCanCompile(expression);
assertThat(expression.getValue(context)).isEqualTo(Color.GREEN.ordinal());
assertThat(getAst().getExitDescriptor()).isEqualTo(exitTypeDescriptor);
// Null-safe support should have been compiled once the indexed value type is known.
context.setVariable("colorOrdinals", null);
assertThat(expression.getValue(context)).isNull();
assertCanCompile(expression);
assertThat(expression.getValue(context)).isNull();
assertThat(getAst().getExitDescriptor()).isEqualTo(exitTypeDescriptor);
}
@Test
void nullSafeIndexWithReferenceIndexTypeAndReferenceValueType() {
String exitTypeDescriptor = CodeFlow.toDescriptor(String.class);
StandardEvaluationContext context = new StandardEvaluationContext();
context.addIndexAccessor(new FruitMapIndexAccessor());
context.setVariable("color", Color.RED);
expression = parser.parseExpression("#fruitMap?.[#color]");
// Cannot compile before the indexed value type is known.
assertThat(expression.getValue(context)).isNull();
assertCannotCompile(expression);
assertThat(expression.getValue(context)).isNull();
assertThat(getAst().getExitDescriptor()).isNull();
context.setVariable("fruitMap", new FruitMap());
assertThat(expression.getValue(context)).isEqualTo("cherry");
assertCanCompile(expression);
assertThat(expression.getValue(context)).isEqualTo("cherry");
assertThat(getAst().getExitDescriptor()).isEqualTo(exitTypeDescriptor);
// Null-safe support should have been compiled once the indexed value type is known.
context.setVariable("fruitMap", null);
assertThat(expression.getValue(context)).isNull();
assertCanCompile(expression);
assertThat(expression.getValue(context)).isNull();
assertThat(getAst().getExitDescriptor()).isEqualTo(exitTypeDescriptor);
}
}
}
@Nested
|
NullSafeIndexAccessorTests
|
java
|
google__gson
|
gson/src/test/java/com/google/gson/internal/ConstructorConstructorTest.java
|
{
"start": 9441,
"end": 10031
}
|
interface ____ extends Map<String, Integer> {}
@Test
public void testCustomMapInterfaceCreation() {
var objectConstructor = constructorConstructor.get(TypeToken.get(CustomMapInterface.class));
var exception = assertThrows(RuntimeException.class, () -> objectConstructor.construct());
assertThat(exception)
.hasMessageThat()
.isEqualTo(
"Interfaces can't be instantiated! Register an InstanceCreator or a TypeAdapter"
+ " for this type. Interface name: "
+ CustomMapInterface.class.getName());
}
}
|
CustomMapInterface
|
java
|
apache__camel
|
components/camel-http/src/test/java/org/apache/camel/component/http/HttpReferenceParameterTest.java
|
{
"start": 1383,
"end": 3515
}
|
class ____ extends CamelTestSupport {
private static final String TEST_URI_1
= "http://localhost:8080?httpBinding=#customBinding&httpClientConfigurer=#customConfigurer&httpContext=#customContext";
private static final String TEST_URI_2
= "http://localhost:8081?httpBinding=#customBinding&httpClientConfigurer=#customConfigurer&httpContext=#customContext";
private HttpEndpoint endpoint1;
private HttpEndpoint endpoint2;
@BindToRegistry("customBinding")
private TestHttpBinding testBinding;
@BindToRegistry("customConfigurer")
private TestClientConfigurer testConfigurer;
@BindToRegistry("customContext")
private HttpContext testHttpContext;
@Override
public final void doPreSetup() throws Exception {
super.doPreSetup();
this.testBinding = new TestHttpBinding();
this.testConfigurer = new TestClientConfigurer();
this.testHttpContext = HttpClientContext.create();
}
@Override
protected final void doPostSetup() throws Exception {
super.doPostSetup();
this.endpoint1 = context.getEndpoint(TEST_URI_1, HttpEndpoint.class);
this.endpoint2 = context.getEndpoint(TEST_URI_2, HttpEndpoint.class);
}
@Test
public void testHttpBinding() {
assertSame(testBinding, endpoint1.getHttpBinding());
assertSame(testBinding, endpoint2.getHttpBinding());
}
@Test
public void testHttpClientConfigurer() {
assertSame(testConfigurer, endpoint1.getHttpClientConfigurer());
assertSame(testConfigurer, endpoint2.getHttpClientConfigurer());
}
@Test
public void testHttpContext() {
assertSame(testHttpContext, endpoint1.getHttpContext());
assertSame(testHttpContext, endpoint2.getHttpContext());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:start1").to(TEST_URI_1);
from("direct:start2").to(TEST_URI_2);
}
};
}
private static
|
HttpReferenceParameterTest
|
java
|
micronaut-projects__micronaut-core
|
core/src/main/java/io/micronaut/core/reflect/InstantiationUtils.java
|
{
"start": 11623,
"end": 12157
}
|
class ____ any exceptions as {@link InstantiationException}.
*
* @param type The type
* @param classLoader The classloader
* @return The instantiated instance
* @throws InstantiationException When an error occurs
*/
public static Object instantiate(String type, ClassLoader classLoader) {
try {
return ClassUtils.forName(type, classLoader)
.flatMap(InstantiationUtils::tryInstantiate)
.orElseThrow(() -> new InstantiationException("No
|
rethrowing
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/NonCanonicalTypeTest.java
|
{
"start": 7710,
"end": 7992
}
|
class ____ extends Nested {}
void foo(Crash.@TA Nested.DoublyNested p) {}
// BUG: Diagnostic contains: Crash.Nested.DoublyNested
void bar(Crash.@TA SubNested.DoublyNested p) {}
}
""")
.doTest();
}
}
|
SubNested
|
java
|
ReactiveX__RxJava
|
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMergeWithCompletable.java
|
{
"start": 1850,
"end": 4091
}
|
class ____<T> extends AtomicInteger
implements FlowableSubscriber<T>, Subscription {
private static final long serialVersionUID = -4592979584110982903L;
final Subscriber<? super T> downstream;
final AtomicReference<Subscription> mainSubscription;
final OtherObserver otherObserver;
final AtomicThrowable errors;
final AtomicLong requested;
volatile boolean mainDone;
volatile boolean otherDone;
MergeWithSubscriber(Subscriber<? super T> downstream) {
this.downstream = downstream;
this.mainSubscription = new AtomicReference<>();
this.otherObserver = new OtherObserver(this);
this.errors = new AtomicThrowable();
this.requested = new AtomicLong();
}
@Override
public void onSubscribe(Subscription s) {
SubscriptionHelper.deferredSetOnce(mainSubscription, requested, s);
}
@Override
public void onNext(T t) {
HalfSerializer.onNext(downstream, t, this, errors);
}
@Override
public void onError(Throwable ex) {
DisposableHelper.dispose(otherObserver);
HalfSerializer.onError(downstream, ex, this, errors);
}
@Override
public void onComplete() {
mainDone = true;
if (otherDone) {
HalfSerializer.onComplete(downstream, this, errors);
}
}
@Override
public void request(long n) {
SubscriptionHelper.deferredRequest(mainSubscription, requested, n);
}
@Override
public void cancel() {
SubscriptionHelper.cancel(mainSubscription);
DisposableHelper.dispose(otherObserver);
errors.tryTerminateAndReport();
}
void otherError(Throwable ex) {
SubscriptionHelper.cancel(mainSubscription);
HalfSerializer.onError(downstream, ex, this, errors);
}
void otherComplete() {
otherDone = true;
if (mainDone) {
HalfSerializer.onComplete(downstream, this, errors);
}
}
static final
|
MergeWithSubscriber
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/delegation/AbstractS3ATokenIdentifier.java
|
{
"start": 1652,
"end": 2189
}
|
class ____ provide
* <ol>
* <li>Their unique token kind.</li>
* <li>An empty constructor.</li>
* <li>An entry in the resource file
* {@code /META-INF/services/org.apache.hadoop.security.token.TokenIdentifier}
* </li>
* </ol>
*
* The base implementation contains
* <ol>
* <li>The URI of the FS.</li>
* <li>Encryption secrets for use in the destination FS.</li>
* </ol>
* Subclasses are required to add whatever information is needed to authenticate
* the user with the credential provider which their binding
|
must
|
java
|
netty__netty
|
codec-http2/src/test/java/io/netty/handler/codec/http2/Http2ClientUpgradeCodecTest.java
|
{
"start": 1232,
"end": 3332
}
|
class ____ {
@Test
public void testUpgradeToHttp2ConnectionHandler() throws Exception {
testUpgrade(new Http2ConnectionHandlerBuilder().server(false).frameListener(
new Http2FrameAdapter()).build(), null);
}
@Test
public void testUpgradeToHttp2FrameCodec() throws Exception {
testUpgrade(Http2FrameCodecBuilder.forClient().build(), null);
}
@Test
public void testUpgradeToHttp2MultiplexCodec() throws Exception {
testUpgrade(Http2MultiplexCodecBuilder.forClient(new HttpInboundHandler())
.withUpgradeStreamHandler(new ChannelInboundHandlerAdapter()).build(), null);
}
@Test
public void testUpgradeToHttp2FrameCodecWithMultiplexer() throws Exception {
testUpgrade(Http2FrameCodecBuilder.forClient().build(),
new Http2MultiplexHandler(new HttpInboundHandler(), new HttpInboundHandler()));
}
private static void testUpgrade(Http2ConnectionHandler handler, Http2MultiplexHandler multiplexer)
throws Exception {
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "*");
EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
ChannelHandlerContext ctx = channel.pipeline().firstContext();
Http2ClientUpgradeCodec codec;
if (multiplexer == null) {
codec = new Http2ClientUpgradeCodec("connectionHandler", handler);
} else {
codec = new Http2ClientUpgradeCodec("connectionHandler", handler, multiplexer);
}
codec.setUpgradeHeaders(ctx, request);
// Flush the channel to ensure we write out all buffered data
channel.flush();
codec.upgradeTo(ctx, null);
assertNotNull(channel.pipeline().get("connectionHandler"));
if (multiplexer != null) {
assertNotNull(channel.pipeline().get(Http2MultiplexHandler.class));
}
assertTrue(channel.finishAndReleaseAll());
}
@ChannelHandler.Sharable
private static final
|
Http2ClientUpgradeCodecTest
|
java
|
netty__netty
|
microbench/src/main/java/io/netty/microbench/channel/EmbeddedChannelWriteAccumulatingHandlerContext.java
|
{
"start": 1022,
"end": 3702
}
|
class ____ extends EmbeddedChannelHandlerContext {
private ByteBuf cumulation;
private final ByteToMessageDecoder.Cumulator cumulator;
protected EmbeddedChannelWriteAccumulatingHandlerContext(ByteBufAllocator alloc, ChannelHandler handler,
ByteToMessageDecoder.Cumulator writeCumulator) {
this(alloc, handler, writeCumulator, new EmbeddedChannel());
}
protected EmbeddedChannelWriteAccumulatingHandlerContext(ByteBufAllocator alloc, ChannelHandler handler,
ByteToMessageDecoder.Cumulator writeCumulator,
EmbeddedChannel channel) {
super(alloc, handler, channel);
this.cumulator = ObjectUtil.checkNotNull(writeCumulator, "writeCumulator");
}
public final ByteBuf cumulation() {
return cumulation;
}
public final void releaseCumulation() {
if (cumulation != null) {
cumulation.release();
cumulation = null;
}
}
@Override
public final ChannelFuture write(Object msg) {
return write(msg, newPromise());
}
@Override
public final ChannelFuture write(Object msg, ChannelPromise promise) {
try {
if (msg instanceof ByteBuf) {
if (cumulation == null) {
cumulation = (ByteBuf) msg;
} else {
cumulation = cumulator.cumulate(alloc(), cumulation, (ByteBuf) msg);
}
promise.setSuccess();
} else {
channel().write(msg, promise);
}
} catch (Exception e) {
promise.setFailure(e);
handleException(e);
}
return promise;
}
@Override
public final ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) {
try {
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
if (cumulation == null) {
cumulation = buf;
} else {
cumulation = cumulator.cumulate(alloc(), cumulation, buf);
}
promise.setSuccess();
} else {
channel().writeAndFlush(msg, promise);
}
} catch (Exception e) {
promise.setFailure(e);
handleException(e);
}
return promise;
}
@Override
public final ChannelFuture writeAndFlush(Object msg) {
return writeAndFlush(msg, newPromise());
}
}
|
EmbeddedChannelWriteAccumulatingHandlerContext
|
java
|
mapstruct__mapstruct
|
processor/src/test/java/org/mapstruct/ap/test/bugs/_913/DomainWithoutSetterDtoWithNvmsDefaultMapper.java
|
{
"start": 587,
"end": 1484
}
|
interface ____ {
DomainWithoutSetterDtoWithNvmsDefaultMapper INSTANCE =
Mappers.getMapper( DomainWithoutSetterDtoWithNvmsDefaultMapper.class );
@Mappings({
@Mapping(target = "strings", source = "strings"),
@Mapping(target = "longs", source = "strings"),
@Mapping(target = "stringsInitialized", source = "stringsInitialized"),
@Mapping(target = "longsInitialized", source = "stringsInitialized"),
@Mapping(target = "stringsWithDefault", source = "stringsWithDefault", defaultValue = "3")
})
DomainWithoutSetter create(Dto source);
@InheritConfiguration( name = "create" )
void update(Dto source, @MappingTarget DomainWithoutSetter target);
@InheritConfiguration( name = "create" )
DomainWithoutSetter updateWithReturn(Dto source, @MappingTarget DomainWithoutSetter target);
}
|
DomainWithoutSetterDtoWithNvmsDefaultMapper
|
java
|
apache__dubbo
|
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjectorTest.java
|
{
"start": 1764,
"end": 4002
}
|
class ____ {
@BeforeEach
public void init() {
DubboBootstrap.reset();
}
@AfterEach
public void destroy() {}
@Test
void testSpringInjector() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try {
context.setDisplayName("Context1");
context.register(getClass());
context.refresh();
SpringExtensionInjector springExtensionInjector =
SpringExtensionInjector.get(DubboBeanUtils.getApplicationModel(context));
Assertions.assertEquals(springExtensionInjector.getContext(), context);
Protocol protocol = springExtensionInjector.getInstance(Protocol.class, "protocol");
Assertions.assertNull(protocol);
DemoService demoServiceBean1 = springExtensionInjector.getInstance(DemoService.class, "bean1");
Assertions.assertNotNull(demoServiceBean1);
DemoService demoServiceBean2 = springExtensionInjector.getInstance(DemoService.class, "bean2");
Assertions.assertNotNull(demoServiceBean2);
HelloService helloServiceBean = springExtensionInjector.getInstance(HelloService.class, "hello");
Assertions.assertNotNull(helloServiceBean);
HelloService helloService = springExtensionInjector.getInstance(HelloService.class, null);
Assertions.assertEquals(helloService, helloServiceBean);
Assertions.assertThrows(
IllegalStateException.class,
() -> springExtensionInjector.getInstance(DemoService.class, null),
"Expect single but found 2 beans in spring context: [bean1, bean2]");
} finally {
context.close();
}
}
@Bean("bean1")
public DemoService bean1() {
return new DemoServiceImpl();
}
@Bean("bean2")
public DemoService bean2() {
return new DemoServiceImpl();
}
@Bean("hello")
public HelloService helloService() {
return new HelloServiceImpl();
}
@Bean
public ApplicationConfig applicationConfig() {
return new ApplicationConfig("test-app");
}
}
|
SpringExtensionInjectorTest
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/api/map/MapWriterAsync.java
|
{
"start": 897,
"end": 1041
}
|
interface ____<K, V> {
CompletionStage<Void> write(Map<K, V> map);
CompletionStage<Void> delete(Collection<K> keys);
}
|
MapWriterAsync
|
java
|
grpc__grpc-java
|
core/src/main/java/io/grpc/internal/ManagedChannelImplBuilder.java
|
{
"start": 29027,
"end": 31660
}
|
class ____ {
public final URI targetUri;
public final NameResolverProvider provider;
public ResolvedNameResolver(URI targetUri, NameResolverProvider provider) {
this.targetUri = checkNotNull(targetUri, "targetUri");
this.provider = checkNotNull(provider, "provider");
}
}
@VisibleForTesting
static ResolvedNameResolver getNameResolverProvider(
String target, NameResolverRegistry nameResolverRegistry,
Collection<Class<? extends SocketAddress>> channelTransportSocketAddressTypes) {
// Finding a NameResolver. Try using the target string as the URI. If that fails, try prepending
// "dns:///".
NameResolverProvider provider = null;
URI targetUri = null;
StringBuilder uriSyntaxErrors = new StringBuilder();
try {
targetUri = new URI(target);
} catch (URISyntaxException e) {
// Can happen with ip addresses like "[::1]:1234" or 127.0.0.1:1234.
uriSyntaxErrors.append(e.getMessage());
}
if (targetUri != null) {
// For "localhost:8080" this would likely cause provider to be null, because "localhost" is
// parsed as the scheme. Will hit the next case and try "dns:///localhost:8080".
provider = nameResolverRegistry.getProviderForScheme(targetUri.getScheme());
}
if (provider == null && !URI_PATTERN.matcher(target).matches()) {
// It doesn't look like a URI target. Maybe it's an authority string. Try with the default
// scheme from the registry.
try {
targetUri = new URI(nameResolverRegistry.getDefaultScheme(), "", "/" + target, null);
} catch (URISyntaxException e) {
// Should not be possible.
throw new IllegalArgumentException(e);
}
provider = nameResolverRegistry.getProviderForScheme(targetUri.getScheme());
}
if (provider == null) {
throw new IllegalArgumentException(String.format(
"Could not find a NameResolverProvider for %s%s",
target, uriSyntaxErrors.length() > 0 ? " (" + uriSyntaxErrors + ")" : ""));
}
if (channelTransportSocketAddressTypes != null) {
Collection<Class<? extends SocketAddress>> nameResolverSocketAddressTypes
= provider.getProducedSocketAddressTypes();
if (!channelTransportSocketAddressTypes.containsAll(nameResolverSocketAddressTypes)) {
throw new IllegalArgumentException(String.format(
"Address types of NameResolver '%s' for '%s' not supported by transport",
targetUri.getScheme(), target));
}
}
return new ResolvedNameResolver(targetUri, provider);
}
private static
|
ResolvedNameResolver
|
java
|
micronaut-projects__micronaut-core
|
websocket/src/main/java/io/micronaut/websocket/event/WebSocketEvent.java
|
{
"start": 756,
"end": 862
}
|
class ____ all events emitted by the WebSocket server.
*
* @author graemerocher
* @since 1.0
*/
public
|
for
|
java
|
elastic__elasticsearch
|
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/function/scalar/string/BetweenFunctionPipe.java
|
{
"start": 693,
"end": 4395
}
|
class ____ extends Pipe {
private final Pipe input, left, right, greedy;
private final boolean caseInsensitive;
public BetweenFunctionPipe(
Source source,
Expression expression,
Pipe input,
Pipe left,
Pipe right,
Pipe greedy,
boolean caseInsensitive
) {
super(source, expression, Arrays.asList(input, left, right, greedy));
this.input = input;
this.left = left;
this.right = right;
this.greedy = greedy;
this.caseInsensitive = caseInsensitive;
}
@Override
public final Pipe replaceChildren(List<Pipe> newChildren) {
return replaceChildren(newChildren.get(0), newChildren.get(1), newChildren.get(2), newChildren.get(3));
}
@Override
public final Pipe resolveAttributes(AttributeResolver resolver) {
Pipe newInput = input.resolveAttributes(resolver);
Pipe newLeft = left.resolveAttributes(resolver);
Pipe newRight = right.resolveAttributes(resolver);
Pipe newGreedy = greedy.resolveAttributes(resolver);
if (newInput == input && newLeft == left && newRight == right && newGreedy == greedy) {
return this;
}
return replaceChildren(newInput, newLeft, newRight, newGreedy);
}
@Override
public boolean supportedByAggsOnlyQuery() {
return input.supportedByAggsOnlyQuery()
&& left.supportedByAggsOnlyQuery()
&& right.supportedByAggsOnlyQuery()
&& greedy.supportedByAggsOnlyQuery();
}
@Override
public boolean resolved() {
return input.resolved() && left.resolved() && right.resolved() && greedy.resolved();
}
protected Pipe replaceChildren(Pipe newInput, Pipe newLeft, Pipe newRight, Pipe newGreedy) {
return new BetweenFunctionPipe(source(), expression(), newInput, newLeft, newRight, newGreedy, caseInsensitive);
}
@Override
public final void collectFields(QlSourceBuilder sourceBuilder) {
input.collectFields(sourceBuilder);
left.collectFields(sourceBuilder);
right.collectFields(sourceBuilder);
greedy.collectFields(sourceBuilder);
}
@Override
protected NodeInfo<BetweenFunctionPipe> info() {
return NodeInfo.create(this, BetweenFunctionPipe::new, expression(), input, left, right, greedy, caseInsensitive);
}
@Override
public BetweenFunctionProcessor asProcessor() {
return new BetweenFunctionProcessor(
input.asProcessor(),
left.asProcessor(),
right.asProcessor(),
greedy.asProcessor(),
caseInsensitive
);
}
public Pipe input() {
return input;
}
public Pipe left() {
return left;
}
public Pipe right() {
return right;
}
public Pipe greedy() {
return greedy;
}
public boolean isCaseInsensitive() {
return caseInsensitive;
}
@Override
public int hashCode() {
return Objects.hash(input(), left(), right(), greedy(), caseInsensitive);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
BetweenFunctionPipe other = (BetweenFunctionPipe) obj;
return Objects.equals(input(), other.input())
&& Objects.equals(left(), other.left())
&& Objects.equals(right(), other.right())
&& Objects.equals(greedy(), other.greedy())
&& Objects.equals(caseInsensitive, other.caseInsensitive);
}
}
|
BetweenFunctionPipe
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_hasOnlyElementsOfType_Test.java
|
{
"start": 883,
"end": 1276
}
|
class ____ extends ObjectArrayAssertBaseTest {
@Override
protected ObjectArrayAssert<Object> invoke_api_method() {
return assertions.hasOnlyElementsOfType(String.class);
}
@Override
protected void verify_internal_effects() {
verify(arrays).assertHasOnlyElementsOfType(getInfo(assertions), getActual(assertions), String.class);
}
}
|
ObjectArrayAssert_hasOnlyElementsOfType_Test
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/factories/RpcClientFactory.java
|
{
"start": 1058,
"end": 1249
}
|
interface ____ {
public Object getClient(Class<?> protocol, long clientVersion,
InetSocketAddress addr, Configuration conf);
public void stopClient(Object proxy);
}
|
RpcClientFactory
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.