proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/ChangeDelta.java
|
ChangeDelta
|
applyTo
|
class ChangeDelta<T> extends Delta<T> {
/**
* Creates a change delta with the two given chunks.
* @param original The original chunk. Must not be {@code null}.
* @param revised The original chunk. Must not be {@code null}.
*/
public ChangeDelta(Chunk<T> original, Chunk<T> revised) {
super(original, revised);
}
/**
* {@inheritDoc}
*/
@Override
public void applyTo(List<T> target) throws IllegalStateException {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public void verify(List<T> target) throws IllegalStateException {
getOriginal().verify(target);
checkState(getOriginal().getPosition() <= target.size(),
"Incorrect patch for delta: delta original position > target size");
}
@Override
public TYPE getType() {
return Delta.TYPE.CHANGE;
}
}
|
verify(target);
int position = getOriginal().getPosition();
int size = getOriginal().size();
for (int i = 0; i < size; i++) {
target.remove(position);
}
int i = 0;
for (T line : getRevised().getLines()) {
target.add(position + i, line);
i++;
}
| 262
| 101
| 363
|
<methods>public void <init>(Chunk<T>, Chunk<T>) ,public abstract void applyTo(List<T>) throws java.lang.IllegalStateException,public boolean equals(java.lang.Object) ,public Chunk<T> getOriginal() ,public Chunk<T> getRevised() ,public abstract org.assertj.core.util.diff.Delta.TYPE getType() ,public int hashCode() ,public int lineNumber() ,public java.lang.String toString() ,public abstract void verify(List<T>) throws java.lang.IllegalStateException<variables>public static final java.lang.String DEFAULT_END,public static final java.lang.String DEFAULT_START,private Chunk<T> original,private Chunk<T> revised
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/Chunk.java
|
Chunk
|
equals
|
class Chunk<T> {
private final int position;
private List<T> lines;
/**
* Creates a chunk and saves a copy of affected lines
*
* @param position
* the start position
* @param lines
* the affected lines
*/
public Chunk(int position, List<T> lines) {
this.position = position;
this.lines = lines;
}
/**
* Verifies that this chunk's saved text matches the corresponding text in
* the given sequence.
*
* @param target
* the sequence to verify against.
*/
public void verify(List<T> target) throws IllegalStateException {
checkState(last() <= target.size(), "Incorrect Chunk: the position of chunk > target size");
for (int i = 0; i < size(); i++) {
checkState(target.get(position + i).equals(lines.get(i)),
"Incorrect Chunk: the chunk content doesn't match the target");
}
}
/**
* @return the start position of chunk in the text
*/
public int getPosition() {
return position;
}
/**
* @return the affected lines
*/
public List<T> getLines() {
return lines;
}
/**
* Return the chunk size
* @return the chunk size
*/
public int size() {
return lines.size();
}
/**
* Returns the index of the last line of the chunk.
* @return the index of the last line of the chunk.
*/
public int last() {
return getPosition() + size() - 1;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((lines == null) ? 0 : lines.hashCode());
result = prime * result + position;
result = prime * result + size();
return result;
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "[position: " + position + ", size: " + size() + ", lines: " + lines + "]";
}
}
|
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
@SuppressWarnings("rawtypes")
Chunk other = (Chunk) obj;
if (lines == null) {
if (other.lines != null)
return false;
} else if (!lines.equals(other.lines))
return false;
return position == other.position;
| 589
| 125
| 714
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/DeleteDelta.java
|
DeleteDelta
|
applyTo
|
class DeleteDelta<T> extends Delta<T> {
/**
* Creates a change delta with the two given chunks.
*
* @param original
* The original chunk. Must not be {@code null}.
* @param revised
* The original chunk. Must not be {@code null}.
*/
public DeleteDelta(Chunk<T> original, Chunk<T> revised) {
super(original, revised);
}
/**
* {@inheritDoc}
*/
@Override
public void applyTo(List<T> target) throws IllegalStateException {<FILL_FUNCTION_BODY>}
@Override
public TYPE getType() {
return Delta.TYPE.DELETE;
}
@Override
public void verify(List<T> target) throws IllegalStateException {
getOriginal().verify(target);
}
}
|
verify(target);
int position = getOriginal().getPosition();
int size = getOriginal().size();
for (int i = 0; i < size; i++) {
target.remove(position);
}
| 229
| 58
| 287
|
<methods>public void <init>(Chunk<T>, Chunk<T>) ,public abstract void applyTo(List<T>) throws java.lang.IllegalStateException,public boolean equals(java.lang.Object) ,public Chunk<T> getOriginal() ,public Chunk<T> getRevised() ,public abstract org.assertj.core.util.diff.Delta.TYPE getType() ,public int hashCode() ,public int lineNumber() ,public java.lang.String toString() ,public abstract void verify(List<T>) throws java.lang.IllegalStateException<variables>public static final java.lang.String DEFAULT_END,public static final java.lang.String DEFAULT_START,private Chunk<T> original,private Chunk<T> revised
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/Delta.java
|
Delta
|
equals
|
class Delta<T> {
public static final String DEFAULT_END = "]";
public static final String DEFAULT_START = "[";
/** The original chunk. */
private Chunk<T> original;
/** The revised chunk. */
private Chunk<T> revised;
/**
* Specifies the type of the delta.
*
*/
public enum TYPE {
/** A change in the original. */
CHANGE,
/** A delete from the original. */
DELETE,
/** An insert into the original. */
INSERT
}
/**
* Construct the delta for original and revised chunks
*
* @param original Chunk describing the original text. Must not be {@code null}.
* @param revised Chunk describing the revised text. Must not be {@code null}.
*/
public Delta(Chunk<T> original, Chunk<T> revised) {
checkArgument(original != null, "original must not be null");
checkArgument(revised != null, "revised must not be null");
this.original = original;
this.revised = revised;
}
/**
* Verifies that this delta can be used to patch the given text.
*
* @param target the text to patch.
* @throws IllegalStateException if the patch cannot be applied.
*/
public abstract void verify(List<T> target) throws IllegalStateException;
/**
* Applies this delta as the patch for a given target
*
* @param target the given target
* @throws IllegalStateException if {@link #verify(List)} fails
*/
public abstract void applyTo(List<T> target) throws IllegalStateException;
/**
* Returns the type of delta
* @return the type enum
*/
public abstract TYPE getType();
/**
* @return The Chunk describing the original text.
*/
public Chunk<T> getOriginal() {
return original;
}
/**
* @return The Chunk describing the revised text.
*/
public Chunk<T> getRevised() {
return revised;
}
@Override
public int hashCode() {
return Objects.hash(original, revised);
}
@Override
public boolean equals(Object obj) {<FILL_FUNCTION_BODY>}
public int lineNumber() {
return getOriginal().getPosition() + 1;
}
@Override
public String toString() {
return ConfigurationProvider.CONFIGURATION_PROVIDER.representation().toStringOf(this);
}
}
|
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Delta<?> other = (Delta<?>) obj;
return Objects.equals(original, other.original) && Objects.equals(revised, other.revised);
| 667
| 87
| 754
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/DeltaComparator.java
|
DeltaComparator
|
compare
|
class DeltaComparator implements Comparator<Delta<?>>, Serializable {
private static final long serialVersionUID = 1L;
public static final Comparator<Delta<?>> INSTANCE = new DeltaComparator();
private DeltaComparator() {}
@Override
public int compare(final Delta<?> a, final Delta<?> b) {<FILL_FUNCTION_BODY>}
}
|
final int posA = a.getOriginal().getPosition();
final int posB = b.getOriginal().getPosition();
if (posA > posB) {
return 1;
} else if (posA < posB) {
return -1;
}
return 0;
| 110
| 78
| 188
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/InsertDelta.java
|
InsertDelta
|
applyTo
|
class InsertDelta<T> extends Delta<T> {
/**
* Creates an insert delta with the two given chunks.
*
* @param original
* The original chunk. Must not be {@code null}.
* @param revised
* The original chunk. Must not be {@code null}.
*/
public InsertDelta(Chunk<T> original, Chunk<T> revised) {
super(original, revised);
}
/**
* {@inheritDoc}
*/
@Override
public void applyTo(List<T> target) {<FILL_FUNCTION_BODY>}
@Override
public void verify(List<T> target) throws IllegalStateException {
checkState(getOriginal().getPosition() <= target.size(),
"Incorrect patch for delta: delta original position > target size");
}
@Override
public TYPE getType() {
return Delta.TYPE.INSERT;
}
}
|
verify(target);
int position = this.getOriginal().getPosition();
List<T> lines = this.getRevised().getLines();
for (int i = 0; i < lines.size(); i++) {
target.add(position + i, lines.get(i));
}
| 248
| 78
| 326
|
<methods>public void <init>(Chunk<T>, Chunk<T>) ,public abstract void applyTo(List<T>) throws java.lang.IllegalStateException,public boolean equals(java.lang.Object) ,public Chunk<T> getOriginal() ,public Chunk<T> getRevised() ,public abstract org.assertj.core.util.diff.Delta.TYPE getType() ,public int hashCode() ,public int lineNumber() ,public java.lang.String toString() ,public abstract void verify(List<T>) throws java.lang.IllegalStateException<variables>public static final java.lang.String DEFAULT_END,public static final java.lang.String DEFAULT_START,private Chunk<T> original,private Chunk<T> revised
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/Patch.java
|
Patch
|
applyTo
|
class Patch<T> {
private List<Delta<T>> deltas = new LinkedList<>();
/**
* Apply this patch to the given target
* @param target the list to patch
* @return the patched text
* @throws IllegalStateException if can't apply patch
*/
public List<T> applyTo(List<T> target) throws IllegalStateException {<FILL_FUNCTION_BODY>}
/**
* Add the given delta to this patch
* @param delta the given delta
*/
public void addDelta(Delta<T> delta) {
deltas.add(delta);
}
/**
* Get the list of computed deltas
* @return the deltas
*/
public List<Delta<T>> getDeltas() {
Collections.sort(deltas, DeltaComparator.INSTANCE);
return deltas;
}
}
|
List<T> result = new LinkedList<>(target);
ListIterator<Delta<T>> it = getDeltas().listIterator(deltas.size());
while (it.hasPrevious()) {
Delta<T> delta = it.previous();
delta.applyTo(result);
}
return result;
| 236
| 83
| 319
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/myers/MyersDiff.java
|
MyersDiff
|
buildPath
|
class MyersDiff<T> implements DiffAlgorithm<T> {
/** The equalizer. */
private final Equalizer<T> equalizer;
/**
* Constructs an instance of the Myers differencing algorithm.
*/
public MyersDiff() {
/* Default equalizer. */
equalizer = Object::equals;
}
/**
* {@inheritDoc}
*
* Return empty diff if get the error while procession the difference.
*/
@Override
public Patch<T> diff(final List<T> original, final List<T> revised) {
checkArgument(original != null, "original list must not be null");
checkArgument(revised != null, "revised list must not be null");
PathNode path;
try {
path = buildPath(original, revised);
return buildRevision(path, original, revised);
} catch (IllegalStateException e) {
e.printStackTrace();
return new Patch<>();
}
}
/**
* Computes the minimum diffpath that expresses de differences
* between the original and revised sequences, according
* to Gene Myers differencing algorithm.
*
* @param orig The original sequence.
* @param rev The revised sequence.
* @return A minimum {@link PathNode Path} across the differences graph.
* @throws IllegalStateException if a diff path could not be found.
*/
public PathNode buildPath(final List<T> orig, final List<T> rev) {<FILL_FUNCTION_BODY>}
private boolean equals(T orig, T rev) {
return equalizer.equals(orig, rev);
}
/**
* Constructs a {@link Patch} from a difference path.
*
* @param path The path.
* @param orig The original sequence.
* @param rev The revised sequence.
* @return A {@link Patch} script corresponding to the path.
*/
public Patch<T> buildRevision(PathNode path, List<T> orig, List<T> rev) {
checkArgument(path != null, "path is null");
checkArgument(orig != null, "original sequence is null");
checkArgument(rev != null, "revised sequence is null");
Patch<T> patch = new Patch<>();
if (path.isSnake())
path = path.prev;
while (path != null && path.prev != null && path.prev.j >= 0) {
checkState(!path.isSnake(), "bad diffpath: found snake when looking for diff");
int i = path.i;
int j = path.j;
path = path.prev;
int ianchor = path.i;
int janchor = path.j;
Chunk<T> original = new Chunk<>(ianchor, copyOfRange(orig, ianchor, i));
Chunk<T> revised = new Chunk<>(janchor, copyOfRange(rev, janchor, j));
Delta<T> delta;
if (original.size() == 0 && revised.size() != 0) {
delta = new InsertDelta<>(original, revised);
} else if (original.size() > 0 && revised.size() == 0) {
delta = new DeleteDelta<>(original, revised);
} else {
delta = new ChangeDelta<>(original, revised);
}
patch.addDelta(delta);
if (path.isSnake()) path = path.prev;
}
return patch;
}
/**
* Creates a new list containing the elements returned by {@link List#subList(int, int)}.
* @param original The original sequence. Must not be {@code null}.
* @param fromIndex low endpoint (inclusive) of the subList.
* @param to high endpoint (exclusive) of the subList.
* @return A new list of the specified range within the original list.
*/
private List<T> copyOfRange(final List<T> original, final int fromIndex, final int to) {
return new ArrayList<>(original.subList(fromIndex, to));
}
}
|
checkArgument(orig != null, "original sequence is null");
checkArgument(rev != null, "revised sequence is null");
// these are local constants
final int N = orig.size();
final int M = rev.size();
final int MAX = N + M + 1;
final int size = 1 + 2 * MAX;
final int middle = size / 2;
final PathNode[] diagonal = new PathNode[size];
diagonal[middle + 1] = new Snake(0, -1, null);
for (int d = 0; d < MAX; d++) {
for (int k = -d; k <= d; k += 2) {
final int kmiddle = middle + k;
final int kplus = kmiddle + 1;
final int kminus = kmiddle - 1;
PathNode prev;
int i;
if ((k == -d) || (k != d && diagonal[kminus].i < diagonal[kplus].i)) {
i = diagonal[kplus].i;
prev = diagonal[kplus];
} else {
i = diagonal[kminus].i + 1;
prev = diagonal[kminus];
}
diagonal[kminus] = null; // no longer used
int j = i - k;
PathNode node = new DiffNode(i, j, prev);
// orig and rev are zero-based
// but the algorithm is one-based
// that's why there's no +1 when indexing the sequences
while (i < N && j < M && equals(orig.get(i), rev.get(j))) {
i++;
j++;
}
if (i > node.i) node = new Snake(i, j, node);
diagonal[kmiddle] = node;
if (i >= N && j >= M) return diagonal[kmiddle];
}
diagonal[middle + d - 1] = null;
}
// According to Myers, this cannot happen
throw new IllegalStateException("could not find a diff path");
| 1,057
| 520
| 1,577
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/diff/myers/PathNode.java
|
PathNode
|
previousSnake
|
class PathNode {
/** Position in the original sequence. */
public final int i;
/** Position in the revised sequence. */
public final int j;
/** The previous node in the path. */
public final PathNode prev;
/**
* Concatenates a new path node with an existing diffpath.
* @param i The position in the original sequence for the new node.
* @param j The position in the revised sequence for the new node.
* @param prev The previous node in the path.
*/
public PathNode(int i, int j, PathNode prev) {
this.i = i;
this.j = j;
this.prev = prev;
}
/**
* Is this node a {@link Snake Snake node}?
* @return true if this is a {@link Snake Snake node}
*/
public abstract boolean isSnake();
/**
* Is this a bootstrap node?
* <p>
* In bootstrap nodes one of the two coordinates is
* less than zero.
* @return tru if this is a bootstrap node.
*/
public boolean isBootstrap() {
return i < 0 || j < 0;
}
/**
* Skips sequences of {@link DiffNode DiffNodes} until a
* {@link Snake} or bootstrap node is found, or the end
* of the path is reached.
* @return The next first {@link Snake} or bootstrap node in the path, or
* <code>null</code>
* if none found.
*/
public final PathNode previousSnake() {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder("[");
PathNode node = this;
while (node != null) {
buf.append("(").append(node.i).append(",").append(node.j).append(")");
node = node.prev;
}
buf.append("]");
return buf.toString();
}
}
|
if (isBootstrap())
return null;
if (!isSnake() && prev != null)
return prev.previousSnake();
return this;
| 535
| 44
| 579
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/CaseFormatUtils.java
|
CaseFormatUtils
|
adjustWordCase
|
class CaseFormatUtils {
private static final String WORD_SEPARATOR_REGEX = "[ _-]";
private CaseFormatUtils() {}
/**
* Converts an input string into camelCase.
* <p>
* The input string may use any of the well known case styles: Pascal, Snake, Kebab or even Camel.
* Already camelCased strings will be returned as is.
* Mix and match is also an option; the algorithm will try its best to give an acceptable answer.
* Mixed case will be preserved, i.e {@code assertThat(toCamelCase("miXedCAse")).isEqualTo("miXedCAse")}
*
* @param s the string to be converted
* @return the input string converted to camelCase
*/
public static String toCamelCase(String s) {
List<String> words = extractWords(requireNonNull(s));
return IntStream.range(0, words.size())
.mapToObj(i -> adjustWordCase(words.get(i), i > 0))
.collect(joining());
}
private static List<String> extractWords(String s) {
String[] chunks = s.split(WORD_SEPARATOR_REGEX);
return Arrays.stream(chunks)
.map(String::trim)
.filter(w -> !w.isEmpty())
.collect(toList());
}
private static String adjustWordCase(String s, boolean firstLetterUpperCased) {<FILL_FUNCTION_BODY>}
private static boolean isAllCaps(String s) {
return s.toUpperCase().equals(s);
}
}
|
String firstLetter = s.substring(0, 1);
String trailingLetters = s.substring(1);
return (firstLetterUpperCased ? firstLetter.toUpperCase() : firstLetter.toLowerCase()) +
(isAllCaps(s) ? trailingLetters.toLowerCase() : trailingLetters);
| 433
| 92
| 525
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/ClassUtils.java
|
ClassUtils
|
getAllSuperclasses
|
class ClassUtils {
/**
* Lists primitive wrapper {@link Class}es.
*/
private static final List<Class<?>> PRIMITIVE_WRAPPER_TYPES = list(Boolean.class, Byte.class, Character.class, Short.class,
Integer.class, Long.class, Double.class, Float.class,
Void.class);
private static final List<Class<?>> OPTIONAL_TYPES = list(Optional.class, OptionalLong.class, OptionalDouble.class,
OptionalInt.class);
/**
* <p>Gets a {@code List} of superclasses for the given class.</p>
*
* @param cls the class to look up, may be {@code null}
* @return the {@code List} of superclasses in order going up from this one
* {@code null} if null input
*/
public static List<Class<?>> getAllSuperclasses(final Class<?> cls) {<FILL_FUNCTION_BODY>}
/**
* <p>
* Gets a {@code List} of all interfaces implemented by the given class and its superclasses.
* </p>
*
* <p>
* The order is determined by looking through each interface in turn as declared in the source file and following its
* hierarchy up. Then each superclass is considered in the same way. Later duplicates are ignored, so the order is
* maintained.
* </p>
*
* @param cls the class to look up, may be {@code null}
* @return the {@code List} of interfaces in order, {@code null} if null input
*/
public static List<Class<?>> getAllInterfaces(Class<?> cls) {
if (cls == null) return null;
LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>();
getAllInterfaces(cls, interfacesFound);
return new ArrayList<>(interfacesFound);
}
/**
* Get the interfaces for the specified class.
*
* @param cls the class to look up, may be {@code null}
* @param interfacesFound the {@code Set} of interfaces for the class
*/
static void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) {
while (cls != null) {
Class<?>[] interfaces = cls.getInterfaces();
for (Class<?> i : interfaces) {
if (interfacesFound.add(i)) {
getAllInterfaces(i, interfacesFound);
}
}
cls = cls.getSuperclass();
}
}
/**
* Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
* {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}, {@link Void}).
* <p>
* Returns false if passed null since the method can't evaluate the class.
* <p>
* Inspired from apache commons-lang ClassUtils
*
* @param type The class to query or null.
* @return true if the given {@code type} is a primitive or primitive wrapper ({@link Boolean}, {@link Byte},
* {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Double}, {@link Float}, {@link Void}).
* @since 3.24.0
*/
public static boolean isPrimitiveOrWrapper(final Class<?> type) {
if (type == null) {
return false;
}
return type.isPrimitive() || PRIMITIVE_WRAPPER_TYPES.contains(type);
}
/**
* Returns whether the given {@code type} is a primitive or primitive wrapper ({@link Optional}, {@link OptionalInt},
* {@link OptionalLong}, {@link OptionalDouble}).
* <p>
* Returns false if passed null since the method can't evaluate the class.
*
* @param type The class to query or null.
* @return true if the given {@code type} is a primitive or primitive wrapper ({@link Optional}, {@link OptionalInt},
* {@link OptionalLong}, {@link OptionalDouble}).
* @since 3.24.0
*/
public static boolean isOptionalOrPrimitiveOptional(final Class<?> type) {
if (type == null) {
return false;
}
return OPTIONAL_TYPES.contains(type);
}
/**
* Returns whether the given {@code type} belongs to the java.lang package itself or one of its subpackage.
*
* @param type The class to check or null.
* @return true the given {@code type} belongs to the java.lang package itself or one of its subpackage, false otherwise.
* @since 3.25.0
*/
public static boolean isInJavaLangPackage(final Class<?> type) {
return type != null && type.getName().startsWith("java.lang");
}
}
|
if (cls == null) {
return null;
}
final List<Class<?>> classes = new ArrayList<>();
Class<?> superclass = cls.getSuperclass();
while (superclass != null) {
classes.add(superclass);
superclass = superclass.getSuperclass();
}
return classes;
| 1,272
| 91
| 1,363
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/FieldUtils.java
|
FieldUtils
|
readField
|
class FieldUtils {
// use ConcurrentHashMap as FieldUtils can be used in a multi-thread context
private static final Map<Class<?>, Map<String, Field>> fieldsPerClass = new ConcurrentHashMap<>();
/**
* Gets an accessible <code>Field</code> by name breaking scope if requested. Superclasses/interfaces will be
* considered.
*
* @param cls the class to reflect, must not be null
* @param fieldName the field name to obtain
* @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.
* <code>False</code> will only match public fields.
* @return the Field object
* @throws IllegalArgumentException if the class or field name is null
* @throws IllegalAccessException if field exists but is not public
*/
static Field getField(final Class<?> cls, String fieldName, boolean forceAccess) throws IllegalAccessException {
checkArgument(cls != null, "The class must not be null");
checkArgument(fieldName != null, "The field name must not be null");
// Sun Java 1.3 has a bugged implementation of getField hence we write the
// code ourselves
// getField() will return the Field object with the declaring class
// set correctly to the class that declares the field. Thus requesting the
// field on a subclass will return the field from the superclass.
//
// priority order for lookup:
// searchclass private/protected/package/public
// superclass protected/package/public
// private/different package blocks access to further superclasses
// implementedinterface public
// check up the superclass hierarchy
for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) {
try {
Field field = getDeclaredField(fieldName, acls);
// getDeclaredField checks for non-public scopes as well and it returns accurate results
if (!Modifier.isPublic(field.getModifiers())) {
if (forceAccess) {
field.setAccessible(true);
} else {
throw new IllegalAccessException("can not access" + fieldName + " because it is not public");
}
}
return field;
} catch (NoSuchFieldException ex) { // NOPMD
// ignore
}
}
// check the public interface case. This must be manually searched for
// incase there is a public supersuperclass field hidden by a private/package
// superclass field.
Field match = null;
for (Class<?> class1 : ClassUtils.getAllInterfaces(cls)) {
try {
Field test = class1.getField(fieldName);
checkArgument(match == null, "Reference to field " + fieldName + " is ambiguous relative to " + cls
+ "; a matching field exists on two or more implemented interfaces.");
match = test;
} catch (NoSuchFieldException ex) { // NOPMD
// ignore
}
}
return match;
}
/**
* Returns the {@link Field} corresponding to the given fieldName for the specified class.
* <p>
* Caches the field after getting it for efficiency.
*
* @param fieldName the name of the field to get
* @param acls the class to introspect
* @return the {@link Field} corresponding to the given fieldName for the specified class.
* @throws NoSuchFieldException bubbled up from the call to {@link Class#getDeclaredField(String)}
*/
private static Field getDeclaredField(String fieldName, Class<?> acls) throws NoSuchFieldException {
fieldsPerClass.computeIfAbsent(acls, unused -> new ConcurrentHashMap<>());
// can't use computeIfAbsent for fieldName as getDeclaredField throws a checked exception
if (fieldsPerClass.get(acls).containsKey(fieldName)) return fieldsPerClass.get(acls).get(fieldName);
Field field = acls.getDeclaredField(fieldName);
fieldsPerClass.get(acls).put(fieldName, field);
return acls.getDeclaredField(fieldName);
}
/**
* Reads an accessible Field.
*
* @param field the field to use
* @param target the object to call on, may be null for static fields
* @return the field value
* @throws IllegalArgumentException if the field is null
* @throws IllegalAccessException if the field is not accessible
*/
private static Object readField(Field field, Object target) throws IllegalAccessException {
return readField(field, target, false);
}
/**
* Reads a Field.
*
* @param field the field to use
* @param target the object to call on, may be null for static fields
* @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.
* @return the field value
* @throws IllegalArgumentException if the field is null
* @throws IllegalAccessException if the field is not made accessible
*/
private static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException {
checkArgument(field != null, "The field must not be null");
if (forceAccess && !field.isAccessible()) {
field.setAccessible(true);
} else {
MemberUtils.setAccessibleWorkaround(field);
}
return field.get(target);
}
/**
* Reads the named field. Superclasses will be considered.
* <p>
* Since 3.19.0 static and synthetic fields are ignored.
*
* @param target the object to reflect, must not be null
* @param fieldName the field name to obtain
* @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.
* <code>False</code> will only match public fields.
* @return the field value
* @throws IllegalArgumentException if the class or field name is null or the field can not be found.
* @throws IllegalAccessException if the named field is not made accessible
*/
static Object readField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException {<FILL_FUNCTION_BODY>}
}
|
checkArgument(target != null, "target object must not be null");
Class<?> cls = target.getClass();
Field field = getField(cls, fieldName, forceAccess);
checkArgument(field != null, "Cannot locate field %s on %s", fieldName, cls);
checkArgument(!isStatic(field.getModifiers()), "Reading static field is not supported and field %s is static on %s",
fieldName, cls);
checkArgument(!field.isSynthetic(), "Reading synthetic field is not supported and field %s is", fieldName);
// already forced access above, don't repeat it here:
return readField(field, target);
| 1,564
| 169
| 1,733
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/Introspection.java
|
MethodKey
|
equals
|
class MethodKey {
private final String name;
private final Class<?> clazz;
private MethodKey(final String name, final Class<?> clazz) {
this.name = name;
this.clazz = clazz;
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(name, clazz);
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final MethodKey methodKey = (MethodKey) o;
return Objects.equals(name, methodKey.name) && Objects.equals(clazz, methodKey.clazz);
| 124
| 79
| 203
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/MemberUtils.java
|
MemberUtils
|
setAccessibleWorkaround
|
class MemberUtils {
private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE;
/**
* XXX Default access superclass workaround
*
* When a public class has a default access superclass with public members,
* these members are accessible. Calling them from compiled code works fine.
* Unfortunately, on some JVMs, using reflection to invoke these members
* seems to (wrongly) prevent access even when the modifier is public.
* Calling setAccessible(true) solves the problem but will only work from
* sufficiently privileged code. Better workarounds would be gratefully
* accepted.
* @param o the AccessibleObject to set as accessible
*/
static void setAccessibleWorkaround(AccessibleObject o) {<FILL_FUNCTION_BODY>}
/**
* Returns whether a given set of modifiers implies package access.
* @param modifiers to test
* @return true unless package/protected/private modifier detected
*/
static boolean isPackageAccess(int modifiers) {
return (modifiers & ACCESS_TEST) == 0;
}
}
|
if (o == null || o.isAccessible()) {
return;
}
Member m = (Member) o;
if (Modifier.isPublic(m.getModifiers())
&& isPackageAccess(m.getDeclaringClass().getModifiers())) {
try {
o.setAccessible(true);
} catch (SecurityException e) { // NOPMD
// ignore in favor of subsequent IllegalAccessException
}
}
| 292
| 115
| 407
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/MethodSupport.java
|
MethodSupport
|
methodResultFor
|
class MethodSupport {
private static final String METHOD_HAS_NO_RETURN_VALUE = "Method '%s' in class %s.class has to return a value!";
private static final String METHOD_NOT_FOUND = "Can't find method '%s' in class %s.class. Make sure public method " +
"exists and accepts no arguments!";
/**
* Returns result of given method invocation on provided object.
* <p>
* Following requirements have to be met to extract method results:
* <ul>
* <li>method has to be public,</li>
* <li>method cannot accept any arguments,</li>
* <li>method cannot return void.</li>
* </ul>
*
* @param instance object on which
* @param methodName name of method to be invoked
* @return result of method invocation
* @throws IllegalArgumentException if method does not exist or is not public, method returns void or method accepts
* any argument
*/
public static Object methodResultFor(Object instance, String methodName) {<FILL_FUNCTION_BODY>}
private static Object invokeMethod(Object item, Method method) {
try {
return method.invoke(item);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
private static Method findMethod(String methodName, Class<?> itemClass) {
try {
Method method = itemClass.getMethod(methodName);
assertHasReturnType(itemClass, method);
return method;
} catch (SecurityException | NoSuchMethodException e) {
throw prepareMethodNotFoundException(methodName, itemClass, e);
}
}
private static IllegalArgumentException prepareMethodNotFoundException(String methodName,
Class<?> itemClass,
Exception cause) {
String message = format(METHOD_NOT_FOUND, methodName, itemClass.getSimpleName());
return new IllegalArgumentException(message, cause);
}
private static void assertHasReturnType(Class<?> itemClass, Method method) {
checkArgument(!Void.TYPE.equals(method.getReturnType()),
METHOD_HAS_NO_RETURN_VALUE, method.getName(), itemClass.getSimpleName());
}
}
|
requireNonNull(instance, "Object instance can not be null!");
checkNotNullOrEmpty(methodName, "Method name can not be empty!");
Method method = findMethod(methodName, instance.getClass());
return invokeMethod(instance, method);
| 576
| 65
| 641
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/introspection/PropertyOrFieldSupport.java
|
PropertyOrFieldSupport
|
getValueOf
|
class PropertyOrFieldSupport {
private static final String SEPARATOR = ".";
private PropertySupport propertySupport;
private FieldSupport fieldSupport;
public static final PropertyOrFieldSupport EXTRACTION = new PropertyOrFieldSupport();
public static final PropertyOrFieldSupport COMPARISON = new PropertyOrFieldSupport(PropertySupport.instance(),
FieldSupport.COMPARISON);
PropertyOrFieldSupport() {
this.propertySupport = PropertySupport.instance();
this.fieldSupport = FieldSupport.extraction();
}
@VisibleForTesting
PropertyOrFieldSupport(PropertySupport propertySupport, FieldSupport fieldSupport) {
this.propertySupport = propertySupport;
this.fieldSupport = fieldSupport;
}
public void setAllowUsingPrivateFields(boolean allowUsingPrivateFields) {
fieldSupport.setAllowUsingPrivateFields(allowUsingPrivateFields);
}
public Object getValueOf(String propertyOrFieldName, Object input) {<FILL_FUNCTION_BODY>}
@SuppressWarnings({ "unchecked", "rawtypes" })
public Object getSimpleValue(String name, Object input) {
// if input is an optional and name is "value", let's get the optional value directly
if (input instanceof Optional && name.equals("value")) return ((Optional) input).orElse(null);
try {
// try to get name as a property
return propertySupport.propertyValueOf(name, Object.class, input);
} catch (IntrospectionError propertyIntrospectionError) {
// try to get name as a field
try {
return fieldSupport.fieldValue(name, Object.class, input);
} catch (IntrospectionError fieldIntrospectionError) {
// if input is a map, try to use the name value as a map key
if (input instanceof Map) {
Map<?, ?> map = (Map<?, ?>) input;
if (map.containsKey(name)) return map.get(name);
}
// no value found with given name, it is considered as an error
String message = format("%nCan't find any field or property with name '%s'.%n" +
"Error when introspecting properties was :%n" +
"- %s %n" +
"Error when introspecting fields was :%n" +
"- %s",
name, propertyIntrospectionError.getMessage(),
fieldIntrospectionError.getMessage());
throw new IntrospectionError(message, fieldIntrospectionError);
}
}
}
private String popNameFrom(String propertyOrFieldNameChain) {
if (!isNested(propertyOrFieldNameChain)) return propertyOrFieldNameChain;
return propertyOrFieldNameChain.substring(0, propertyOrFieldNameChain.indexOf(SEPARATOR));
}
private String nextNameFrom(String propertyOrFieldNameChain) {
if (!isNested(propertyOrFieldNameChain)) return "";
return propertyOrFieldNameChain.substring(propertyOrFieldNameChain.indexOf(SEPARATOR) + 1);
}
private boolean isNested(String propertyOrFieldName) {
return propertyOrFieldName.contains(SEPARATOR)
&& !propertyOrFieldName.startsWith(SEPARATOR)
&& !propertyOrFieldName.endsWith(SEPARATOR);
}
}
|
checkArgument(propertyOrFieldName != null, "The name of the property/field to read should not be null");
checkArgument(!propertyOrFieldName.isEmpty(), "The name of the property/field to read should not be empty");
checkArgument(input != null, "The object to extract property/field from should not be null");
if (isNested(propertyOrFieldName)) {
String firstPropertyName = popNameFrom(propertyOrFieldName);
Object propertyOrFieldValue = getSimpleValue(firstPropertyName, input);
// when one of the intermediate nested property/field value is null, return null
if (propertyOrFieldValue == null) return null;
// extract next sub-property/field value until reaching the last sub-property/field
return getValueOf(nextNameFrom(propertyOrFieldName), propertyOrFieldValue);
}
return getSimpleValue(propertyOrFieldName, input);
| 828
| 222
| 1,050
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-core/src/main/java/org/assertj/core/util/xml/XmlStringPrettyFormatter.java
|
XmlStringPrettyFormatter
|
prettyFormat
|
class XmlStringPrettyFormatter {
private static final String FORMAT_ERROR = "Unable to format XML string";
public static String xmlPrettyFormat(String xmlStringToFormat) {
checkArgument(xmlStringToFormat != null, "Expecting XML String not to be null");
// convert String to an XML Document and then back to String but prettily formatted.
return prettyFormat(toXmlDocument(xmlStringToFormat), xmlStringToFormat.startsWith("<?xml"));
}
private static String prettyFormat(Document document, boolean keepXmlDeclaration) {<FILL_FUNCTION_BODY>}
private static Document toXmlDocument(String xmlString) {
try {
InputSource xmlInputSource = new InputSource(new StringReader(xmlString));
DocumentBuilder xmlDocumentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return xmlDocumentBuilder.parse(xmlInputSource);
} catch (Exception e) {
throw new RuntimeException(FORMAT_ERROR, e);
}
}
private XmlStringPrettyFormatter() {
// utility class
}
}
|
try {
DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
DOMImplementationLS domImplementation = (DOMImplementationLS) registry.getDOMImplementation("LS");
Writer stringWriter = new StringWriter();
LSOutput formattedOutput = domImplementation.createLSOutput();
formattedOutput.setCharacterStream(stringWriter);
LSSerializer domSerializer = domImplementation.createLSSerializer();
domSerializer.getDomConfig().setParameter("format-pretty-print", true);
// Set this to true if the declaration is needed to be in the output.
domSerializer.getDomConfig().setParameter("xml-declaration", keepXmlDeclaration);
domSerializer.write(document, formattedOutput);
return stringWriter.toString();
} catch (Exception e) {
throw new RuntimeException(FORMAT_ERROR, e);
}
| 275
| 211
| 486
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/api/ByteSourceAssert.java
|
ByteSourceAssert
|
hasSize
|
class ByteSourceAssert extends AbstractAssert<ByteSourceAssert, ByteSource> {
protected ByteSourceAssert(ByteSource actual) {
super(actual, ByteSourceAssert.class);
}
/**
* Verifies that the actual {@link ByteSource} has the same content as the provided one.<br>
* <p>
* Example :
* <pre><code class='java'> ByteSource actual = ByteSource.wrap(new byte[1]);
* ByteSource other = ByteSource.wrap(new byte[1]);
*
* assertThat(actual).hasSameContentAs(other);</code></pre>
*
* @param other ByteSource to compare against.
* @return this {@link ByteSourceAssert} for assertions chaining.
* @throws IOException if {@link ByteSource#contentEquals} throws one.
* @throws AssertionError if the actual {@link ByteSource} is {@code null}.
* @throws AssertionError if the actual {@link ByteSource} does not contain the same content.
*/
public ByteSourceAssert hasSameContentAs(ByteSource other) throws IOException {
isNotNull();
if (!actual.contentEquals(other)) throw assertionError(shouldHaveSameContent(actual, other));
return this;
}
/**
* Verifies that the actual {@link ByteSource} is empty.
* <p>
* Example :
* <pre><code class='java'> ByteSource actual = ByteSource.wrap(new byte[0]);
*
* assertThat(actual).isEmpty();</code></pre>
*
* @throws IOException if {@link ByteSource#isEmpty} throws one.
* @throws AssertionError if the actual {@link ByteSource} is {@code null}.
* @throws AssertionError if the actual {@link ByteSource} is not empty.
*/
public void isEmpty() throws IOException {
isNotNull();
if (!actual.isEmpty()) throw assertionError(shouldBeEmpty(actual));
}
/**
* Verifies that the size of the actual {@link ByteSource} is equal to the given one.
* <p>
* Example :
*
* <pre><code class='java'> ByteSource actual = ByteSource.wrap(new byte[9]);
*
* assertThat(actual).hasSize(9);</code></pre>
*
* @param expectedSize the expected size of actual {@link ByteSource}.
* @return this {@link ByteSourceAssert} for assertions chaining.
* @throws IOException if {@link com.google.common.io.ByteSource#size()} throws one.
* @throws AssertionError if the actual {@link ByteSource} is {@code null}.
* @throws AssertionError if the number of values of the actual {@link ByteSource} is not equal to the given one.
*/
public ByteSourceAssert hasSize(long expectedSize) throws IOException {<FILL_FUNCTION_BODY>}
}
|
isNotNull();
long sizeOfActual = actual.size();
if (sizeOfActual != expectedSize) throw assertionError(shouldHaveSize(actual, sizeOfActual, expectedSize));
return this;
| 724
| 53
| 777
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public org.assertj.guava.api.ByteSourceAssert describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public org.assertj.guava.api.ByteSourceAssert doesNotHave(Condition<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert doesNotHaveSameClassAs(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert doesNotHaveSameHashCodeAs(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert doesNotHaveToString(java.lang.String) ,public transient org.assertj.guava.api.ByteSourceAssert doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public org.assertj.guava.api.ByteSourceAssert has(Condition<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert hasSameClassAs(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert hasSameHashCodeAs(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert hasToString(java.lang.String) ,public transient org.assertj.guava.api.ByteSourceAssert hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public org.assertj.guava.api.ByteSourceAssert is(Condition<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert isEqualTo(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert isExactlyInstanceOf(Class<?>) ,public transient org.assertj.guava.api.ByteSourceAssert isIn(java.lang.Object[]) ,public org.assertj.guava.api.ByteSourceAssert isIn(Iterable<?>) ,public org.assertj.guava.api.ByteSourceAssert isInstanceOf(Class<?>) ,public transient org.assertj.guava.api.ByteSourceAssert isInstanceOfAny(Class<?>[]) ,public org.assertj.guava.api.ByteSourceAssert isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public org.assertj.guava.api.ByteSourceAssert isNot(Condition<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert isNotEqualTo(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert isNotExactlyInstanceOf(Class<?>) ,public transient org.assertj.guava.api.ByteSourceAssert isNotIn(java.lang.Object[]) ,public org.assertj.guava.api.ByteSourceAssert isNotIn(Iterable<?>) ,public org.assertj.guava.api.ByteSourceAssert isNotInstanceOf(Class<?>) ,public transient org.assertj.guava.api.ByteSourceAssert isNotInstanceOfAny(Class<?>[]) ,public org.assertj.guava.api.ByteSourceAssert isNotNull() ,public transient org.assertj.guava.api.ByteSourceAssert isNotOfAnyClassIn(Class<?>[]) ,public org.assertj.guava.api.ByteSourceAssert isNotSameAs(java.lang.Object) ,public void isNull() ,public transient org.assertj.guava.api.ByteSourceAssert isOfAnyClassIn(Class<?>[]) ,public org.assertj.guava.api.ByteSourceAssert isSameAs(java.lang.Object) ,public org.assertj.guava.api.ByteSourceAssert matches(Predicate<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert matches(Predicate<? super ByteSource>, java.lang.String) ,public transient org.assertj.guava.api.ByteSourceAssert overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public org.assertj.guava.api.ByteSourceAssert overridingErrorMessage(Supplier<java.lang.String>) ,public org.assertj.guava.api.ByteSourceAssert satisfies(Condition<? super ByteSource>) ,public final transient org.assertj.guava.api.ByteSourceAssert satisfies(Consumer<? super ByteSource>[]) ,public final transient org.assertj.guava.api.ByteSourceAssert satisfies(ThrowingConsumer<? super ByteSource>[]) ,public final transient org.assertj.guava.api.ByteSourceAssert satisfiesAnyOf(Consumer<? super ByteSource>[]) ,public final transient org.assertj.guava.api.ByteSourceAssert satisfiesAnyOf(ThrowingConsumer<? super ByteSource>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public org.assertj.guava.api.ByteSourceAssert usingComparator(Comparator<? super ByteSource>) ,public org.assertj.guava.api.ByteSourceAssert usingComparator(Comparator<? super ByteSource>, java.lang.String) ,public org.assertj.guava.api.ByteSourceAssert usingDefaultComparator() ,public transient org.assertj.guava.api.ByteSourceAssert withFailMessage(java.lang.String, java.lang.Object[]) ,public org.assertj.guava.api.ByteSourceAssert withFailMessage(Supplier<java.lang.String>) ,public org.assertj.guava.api.ByteSourceAssert withRepresentation(org.assertj.core.presentation.Representation) ,public org.assertj.guava.api.ByteSourceAssert withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed ByteSource actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed org.assertj.guava.api.ByteSourceAssert myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/api/MultisetAssert.java
|
MultisetAssert
|
contains
|
class MultisetAssert<T> extends AbstractIterableAssert<MultisetAssert<T>, Multiset<? extends T>, T, ObjectAssert<T>> {
protected MultisetAssert(Multiset<? extends T> actual) {
super(actual, MultisetAssert.class);
}
/**
* Verifies the actual {@link Multiset} contains the given value <b>exactly</b> the given number of times.
* <p>
* Example :
*
* <pre><code class='java'> Multiset<String> actual = HashMultiset.create();
* actual.add("shoes", 2);
*
* // assertion succeeds
* assertThat(actual).contains(2, "shoes");
*
* // assertions fail
* assertThat(actual).contains(1, "shoes");
* assertThat(actual).contains(3, "shoes");</code></pre>
*
* @param expectedCount the exact number of times the given value should appear in the set
* @param expected the value which to expect
*
* @return this {@link MultisetAssert} for fluent chaining
*
* @throws AssertionError if the actual {@link Multiset} is null
* @throws AssertionError if the actual {@link Multiset} contains the given value a number of times different to the given count
*/
public MultisetAssert<T> contains(int expectedCount, T expected) {<FILL_FUNCTION_BODY>}
/**
* Verifies the actual {@link Multiset} contains the given value <b>at least</b> the given number of times.
* <p>
* Example :
*
* <pre><code class='java'> Multiset<String> actual = HashMultiset.create();
* actual.add("shoes", 2);
*
* // assertions succeed
* assertThat(actual).containsAtLeast(1, "shoes");
* assertThat(actual).containsAtLeast(2, "shoes");
*
* // assertion fails
* assertThat(actual).containsAtLeast(3, "shoes");</code></pre>
*
* @param minimumCount the minimum number of times the given value should appear in the set
* @param expected the value which to expect
*
* @return this {@link MultisetAssert} for fluent chaining
*
* @throws AssertionError if the actual {@link Multiset} is null
* @throws AssertionError if the actual {@link Multiset} contains the given value fewer times than the given count
*/
public MultisetAssert<T> containsAtLeast(int minimumCount, T expected) {
isNotNull();
checkArgument(minimumCount >= 0, "The minimum count should not be negative.");
int actualCount = actual.count(expected);
if (actualCount < minimumCount) {
throw assertionError(shouldContainAtLeastTimes(actual, expected, minimumCount, actualCount));
}
return myself;
}
/**
* Verifies the actual {@link Multiset} contains the given value <b>at most</b> the given number of times.
* <p>
* Example :
*
* <pre><code class='java'> Multiset<String> actual = HashMultiset.create();
* actual.add("shoes", 2);
*
* // assertions succeed
* assertThat(actual).containsAtMost(3, "shoes");
* assertThat(actual).containsAtMost(2, "shoes");
*
* // assertion fails
* assertThat(actual).containsAtMost(1, "shoes");</code></pre>
*
*
* @param maximumCount the maximum number of times the given value should appear in the set
*
* @param expected the value which to expect
* @return this {@link MultisetAssert} for fluent chaining
*
* @throws AssertionError if the actual {@link Multiset} is null
* @throws AssertionError if the actual {@link Multiset} contains the given value more times than the given count
*/
public MultisetAssert<T> containsAtMost(int maximumCount, T expected) {
isNotNull();
checkArgument(maximumCount >= 0, "The maximum count should not be negative.");
int actualCount = actual.count(expected);
if (actualCount > maximumCount) {
throw assertionError(shouldContainAtMostTimes(actual, expected, maximumCount, actualCount));
}
return myself;
}
@Override
protected ObjectAssert<T> toAssert(T value, String description) {
return null;
}
@Override
protected MultisetAssert<T> newAbstractIterableAssert(Iterable<? extends T> iterable) {
// actual may not have been a HashMultiset but there is no easy elegant to build the same Multiset subtype.
Multiset<T> filtered = HashMultiset.create();
iterable.forEach(filtered::add);
return new MultisetAssert<>(filtered);
}
}
|
isNotNull();
checkArgument(expectedCount >= 0, "The expected count should not be negative.");
int actualCount = actual.count(expected);
if (actualCount != expectedCount) {
throw assertionError(shouldContainTimes(actual, expected, expectedCount, actualCount));
}
return myself;
| 1,297
| 80
| 1,377
|
<methods>public MultisetAssert<T> allMatch(Predicate<? super T>) ,public MultisetAssert<T> allMatch(Predicate<? super T>, java.lang.String) ,public MultisetAssert<T> allSatisfy(Consumer<? super T>) ,public MultisetAssert<T> allSatisfy(ThrowingConsumer<? super T>) ,public MultisetAssert<T> anyMatch(Predicate<? super T>) ,public MultisetAssert<T> anySatisfy(Consumer<? super T>) ,public MultisetAssert<T> anySatisfy(ThrowingConsumer<? super T>) ,public MultisetAssert<T> are(Condition<? super T>) ,public MultisetAssert<T> areAtLeast(int, Condition<? super T>) ,public MultisetAssert<T> areAtLeastOne(Condition<? super T>) ,public MultisetAssert<T> areAtMost(int, Condition<? super T>) ,public MultisetAssert<T> areExactly(int, Condition<? super T>) ,public MultisetAssert<T> areNot(Condition<? super T>) ,public transient MultisetAssert<T> as(java.lang.String, java.lang.Object[]) ,public MultisetAssert<T> as(org.assertj.core.description.Description) ,public final transient MultisetAssert<T> contains(T[]) ,public MultisetAssert<T> containsAll(Iterable<? extends T>) ,public MultisetAssert<T> containsAnyElementsOf(Iterable<? extends T>) ,public final transient MultisetAssert<T> containsAnyOf(T[]) ,public final transient MultisetAssert<T> containsExactly(T[]) ,public MultisetAssert<T> containsExactlyElementsOf(Iterable<? extends T>) ,public final transient MultisetAssert<T> containsExactlyInAnyOrder(T[]) ,public MultisetAssert<T> containsExactlyInAnyOrderElementsOf(Iterable<? extends T>) ,public MultisetAssert<T> containsNull() ,public final transient MultisetAssert<T> containsOnly(T[]) ,public MultisetAssert<T> containsOnlyElementsOf(Iterable<? extends T>) ,public MultisetAssert<T> containsOnlyNulls() ,public final transient MultisetAssert<T> containsOnlyOnce(T[]) ,public MultisetAssert<T> containsOnlyOnceElementsOf(Iterable<? extends T>) ,public final transient MultisetAssert<T> containsSequence(T[]) ,public MultisetAssert<T> containsSequence(Iterable<? extends T>) ,public final transient MultisetAssert<T> containsSubsequence(T[]) ,public MultisetAssert<T> containsSubsequence(Iterable<? extends T>) ,public MultisetAssert<T> describedAs(org.assertj.core.description.Description) ,public transient MultisetAssert<T> describedAs(java.lang.String, java.lang.Object[]) ,public MultisetAssert<T> doNotHave(Condition<? super T>) ,public final transient MultisetAssert<T> doesNotContain(T[]) ,public MultisetAssert<T> doesNotContainAnyElementsOf(Iterable<? extends T>) ,public MultisetAssert<T> doesNotContainNull() ,public final transient MultisetAssert<T> doesNotContainSequence(T[]) ,public MultisetAssert<T> doesNotContainSequence(Iterable<? extends T>) ,public final transient MultisetAssert<T> doesNotContainSubsequence(T[]) ,public MultisetAssert<T> doesNotContainSubsequence(Iterable<? extends T>) ,public MultisetAssert<T> doesNotHave(Condition<? super Multiset<? extends T>>) ,public transient MultisetAssert<T> doesNotHaveAnyElementsOfTypes(Class<?>[]) ,public MultisetAssert<T> doesNotHaveDuplicates() ,public MultisetAssert<T> doesNotHaveSameClassAs(java.lang.Object) ,public ObjectAssert<T> element(int) ,public ASSERT element(int, InstanceOfAssertFactory<?,ASSERT>) ,public transient MultisetAssert<T> elements(int[]) ,public final transient MultisetAssert<T> endsWith(T, T[]) ,public MultisetAssert<T> endsWith(T[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extracting(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extracting(java.lang.String, Class<P>) ,public transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(Function<? super T,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> extracting(ThrowingExtractor<? super T,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> extracting(Function<? super T,?>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> extractingResultOf(java.lang.String) ,public AbstractListAssert<?,List<? extends P>,P,ObjectAssert<P>> extractingResultOf(java.lang.String, Class<P>) ,public MultisetAssert<T> filteredOn(java.lang.String, java.lang.Object) ,public MultisetAssert<T> filteredOn(java.lang.String, FilterOperator<?>) ,public MultisetAssert<T> filteredOn(Condition<? super T>) ,public MultisetAssert<T> filteredOn(Function<? super T,T>, T) ,public MultisetAssert<T> filteredOn(Predicate<? super T>) ,public MultisetAssert<T> filteredOnAssertions(Consumer<? super T>) ,public MultisetAssert<T> filteredOnAssertions(ThrowingConsumer<? super T>) ,public MultisetAssert<T> filteredOnNull(java.lang.String) ,public ObjectAssert<T> first() ,public ASSERT first(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(Function<? super T,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatExtracting(ThrowingExtractor<? super T,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(Function<? super T,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(ThrowingExtractor<? super T,?,EXCEPTION>[]) ,public AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String) ,public transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatExtracting(java.lang.String[]) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(Function<? super T,? extends Collection<V>>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> flatMap(ThrowingExtractor<? super T,? extends Collection<V>,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(Function<? super T,?>[]) ,public final transient AbstractListAssert<?,List<? extends java.lang.Object>,java.lang.Object,ObjectAssert<java.lang.Object>> flatMap(ThrowingExtractor<? super T,?,EXCEPTION>[]) ,public MultisetAssert<T> has(Condition<? super Multiset<? extends T>>) ,public MultisetAssert<T> hasAtLeastOneElementOfType(Class<?>) ,public transient MultisetAssert<T> hasExactlyElementsOfTypes(Class<?>[]) ,public MultisetAssert<T> hasOnlyElementsOfType(Class<?>) ,public transient MultisetAssert<T> hasOnlyElementsOfTypes(Class<?>[]) ,public MultisetAssert<T> hasOnlyOneElementSatisfying(Consumer<? super T>) ,public MultisetAssert<T> hasSameClassAs(java.lang.Object) ,public MultisetAssert<T> hasSameElementsAs(Iterable<? extends T>) ,public MultisetAssert<T> hasSameSizeAs(java.lang.Object) ,public MultisetAssert<T> hasSameSizeAs(Iterable<?>) ,public MultisetAssert<T> hasSize(int) ,public MultisetAssert<T> hasSizeBetween(int, int) ,public MultisetAssert<T> hasSizeGreaterThan(int) ,public MultisetAssert<T> hasSizeGreaterThanOrEqualTo(int) ,public MultisetAssert<T> hasSizeLessThan(int) ,public MultisetAssert<T> hasSizeLessThanOrEqualTo(int) ,public MultisetAssert<T> hasToString(java.lang.String) ,public MultisetAssert<T> have(Condition<? super T>) ,public MultisetAssert<T> haveAtLeast(int, Condition<? super T>) ,public MultisetAssert<T> haveAtLeastOne(Condition<? super T>) ,public MultisetAssert<T> haveAtMost(int, Condition<? super T>) ,public MultisetAssert<T> haveExactly(int, Condition<? super T>) ,public MultisetAssert<T> inBinary() ,public MultisetAssert<T> inHexadecimal() ,public MultisetAssert<T> is(Condition<? super Multiset<? extends T>>) ,public void isEmpty() ,public MultisetAssert<T> isEqualTo(java.lang.Object) ,public MultisetAssert<T> isExactlyInstanceOf(Class<?>) ,public MultisetAssert<T> isIn(Iterable<?>) ,public transient MultisetAssert<T> isIn(java.lang.Object[]) ,public MultisetAssert<T> isInstanceOf(Class<?>) ,public transient MultisetAssert<T> isInstanceOfAny(Class<?>[]) ,public MultisetAssert<T> isNot(Condition<? super Multiset<? extends T>>) ,public MultisetAssert<T> isNotEmpty() ,public MultisetAssert<T> isNotEqualTo(java.lang.Object) ,public MultisetAssert<T> isNotExactlyInstanceOf(Class<?>) ,public MultisetAssert<T> isNotIn(Iterable<?>) ,public transient MultisetAssert<T> isNotIn(java.lang.Object[]) ,public MultisetAssert<T> isNotInstanceOf(Class<?>) ,public transient MultisetAssert<T> isNotInstanceOfAny(Class<?>[]) ,public MultisetAssert<T> isNotNull() ,public transient MultisetAssert<T> isNotOfAnyClassIn(Class<?>[]) ,public MultisetAssert<T> isNotSameAs(java.lang.Object) ,public void isNullOrEmpty() ,public transient MultisetAssert<T> isOfAnyClassIn(Class<?>[]) ,public MultisetAssert<T> isSameAs(java.lang.Object) ,public MultisetAssert<T> isSubsetOf(Iterable<? extends T>) ,public final transient MultisetAssert<T> isSubsetOf(T[]) ,public ObjectAssert<T> last() ,public ASSERT last(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(Function<? super T,V>) ,public AbstractListAssert<?,List<? extends V>,V,ObjectAssert<V>> map(ThrowingExtractor<? super T,V,EXCEPTION>) ,public final transient AbstractListAssert<?,List<? extends org.assertj.core.groups.Tuple>,org.assertj.core.groups.Tuple,ObjectAssert<org.assertj.core.groups.Tuple>> map(Function<? super T,?>[]) ,public MultisetAssert<T> noneMatch(Predicate<? super T>) ,public MultisetAssert<T> noneSatisfy(Consumer<? super T>) ,public MultisetAssert<T> noneSatisfy(ThrowingConsumer<? super T>) ,public transient MultisetAssert<T> overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public final transient MultisetAssert<T> satisfiesExactly(Consumer<? super T>[]) ,public final transient MultisetAssert<T> satisfiesExactly(ThrowingConsumer<? super T>[]) ,public final transient MultisetAssert<T> satisfiesExactlyInAnyOrder(Consumer<? super T>[]) ,public final transient MultisetAssert<T> satisfiesExactlyInAnyOrder(ThrowingConsumer<? super T>[]) ,public MultisetAssert<T> satisfiesOnlyOnce(Consumer<? super T>) ,public MultisetAssert<T> satisfiesOnlyOnce(ThrowingConsumer<? super T>) ,public ObjectAssert<T> singleElement() ,public ASSERT singleElement(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractIterableSizeAssert<MultisetAssert<T>,Multiset<? extends T>,T,ObjectAssert<T>> size() ,public final transient MultisetAssert<T> startsWith(T[]) ,public MultisetAssert<T> usingComparator(Comparator<? super Multiset<? extends T>>) ,public MultisetAssert<T> usingComparator(Comparator<? super Multiset<? extends T>>, java.lang.String) ,public transient MultisetAssert<T> usingComparatorForElementFieldsWithNames(Comparator<T>, java.lang.String[]) ,public MultisetAssert<T> usingComparatorForElementFieldsWithType(Comparator<T>, Class<T>) ,public MultisetAssert<T> usingComparatorForType(Comparator<T>, Class<T>) ,public MultisetAssert<T> usingDefaultComparator() ,public MultisetAssert<T> usingDefaultElementComparator() ,public MultisetAssert<T> usingElementComparator(Comparator<? super T>) ,public transient MultisetAssert<T> usingElementComparatorIgnoringFields(java.lang.String[]) ,public transient MultisetAssert<T> usingElementComparatorOnFields(java.lang.String[]) ,public MultisetAssert<T> usingFieldByFieldElementComparator() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion() ,public org.assertj.core.api.RecursiveAssertionAssert usingRecursiveAssertion(org.assertj.core.api.recursive.assertion.RecursiveAssertionConfiguration) ,public RecursiveComparisonAssert<?> usingRecursiveComparison() ,public RecursiveComparisonAssert<?> usingRecursiveComparison(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public MultisetAssert<T> usingRecursiveFieldByFieldElementComparator() ,public MultisetAssert<T> usingRecursiveFieldByFieldElementComparator(org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration) ,public transient MultisetAssert<T> usingRecursiveFieldByFieldElementComparatorIgnoringFields(java.lang.String[]) ,public transient MultisetAssert<T> usingRecursiveFieldByFieldElementComparatorOnFields(java.lang.String[]) ,public transient MultisetAssert<T> withFailMessage(java.lang.String, java.lang.Object[]) ,public MultisetAssert<T> withThreadDumpOnError() ,public MultisetAssert<T> zipSatisfy(Iterable<OTHER_ELEMENT>, BiConsumer<? super T,OTHER_ELEMENT>) <variables>private static final java.lang.String ASSERT,private org.assertj.core.internal.TypeComparators comparatorsByType,private Map<java.lang.String,Comparator<?>> comparatorsForElementPropertyOrFieldNames,private org.assertj.core.internal.TypeComparators comparatorsForElementPropertyOrFieldTypes,protected org.assertj.core.internal.Iterables iterables
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/api/OptionalAssert.java
|
OptionalAssert
|
isPresent
|
class OptionalAssert<T> extends AbstractAssert<OptionalAssert<T>, Optional<T>> {
protected OptionalAssert(final Optional<T> actual) {
super(actual, OptionalAssert.class);
}
// visible for test
protected Optional<T> getActual() {
return actual;
}
/**
* Verifies that the actual {@link Optional} contains the given value.<br>
* <p>
* Example :
*
* <pre><code class='java'> Optional<String> optional = Optional.of("Test");
*
* assertThat(optional).contains("Test");</code></pre>
*
* @param value the value to look for in actual {@link Optional}.
* @return this {@link OptionalAssert} for assertions chaining.
*
* @throws AssertionError if the actual {@link Optional} is {@code null}.
* @throws AssertionError if the actual {@link Optional} contains nothing or does not have the given value.
*/
@SuppressWarnings("deprecation")
public OptionalAssert<T> contains(final Object value) {
isNotNull();
if (!actual.isPresent()) {
throw assertionError(shouldBePresentWithValue(value));
}
if (!areEqual(actual.get(), value)) {
throw assertionError(shouldBePresentWithValue(actual, value));
}
return this;
}
/**
* Verifies that the actual {@link Optional} contained instance is absent/null (ie. not {@link Optional#isPresent()}).<br>
* <p>
* Example :
*
* <pre><code class='java'> Optional<String> optional = Optional.absent();
*
* assertThat(optional).isAbsent();</code></pre>
*
* @return this {@link OptionalAssert} for assertions chaining.
*
* @throws AssertionError if the actual {@link Optional} is {@code null}.
* @throws AssertionError if the actual {@link Optional} contains a (non-null) instance.
*/
public OptionalAssert<T> isAbsent() {
isNotNull();
if (actual.isPresent()) {
throw assertionError(shouldBeAbsent(actual));
}
return this;
}
/**
* Verifies that the actual {@link Optional} contains a (non-null) instance.<br>
* <p>
* Example :
*
* <pre><code class='java'> Optional<String> optional = Optional.of("value");
*
* assertThat(optional).isPresent();</code></pre>
*
* @return this {@link OptionalAssert} for assertions chaining.
*
* @throws AssertionError if the actual {@link Optional} is {@code null}.
* @throws AssertionError if the actual {@link Optional} contains a null instance.
*/
public OptionalAssert<T> isPresent() {<FILL_FUNCTION_BODY>}
/**
* Chain assertion on the content of the {@link Optional}.
* <p>
* Example :
*
* <pre><code class='java'> Optional<Number> optional = Optional.of(12L);
*
* assertThat(optional).extractingValue().isInstanceOf(Long.class);</code></pre>
*
* @return a new {@link AbstractObjectAssert} for assertions chaining on the content of the Optional.
* @throws AssertionError if the actual {@link Optional} is {@code null}.
* @throws AssertionError if the actual {@link Optional} contains a null instance.
*/
public AbstractObjectAssert<?, T> extractingValue() {
isPresent();
T assertion = actual.get();
return assertThat(assertion);
}
/**
* Chain assertion on the content of the {@link Optional}.
* <p>
* Example :
*
* <pre><code class='java'> Optional<String> optional = Optional.of("Bill");
*
* assertThat(optional).extractingCharSequence().startsWith("Bi");</code></pre>
*
* @return a new {@link AbstractCharSequenceAssert} for assertions chaining on the content of the Optional.
* @throws AssertionError if the actual {@link Optional} is {@code null}.
* @throws AssertionError if the actual {@link Optional} contains a null instance.
*/
public AbstractCharSequenceAssert<?, ? extends CharSequence> extractingCharSequence() {
isPresent();
assertThat(actual.get()).isInstanceOf(CharSequence.class);
return assertThat((CharSequence) actual.get());
}
}
|
isNotNull();
if (!actual.isPresent()) {
throw assertionError(shouldBePresent(actual));
}
return this;
| 1,199
| 38
| 1,237
|
<methods>public ASSERT asInstanceOf(InstanceOfAssertFactory<?,ASSERT>) ,public AbstractListAssert<?,List<?>,java.lang.Object,ObjectAssert<java.lang.Object>> asList() ,public AbstractStringAssert<?> asString() ,public OptionalAssert<T> describedAs(org.assertj.core.description.Description) ,public java.lang.String descriptionText() ,public OptionalAssert<T> doesNotHave(Condition<? super Optional<T>>) ,public OptionalAssert<T> doesNotHaveSameClassAs(java.lang.Object) ,public OptionalAssert<T> doesNotHaveSameHashCodeAs(java.lang.Object) ,public OptionalAssert<T> doesNotHaveToString(java.lang.String) ,public transient OptionalAssert<T> doesNotHaveToString(java.lang.String, java.lang.Object[]) ,public boolean equals(java.lang.Object) ,public org.assertj.core.api.WritableAssertionInfo getWritableAssertionInfo() ,public OptionalAssert<T> has(Condition<? super Optional<T>>) ,public OptionalAssert<T> hasSameClassAs(java.lang.Object) ,public OptionalAssert<T> hasSameHashCodeAs(java.lang.Object) ,public OptionalAssert<T> hasToString(java.lang.String) ,public transient OptionalAssert<T> hasToString(java.lang.String, java.lang.Object[]) ,public int hashCode() ,public OptionalAssert<T> is(Condition<? super Optional<T>>) ,public OptionalAssert<T> isEqualTo(java.lang.Object) ,public OptionalAssert<T> isExactlyInstanceOf(Class<?>) ,public transient OptionalAssert<T> isIn(java.lang.Object[]) ,public OptionalAssert<T> isIn(Iterable<?>) ,public OptionalAssert<T> isInstanceOf(Class<?>) ,public transient OptionalAssert<T> isInstanceOfAny(Class<?>[]) ,public OptionalAssert<T> isInstanceOfSatisfying(Class<T>, Consumer<T>) ,public OptionalAssert<T> isNot(Condition<? super Optional<T>>) ,public OptionalAssert<T> isNotEqualTo(java.lang.Object) ,public OptionalAssert<T> isNotExactlyInstanceOf(Class<?>) ,public transient OptionalAssert<T> isNotIn(java.lang.Object[]) ,public OptionalAssert<T> isNotIn(Iterable<?>) ,public OptionalAssert<T> isNotInstanceOf(Class<?>) ,public transient OptionalAssert<T> isNotInstanceOfAny(Class<?>[]) ,public OptionalAssert<T> isNotNull() ,public transient OptionalAssert<T> isNotOfAnyClassIn(Class<?>[]) ,public OptionalAssert<T> isNotSameAs(java.lang.Object) ,public void isNull() ,public transient OptionalAssert<T> isOfAnyClassIn(Class<?>[]) ,public OptionalAssert<T> isSameAs(java.lang.Object) ,public OptionalAssert<T> matches(Predicate<? super Optional<T>>) ,public OptionalAssert<T> matches(Predicate<? super Optional<T>>, java.lang.String) ,public transient OptionalAssert<T> overridingErrorMessage(java.lang.String, java.lang.Object[]) ,public OptionalAssert<T> overridingErrorMessage(Supplier<java.lang.String>) ,public OptionalAssert<T> satisfies(Condition<? super Optional<T>>) ,public final transient OptionalAssert<T> satisfies(Consumer<? super Optional<T>>[]) ,public final transient OptionalAssert<T> satisfies(ThrowingConsumer<? super Optional<T>>[]) ,public final transient OptionalAssert<T> satisfiesAnyOf(Consumer<? super Optional<T>>[]) ,public final transient OptionalAssert<T> satisfiesAnyOf(ThrowingConsumer<? super Optional<T>>[]) ,public static void setCustomRepresentation(org.assertj.core.presentation.Representation) ,public static void setDescriptionConsumer(Consumer<org.assertj.core.description.Description>) ,public static void setPrintAssertionsDescription(boolean) ,public OptionalAssert<T> usingComparator(Comparator<? super Optional<T>>) ,public OptionalAssert<T> usingComparator(Comparator<? super Optional<T>>, java.lang.String) ,public OptionalAssert<T> usingDefaultComparator() ,public transient OptionalAssert<T> withFailMessage(java.lang.String, java.lang.Object[]) ,public OptionalAssert<T> withFailMessage(Supplier<java.lang.String>) ,public OptionalAssert<T> withRepresentation(org.assertj.core.presentation.Representation) ,public OptionalAssert<T> withThreadDumpOnError() <variables>private static final java.lang.String ORG_ASSERTJ,protected final non-sealed Optional<T> actual,org.assertj.core.error.AssertionErrorCreator assertionErrorCreator,org.assertj.core.internal.Conditions conditions,static org.assertj.core.presentation.Representation customRepresentation,private static Consumer<org.assertj.core.description.Description> descriptionConsumer,public org.assertj.core.api.WritableAssertionInfo info,protected final non-sealed OptionalAssert<T> myself,protected org.assertj.core.internal.Objects objects,static boolean printAssertionsDescription,public static boolean throwUnsupportedExceptionOnEquals
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/data/MapEntry.java
|
MapEntry
|
hashCode
|
class MapEntry<K, V> {
public final K key;
public final V value;
/**
* Creates a new {@link MapEntry}.
*
* @param <K> key type
* @param <V> value type
* @param key the key of the entry to create.
* @param value the value of the entry to create.
* @return the created {@code MapEntry}.
*/
public static <K, V> MapEntry<K, V> entry(K key, V value) {
return new MapEntry<>(key, value);
}
private MapEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
MapEntry<?, ?> other = (MapEntry<?, ?>) obj;
return areEqual(key, other.key) && areEqual(value, other.value);
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return String.format("%s[key=%s, value=%s]", getClass().getSimpleName(), quote(key), quote(value));
}
}
|
int result = 1;
result = HASH_CODE_PRIME * result + hashCodeFor(key);
result = HASH_CODE_PRIME * result + hashCodeFor(value);
return result;
| 375
| 55
| 430
|
<no_super_class>
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/MultisetShouldContainAtLeastTimes.java
|
MultisetShouldContainAtLeastTimes
|
shouldContainAtLeastTimes
|
class MultisetShouldContainAtLeastTimes extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldContainAtLeastTimes(final Multiset<?> actual, final Object expected,
final int expectedTimes, final int actualTimes) {<FILL_FUNCTION_BODY>}
private MultisetShouldContainAtLeastTimes(String format, Object... arguments) {
super(format, arguments);
}
}
|
return new MultisetShouldContainAtLeastTimes("%n" +
"Expecting:%n" +
" %s%n" +
"to contain:%n" +
" %s%n" +
"at least %s times but was found %s times.",
actual, expected, expectedTimes, actualTimes);
| 110
| 95
| 205
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/MultisetShouldContainAtMostTimes.java
|
MultisetShouldContainAtMostTimes
|
shouldContainAtMostTimes
|
class MultisetShouldContainAtMostTimes extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldContainAtMostTimes(final Multiset<?> actual, final Object expected,
final int expectedTimes, final int actualTimes) {<FILL_FUNCTION_BODY>}
private MultisetShouldContainAtMostTimes(String format, Object... arguments) {
super(format, arguments);
}
}
|
return new MultisetShouldContainAtMostTimes("%n" +
"Expecting:%n" +
" %s%n" +
"to contain:%n" +
" %s%n" +
"at most %s times but was found %s times.",
actual, expected, expectedTimes, actualTimes);
| 106
| 88
| 194
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/MultisetShouldContainTimes.java
|
MultisetShouldContainTimes
|
shouldContainTimes
|
class MultisetShouldContainTimes extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldContainTimes(final Multiset<?> actual, final Object expected,
final int expectedTimes, final int actualTimes) {<FILL_FUNCTION_BODY>}
private MultisetShouldContainTimes(String format, Object... arguments) {
super(format, arguments);
}
}
|
return new MultisetShouldContainTimes("%n" +
"Expecting:%n" +
" %s%n" +
"to contain:%n" +
" %s%n" +
"exactly %s times but was found %s times.",
actual, expected, expectedTimes, actualTimes);
| 100
| 86
| 186
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/OptionalShouldBeAbsent.java
|
OptionalShouldBeAbsent
|
shouldBeAbsent
|
class OptionalShouldBeAbsent extends BasicErrorMessageFactory {
public static <T> ErrorMessageFactory shouldBeAbsent(final Optional<T> actual) {<FILL_FUNCTION_BODY>}
private OptionalShouldBeAbsent(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new OptionalShouldBeAbsent("Expecting Optional to contain nothing (absent Optional) but contained %s",
actual.get());
| 83
| 36
| 119
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/OptionalShouldBePresent.java
|
OptionalShouldBePresent
|
shouldBePresent
|
class OptionalShouldBePresent extends BasicErrorMessageFactory {
public static <T> ErrorMessageFactory shouldBePresent(final Optional<T> actual) {<FILL_FUNCTION_BODY>}
private OptionalShouldBePresent(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new OptionalShouldBePresent(
"Expecting Optional to contain a non-null instance but contained nothing (absent Optional)",
actual);
| 80
| 38
| 118
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/OptionalShouldBePresentWithValue.java
|
OptionalShouldBePresentWithValue
|
shouldBePresentWithValue
|
class OptionalShouldBePresentWithValue extends BasicErrorMessageFactory {
public static <T> ErrorMessageFactory shouldBePresentWithValue(final Optional<T> actual, final Object value) {<FILL_FUNCTION_BODY>}
public static <T> ErrorMessageFactory shouldBePresentWithValue(final Object value) {
return new OptionalShouldBePresentWithValue(
"Expecting Optional to contain %s but contained nothing (absent Optional)",
value);
}
private OptionalShouldBePresentWithValue(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new OptionalShouldBePresentWithValue("%nExpecting Optional to contain value %n %s%n but contained %n %s",
value, actual.get());
| 149
| 45
| 194
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldBeClosedInTheLowerBound.java
|
RangeShouldBeClosedInTheLowerBound
|
shouldHaveClosedLowerBound
|
class RangeShouldBeClosedInTheLowerBound extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveClosedLowerBound(final Range<T> actual) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
public RangeShouldBeClosedInTheLowerBound(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldBeClosedInTheLowerBound(
"%nExpecting:%n %s%nto be closed in the lower bound but was opened", actual);
| 167
| 46
| 213
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldBeClosedInTheUpperBound.java
|
RangeShouldBeClosedInTheUpperBound
|
shouldHaveClosedUpperBound
|
class RangeShouldBeClosedInTheUpperBound extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveClosedUpperBound(final Range<T> actual) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
public RangeShouldBeClosedInTheUpperBound(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldBeClosedInTheUpperBound(
"%nExpecting:%n %s%nto be closed in the upper bound but was opened", actual);
| 170
| 47
| 217
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldBeOpenedInTheLowerBound.java
|
RangeShouldBeOpenedInTheLowerBound
|
shouldHaveOpenedLowerBound
|
class RangeShouldBeOpenedInTheLowerBound extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveOpenedLowerBound(final Range<T> actual) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
public RangeShouldBeOpenedInTheLowerBound(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldBeOpenedInTheLowerBound(
"%nExpecting:%n %s%nto be opened in the lower bound but was closed", actual);
| 167
| 46
| 213
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldBeOpenedInTheUpperBound.java
|
RangeShouldBeOpenedInTheUpperBound
|
shouldHaveOpenedUpperBound
|
class RangeShouldBeOpenedInTheUpperBound extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveOpenedUpperBound(final Range<T> actual) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
public RangeShouldBeOpenedInTheUpperBound(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldBeOpenedInTheUpperBound(
"%nExpecting:%n %s%nto be opened in the upper bound but was closed", actual);
| 170
| 47
| 217
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldHaveLowerEndpointEqual.java
|
RangeShouldHaveLowerEndpointEqual
|
shouldHaveEqualLowerEndpoint
|
class RangeShouldHaveLowerEndpointEqual extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveEqualLowerEndpoint(final Range<T> actual,
final Object value) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
private RangeShouldHaveLowerEndpointEqual(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldHaveLowerEndpointEqual("%n" +
"Expecting:%n" +
" %s%n" +
"to have lower endpoint equal to:%n" +
" %s%n" +
"but was:%n" +
" %s",
actual, value, actual.lowerEndpoint());
| 167
| 97
| 264
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/RangeShouldHaveUpperEndpointEqual.java
|
RangeShouldHaveUpperEndpointEqual
|
shouldHaveEqualUpperEndpoint
|
class RangeShouldHaveUpperEndpointEqual extends BasicErrorMessageFactory {
public static <T extends Comparable<T>> ErrorMessageFactory shouldHaveEqualUpperEndpoint(final Range<T> actual,
final Object value) {<FILL_FUNCTION_BODY>}
/**
* Creates a new <code>{@link org.assertj.core.error.BasicErrorMessageFactory}</code>.
*
* @param format the format string.
* @param arguments arguments referenced by the format specifiers in the format string.
*/
private RangeShouldHaveUpperEndpointEqual(final String format, final Object... arguments) {
super(format, arguments);
}
}
|
return new RangeShouldHaveUpperEndpointEqual("%n" +
"Expecting:%n" +
" %s%n" +
"to have upper endpoint equal to:%n" +
" %s%n" +
"but was:%n" +
" %s",
actual, value, actual.upperEndpoint());
| 170
| 98
| 268
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/ShouldContainKeys.java
|
ShouldContainKeys
|
shouldContainKeys
|
class ShouldContainKeys extends BasicErrorMessageFactory {
private ShouldContainKeys(Object actual, Object key) {
super("%nExpecting:%n %s%nto contain key:%n %s", actual, key);
}
private ShouldContainKeys(Object actual, Object[] keys, Set<?> keysNotFound) {
super("%nExpecting:%n %s%nto contain keys:%n %s%nbut could not find:%n %s", actual, keys, keysNotFound);
}
/**
* Creates a new <code>{@link ShouldContainKeys}</code>.
*
* @param actual the actual value in the failed assertion.
* @param keys the expected keys.
* @param keysNotFound the missing keys.
* @return the created {@code ErrorMessageFactory}.
*/
public static ErrorMessageFactory shouldContainKeys(Object actual, Object[] keys, Set<?> keysNotFound) {<FILL_FUNCTION_BODY>}
}
|
return keys.length == 1 ? new ShouldContainKeys(actual, keys[0]) : new ShouldContainKeys(actual, keys, keysNotFound);
| 255
| 38
| 293
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/ShouldContainValues.java
|
ShouldContainValues
|
shouldContainValues
|
class ShouldContainValues extends BasicErrorMessageFactory {
public static ErrorMessageFactory shouldContainValues(Object actual, Object[] values, Set<?> valuesNotFound) {<FILL_FUNCTION_BODY>}
private ShouldContainValues(Object actual, Object value) {
super("%nExpecting:%n %s%nto contain value:%n %s", actual, value);
}
private ShouldContainValues(Object actual, Object[] values, Set<?> valuesNotFound) {
super("%nExpecting:%n %s%nto contain values:%n %s%nbut could not find:%n %s", actual, values, valuesNotFound);
}
}
|
return values.length == 1 ? new ShouldContainValues(actual, values[0])
: new ShouldContainValues(actual, values,
valuesNotFound);
| 175
| 42
| 217
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/TableShouldContainColumns.java
|
TableShouldContainColumns
|
tableShouldContainColumns
|
class TableShouldContainColumns extends BasicErrorMessageFactory {
public static ErrorMessageFactory tableShouldContainColumns(Object actual, Object[] columns, Set<?> columnsNotFound) {<FILL_FUNCTION_BODY>}
private TableShouldContainColumns(Object actual, Object row) {
super("%nExpecting:%n %s%nto contain column:%n %s", actual, row);
}
public TableShouldContainColumns(Object actual, Object[] rows, Set<?> columnsNotFound) {
super("%nExpecting:%n %s%nto contain columns:%n %s%nbut could not find:%n %s", actual, rows, columnsNotFound);
}
}
|
return columns.length == 1 ? new TableShouldContainColumns(actual, columns[0])
: new TableShouldContainColumns(actual, columns,
columnsNotFound);
| 179
| 44
| 223
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
assertj_assertj
|
assertj/assertj-guava/src/main/java/org/assertj/guava/error/TableShouldContainRows.java
|
TableShouldContainRows
|
tableShouldContainRows
|
class TableShouldContainRows extends BasicErrorMessageFactory {
public static ErrorMessageFactory tableShouldContainRows(Object actual, Object[] rows, Set<?> rowsNotFound) {<FILL_FUNCTION_BODY>}
private TableShouldContainRows(Object actual, Object row) {
super("%nExpecting:%n %s%nto contain row:%n %s", actual, row);
}
public TableShouldContainRows(Object actual, Object[] rows, Set<?> rowsNotFound) {
super("%nExpecting:%n %s%nto contain rows:%n %s%nbut could not find:%n %s", actual, rows, rowsNotFound);
}
}
|
return rows.length == 1 ? new TableShouldContainRows(actual, rows[0])
: new TableShouldContainRows(actual, rows,
rowsNotFound);
| 179
| 45
| 224
|
<methods>public transient void <init>(java.lang.String, java.lang.Object[]) ,public java.lang.String create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation) ,public java.lang.String create(org.assertj.core.description.Description) ,public java.lang.String create() ,public boolean equals(java.lang.Object) ,public int hashCode() ,public java.lang.String toString() <variables>protected final non-sealed java.lang.Object[] arguments,protected final non-sealed java.lang.String format,org.assertj.core.error.MessageFormatter formatter
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/ClientStats.java
|
ClientStats
|
equals
|
class ClientStats {
private final Map<String, HostStats> statsPerHost;
public ClientStats(Map<String, HostStats> statsPerHost) {
this.statsPerHost = Collections.unmodifiableMap(statsPerHost);
}
/**
* @return A map from hostname to statistics on that host's connections.
* The returned map is unmodifiable.
*/
public Map<String, HostStats> getStatsPerHost() {
return statsPerHost;
}
/**
* @return The sum of {@link #getTotalActiveConnectionCount()} and {@link #getTotalIdleConnectionCount()},
* a long representing the total number of connections in the connection pool.
*/
public long getTotalConnectionCount() {
return statsPerHost
.values()
.stream()
.mapToLong(HostStats::getHostConnectionCount)
.sum();
}
/**
* @return A long representing the number of active connections in the connection pool.
*/
public long getTotalActiveConnectionCount() {
return statsPerHost
.values()
.stream()
.mapToLong(HostStats::getHostActiveConnectionCount)
.sum();
}
/**
* @return A long representing the number of idle connections in the connection pool.
*/
public long getTotalIdleConnectionCount() {
return statsPerHost
.values()
.stream()
.mapToLong(HostStats::getHostIdleConnectionCount)
.sum();
}
@Override
public String toString() {
return "There are " + getTotalConnectionCount() +
" total connections, " + getTotalActiveConnectionCount() +
" are active and " + getTotalIdleConnectionCount() + " are idle.";
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hashCode(statsPerHost);
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ClientStats that = (ClientStats) o;
return Objects.equals(statsPerHost, that.statsPerHost);
| 507
| 78
| 585
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/DefaultRequest.java
|
DefaultRequest
|
getQueryParams
|
class DefaultRequest implements Request {
public final @Nullable ProxyServer proxyServer;
private final String method;
private final Uri uri;
private final @Nullable InetAddress address;
private final @Nullable InetAddress localAddress;
private final HttpHeaders headers;
private final List<Cookie> cookies;
private final byte @Nullable [] byteData;
private final @Nullable List<byte[]> compositeByteData;
private final @Nullable String stringData;
private final @Nullable ByteBuffer byteBufferData;
private final @Nullable ByteBuf byteBufData;
private final @Nullable InputStream streamData;
private final @Nullable BodyGenerator bodyGenerator;
private final List<Param> formParams;
private final List<Part> bodyParts;
private final @Nullable String virtualHost;
private final @Nullable Realm realm;
private final @Nullable File file;
private final @Nullable Boolean followRedirect;
private final Duration requestTimeout;
private final Duration readTimeout;
private final long rangeOffset;
private final @Nullable Charset charset;
private final ChannelPoolPartitioning channelPoolPartitioning;
private final NameResolver<InetAddress> nameResolver;
// lazily loaded
private @Nullable List<Param> queryParams;
public DefaultRequest(String method,
Uri uri,
@Nullable InetAddress address,
@Nullable InetAddress localAddress,
HttpHeaders headers,
List<Cookie> cookies,
byte @Nullable [] byteData,
@Nullable List<byte[]> compositeByteData,
@Nullable String stringData,
@Nullable ByteBuffer byteBufferData,
@Nullable ByteBuf byteBufData,
@Nullable InputStream streamData,
@Nullable BodyGenerator bodyGenerator,
List<Param> formParams,
List<Part> bodyParts,
@Nullable String virtualHost,
@Nullable ProxyServer proxyServer,
@Nullable Realm realm,
@Nullable File file,
@Nullable Boolean followRedirect,
@Nullable Duration requestTimeout,
@Nullable Duration readTimeout,
long rangeOffset,
@Nullable Charset charset,
ChannelPoolPartitioning channelPoolPartitioning,
NameResolver<InetAddress> nameResolver) {
this.method = method;
this.uri = uri;
this.address = address;
this.localAddress = localAddress;
this.headers = headers;
this.cookies = cookies;
this.byteData = byteData;
this.compositeByteData = compositeByteData;
this.stringData = stringData;
this.byteBufferData = byteBufferData;
this.byteBufData = byteBufData;
this.streamData = streamData;
this.bodyGenerator = bodyGenerator;
this.formParams = formParams;
this.bodyParts = bodyParts;
this.virtualHost = virtualHost;
this.proxyServer = proxyServer;
this.realm = realm;
this.file = file;
this.followRedirect = followRedirect;
this.requestTimeout = requestTimeout == null ? Duration.ZERO : requestTimeout;
this.readTimeout = readTimeout == null ? Duration.ZERO : readTimeout;
this.rangeOffset = rangeOffset;
this.charset = charset;
this.channelPoolPartitioning = channelPoolPartitioning;
this.nameResolver = nameResolver;
}
@Override
public String getUrl() {
return uri.toUrl();
}
@Override
public String getMethod() {
return method;
}
@Override
public Uri getUri() {
return uri;
}
@Override
public @Nullable InetAddress getAddress() {
return address;
}
@Override
public @Nullable InetAddress getLocalAddress() {
return localAddress;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public List<Cookie> getCookies() {
return cookies;
}
@Override
public byte @Nullable [] getByteData() {
return byteData;
}
@Override
public @Nullable List<byte[]> getCompositeByteData() {
return compositeByteData;
}
@Override
public @Nullable String getStringData() {
return stringData;
}
@Override
public @Nullable ByteBuffer getByteBufferData() {
return byteBufferData;
}
@Override
public @Nullable ByteBuf getByteBufData() {
return byteBufData;
}
@Override
public @Nullable InputStream getStreamData() {
return streamData;
}
@Override
public @Nullable BodyGenerator getBodyGenerator() {
return bodyGenerator;
}
@Override
public List<Param> getFormParams() {
return formParams;
}
@Override
public List<Part> getBodyParts() {
return bodyParts;
}
@Override
public @Nullable String getVirtualHost() {
return virtualHost;
}
@Override
public @Nullable ProxyServer getProxyServer() {
return proxyServer;
}
@Override
public @Nullable Realm getRealm() {
return realm;
}
@Override
public @Nullable File getFile() {
return file;
}
@Override
public @Nullable Boolean getFollowRedirect() {
return followRedirect;
}
@Override
public Duration getRequestTimeout() {
return requestTimeout;
}
@Override
public Duration getReadTimeout() {
return readTimeout;
}
@Override
public long getRangeOffset() {
return rangeOffset;
}
@Override
public @Nullable Charset getCharset() {
return charset;
}
@Override
public ChannelPoolPartitioning getChannelPoolPartitioning() {
return channelPoolPartitioning;
}
@Override
public NameResolver<InetAddress> getNameResolver() {
return nameResolver;
}
@Override
public List<Param> getQueryParams() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(getUrl());
sb.append('\t');
sb.append(method);
sb.append("\theaders:");
if (!headers.isEmpty()) {
for (Map.Entry<String, String> header : headers) {
sb.append('\t');
sb.append(header.getKey());
sb.append(':');
sb.append(header.getValue());
}
}
if (isNonEmpty(formParams)) {
sb.append("\tformParams:");
for (Param param : formParams) {
sb.append('\t');
sb.append(param.getName());
sb.append(':');
sb.append(param.getValue());
}
}
return sb.toString();
}
}
|
// lazy load
if (queryParams == null) {
if (isNonEmpty(uri.getQuery())) {
queryParams = new ArrayList<>(1);
for (String queryStringParam : uri.getQuery().split("&")) {
int pos = queryStringParam.indexOf('=');
if (pos <= 0) {
queryParams.add(new Param(queryStringParam, null));
} else {
queryParams.add(new Param(queryStringParam.substring(0, pos), queryStringParam.substring(pos + 1)));
}
}
} else {
queryParams = Collections.emptyList();
}
}
return queryParams;
| 1,766
| 173
| 1,939
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/Dsl.java
|
Dsl
|
realm
|
class Dsl {
private Dsl() {
}
// /////////// Client ////////////////
public static AsyncHttpClient asyncHttpClient() {
return new DefaultAsyncHttpClient();
}
public static AsyncHttpClient asyncHttpClient(DefaultAsyncHttpClientConfig.Builder configBuilder) {
return new DefaultAsyncHttpClient(configBuilder.build());
}
public static AsyncHttpClient asyncHttpClient(AsyncHttpClientConfig config) {
return new DefaultAsyncHttpClient(config);
}
// /////////// Request ////////////////
public static RequestBuilder get(String url) {
return request(GET, url);
}
public static RequestBuilder put(String url) {
return request(PUT, url);
}
public static RequestBuilder post(String url) {
return request(POST, url);
}
public static RequestBuilder delete(String url) {
return request(DELETE, url);
}
public static RequestBuilder head(String url) {
return request(HEAD, url);
}
public static RequestBuilder options(String url) {
return request(OPTIONS, url);
}
public static RequestBuilder patch(String url) {
return request(PATCH, url);
}
public static RequestBuilder trace(String url) {
return request(TRACE, url);
}
public static RequestBuilder request(String method, String url) {
return new RequestBuilder(method).setUrl(url);
}
// /////////// ProxyServer ////////////////
public static ProxyServer.Builder proxyServer(String host, int port) {
return new ProxyServer.Builder(host, port);
}
// /////////// Config ////////////////
public static DefaultAsyncHttpClientConfig.Builder config() {
return new DefaultAsyncHttpClientConfig.Builder();
}
// /////////// Realm ////////////////
public static Realm.Builder realm(Realm prototype) {<FILL_FUNCTION_BODY>}
public static Realm.Builder realm(AuthScheme scheme, String principal, String password) {
return new Realm.Builder(principal, password).setScheme(scheme);
}
public static Realm.Builder basicAuthRealm(String principal, String password) {
return realm(AuthScheme.BASIC, principal, password);
}
public static Realm.Builder digestAuthRealm(String principal, String password) {
return realm(AuthScheme.DIGEST, principal, password);
}
public static Realm.Builder ntlmAuthRealm(String principal, String password) {
return realm(AuthScheme.NTLM, principal, password);
}
}
|
return new Realm.Builder(prototype.getPrincipal(), prototype.getPassword())
.setRealmName(prototype.getRealmName())
.setAlgorithm(prototype.getAlgorithm())
.setNc(prototype.getNc())
.setNonce(prototype.getNonce())
.setCharset(prototype.getCharset())
.setOpaque(prototype.getOpaque())
.setQop(prototype.getQop())
.setScheme(prototype.getScheme())
.setUri(prototype.getUri())
.setUsePreemptiveAuth(prototype.isUsePreemptiveAuth())
.setNtlmDomain(prototype.getNtlmDomain())
.setNtlmHost(prototype.getNtlmHost())
.setUseAbsoluteURI(prototype.isUseAbsoluteURI())
.setOmitQuery(prototype.isOmitQuery())
.setServicePrincipalName(prototype.getServicePrincipalName())
.setUseCanonicalHostname(prototype.isUseCanonicalHostname())
.setCustomLoginConfig(prototype.getCustomLoginConfig())
.setLoginContextName(prototype.getLoginContextName());
| 679
| 293
| 972
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/HostStats.java
|
HostStats
|
equals
|
class HostStats {
private final long activeConnectionCount;
private final long idleConnectionCount;
public HostStats(long activeConnectionCount, long idleConnectionCount) {
this.activeConnectionCount = activeConnectionCount;
this.idleConnectionCount = idleConnectionCount;
}
/**
* @return The sum of {@link #getHostActiveConnectionCount()} and {@link #getHostIdleConnectionCount()},
* a long representing the total number of connections to this host.
*/
public long getHostConnectionCount() {
return activeConnectionCount + idleConnectionCount;
}
/**
* @return A long representing the number of active connections to the host.
*/
public long getHostActiveConnectionCount() {
return activeConnectionCount;
}
/**
* @return A long representing the number of idle connections in the connection pool.
*/
public long getHostIdleConnectionCount() {
return idleConnectionCount;
}
@Override
public String toString() {
return "There are " + getHostConnectionCount() +
" total connections, " + getHostActiveConnectionCount() +
" are active and " + getHostIdleConnectionCount() + " are idle.";
}
@Override
public boolean equals(final Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
return Objects.hash(activeConnectionCount, idleConnectionCount);
}
}
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final HostStats hostStats = (HostStats) o;
return activeConnectionCount == hostStats.activeConnectionCount && idleConnectionCount == hostStats.idleConnectionCount;
| 366
| 87
| 453
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/Param.java
|
Param
|
map2ParamList
|
class Param {
private final String name;
private final @Nullable String value;
public Param(String name, @Nullable String value) {
this.name = name;
this.value = value;
}
public static @Nullable List<Param> map2ParamList(Map<String, List<String>> map) {<FILL_FUNCTION_BODY>}
public String getName() {
return name;
}
public @Nullable String getValue() {
return value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode());
result = prime * result + (value == null ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Param)) {
return false;
}
Param other = (Param) obj;
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (value == null) {
return other.value == null;
} else {
return value.equals(other.value);
}
}
}
|
if (map == null) {
return null;
}
List<Param> params = new ArrayList<>(map.size());
for (Map.Entry<String, List<String>> entries : map.entrySet()) {
String name = entries.getKey();
for (String value : entries.getValue()) {
params.add(new Param(name, value));
}
}
return params;
| 384
| 106
| 490
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/channel/DefaultKeepAliveStrategy.java
|
DefaultKeepAliveStrategy
|
keepAlive
|
class DefaultKeepAliveStrategy implements KeepAliveStrategy {
/**
* Implemented in accordance with RFC 7230 section 6.1 <a href="https://tools.ietf.org/html/rfc7230#section-6.1">...</a>
*/
@Override
public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest, HttpRequest request, HttpResponse response) {<FILL_FUNCTION_BODY>}
}
|
return HttpUtil.isKeepAlive(response) &&
HttpUtil.isKeepAlive(request) &&
// support non-standard Proxy-Connection
!response.headers().contains("Proxy-Connection", CLOSE, true);
| 123
| 60
| 183
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/config/AsyncHttpClientConfigHelper.java
|
Config
|
parsePropertiesFile
|
class Config {
public static final String DEFAULT_AHC_PROPERTIES = "ahc-default.properties";
public static final String CUSTOM_AHC_PROPERTIES = "ahc.properties";
private final ConcurrentHashMap<String, String> propsCache = new ConcurrentHashMap<>();
private final Properties defaultProperties = parsePropertiesFile(DEFAULT_AHC_PROPERTIES, true);
private volatile Properties customProperties = parsePropertiesFile(CUSTOM_AHC_PROPERTIES, false);
public void reload() {
customProperties = parsePropertiesFile(CUSTOM_AHC_PROPERTIES, false);
propsCache.clear();
}
/**
* Parse a property file.
*
* @param file the file to parse
* @param required if true, the file must be present
* @return the parsed properties
* @throws RuntimeException if the file is required and not present or if the file can't be parsed
*/
private Properties parsePropertiesFile(String file, boolean required) {<FILL_FUNCTION_BODY>}
public String getString(String key) {
return propsCache.computeIfAbsent(key, k -> {
String value = System.getProperty(k);
if (value == null) {
value = customProperties.getProperty(k);
}
if (value == null) {
value = defaultProperties.getProperty(k);
}
return value;
});
}
@Nullable
public String[] getStringArray(String key) {
String s = getString(key);
s = s.trim();
if (s.isEmpty()) {
return null;
}
String[] rawArray = s.split(",");
String[] array = new String[rawArray.length];
for (int i = 0; i < rawArray.length; i++) {
array[i] = rawArray[i].trim();
}
return array;
}
public int getInt(String key) {
return Integer.parseInt(getString(key));
}
public boolean getBoolean(String key) {
return Boolean.parseBoolean(getString(key));
}
public Duration getDuration(String key) {
return Duration.parse(getString(key));
}
}
|
Properties props = new Properties();
try (InputStream is = getClass().getResourceAsStream(file)) {
if (is != null) {
try {
props.load(is);
} catch (IOException e) {
throw new IllegalArgumentException("Can't parse config file " + file, e);
}
} else if (required) {
throw new IllegalArgumentException("Can't locate config file " + file);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return props;
| 577
| 139
| 716
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/filter/ReleasePermitOnComplete.java
|
ReleasePermitOnComplete
|
allInterfaces
|
class ReleasePermitOnComplete {
private ReleasePermitOnComplete() {
// Prevent outside initialization
}
/**
* Wrap handler to release the permit of the semaphore on {@link AsyncHandler#onCompleted()}.
*
* @param handler the handler to be wrapped
* @param available the Semaphore to be released when the wrapped handler is completed
* @param <T> the handler result type
* @return the wrapped handler
*/
@SuppressWarnings("unchecked")
public static <T> AsyncHandler<T> wrap(final AsyncHandler<T> handler, final Semaphore available) {
Class<?> handlerClass = handler.getClass();
ClassLoader classLoader = handlerClass.getClassLoader();
Class<?>[] interfaces = allInterfaces(handlerClass);
return (AsyncHandler<T>) Proxy.newProxyInstance(classLoader, interfaces, (proxy, method, args) -> {
try {
return method.invoke(handler, args);
} finally {
switch (method.getName()) {
case "onCompleted":
case "onThrowable":
available.release();
default:
}
}
});
}
/**
* Extract all interfaces of a class.
*
* @param handlerClass the handler class
* @return all interfaces implemented by this class
*/
private static Class<?>[] allInterfaces(Class<?> handlerClass) {<FILL_FUNCTION_BODY>}
}
|
Set<Class<?>> allInterfaces = new HashSet<>();
for (Class<?> clazz = handlerClass; clazz != null; clazz = clazz.getSuperclass()) {
Collections.addAll(allInterfaces, clazz.getInterfaces());
}
return allInterfaces.toArray(new Class[0]);
| 382
| 88
| 470
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/filter/ThrottleRequestFilter.java
|
ThrottleRequestFilter
|
filter
|
class ThrottleRequestFilter implements RequestFilter {
private static final Logger logger = LoggerFactory.getLogger(ThrottleRequestFilter.class);
private final Semaphore available;
private final int maxWait;
public ThrottleRequestFilter(int maxConnections) {
this(maxConnections, Integer.MAX_VALUE);
}
public ThrottleRequestFilter(int maxConnections, int maxWait) {
this(maxConnections, maxWait, false);
}
public ThrottleRequestFilter(int maxConnections, int maxWait, boolean fair) {
this.maxWait = maxWait;
available = new Semaphore(maxConnections, fair);
}
@Override
public <T> FilterContext<T> filter(FilterContext<T> ctx) throws FilterException {<FILL_FUNCTION_BODY>}
}
|
try {
if (logger.isDebugEnabled()) {
logger.debug("Current Throttling Status {}", available.availablePermits());
}
if (!available.tryAcquire(maxWait, TimeUnit.MILLISECONDS)) {
throw new FilterException(String.format("No slot available for processing Request %s with AsyncHandler %s", ctx.getRequest(), ctx.getAsyncHandler()));
}
} catch (InterruptedException e) {
throw new FilterException(String.format("Interrupted Request %s with AsyncHandler %s", ctx.getRequest(), ctx.getAsyncHandler()));
}
return new FilterContext.FilterContextBuilder<>(ctx)
.asyncHandler(ReleasePermitOnComplete.wrap(ctx.getAsyncHandler(), available))
.build();
| 220
| 194
| 414
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/handler/BodyDeferringAsyncHandler.java
|
BodyDeferringInputStream
|
close
|
class BodyDeferringInputStream extends FilterInputStream {
private final Future<Response> future;
private final BodyDeferringAsyncHandler bdah;
public BodyDeferringInputStream(final Future<Response> future, final BodyDeferringAsyncHandler bdah, final InputStream in) {
super(in);
this.future = future;
this.bdah = bdah;
}
/**
* Closes the input stream, and "joins" (wait for complete execution
* together with potential exception thrown) of the async request.
*/
@Override
public void close() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Delegates to {@link BodyDeferringAsyncHandler#getResponse()}. Will
* blocks as long as headers arrives only. Might return
* {@code null}. See
* {@link BodyDeferringAsyncHandler#getResponse()} method for details.
*
* @return a {@link Response}
* @throws InterruptedException if the latch is interrupted
* @throws IOException if the handler completed with an exception
*/
public @Nullable Response getAsapResponse() throws InterruptedException, IOException {
return bdah.getResponse();
}
/**
* Delegates to {@code Future$lt;Response>#get()} method. Will block
* as long as complete response arrives.
*
* @return a {@link Response}
* @throws ExecutionException if the computation threw an exception
* @throws InterruptedException if the current thread was interrupted
*/
public Response getLastResponse() throws InterruptedException, ExecutionException {
return future.get();
}
}
|
// close
super.close();
// "join" async request
try {
getLastResponse();
} catch (ExecutionException e) {
throw new IOException(e.getMessage(), e.getCause());
} catch (InterruptedException e) {
throw new IOException(e.getMessage(), e);
}
| 412
| 83
| 495
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/handler/TransferCompletionHandler.java
|
TransferCompletionHandler
|
fireOnHeadersSent
|
class TransferCompletionHandler extends AsyncCompletionHandlerBase {
private static final Logger logger = LoggerFactory.getLogger(TransferCompletionHandler.class);
private final ConcurrentLinkedQueue<TransferListener> listeners = new ConcurrentLinkedQueue<>();
private final boolean accumulateResponseBytes;
private @Nullable HttpHeaders headers;
/**
* Create a TransferCompletionHandler that will not accumulate bytes. The resulting {@link Response#getResponseBody()},
* {@link Response#getResponseBodyAsStream()} will throw an IllegalStateException if called.
*/
public TransferCompletionHandler() {
this(false);
}
/**
* Create a TransferCompletionHandler that can or cannot accumulate bytes and make it available when {@link Response#getResponseBody()} get called. The
* default is false.
*
* @param accumulateResponseBytes true to accumulates bytes in memory.
*/
public TransferCompletionHandler(boolean accumulateResponseBytes) {
this.accumulateResponseBytes = accumulateResponseBytes;
}
public TransferCompletionHandler addTransferListener(TransferListener t) {
listeners.offer(t);
return this;
}
public TransferCompletionHandler removeTransferListener(TransferListener t) {
listeners.remove(t);
return this;
}
public void headers(HttpHeaders headers) {
this.headers = headers;
}
@Override
public State onHeadersReceived(final HttpHeaders headers) throws Exception {
fireOnHeaderReceived(headers);
return super.onHeadersReceived(headers);
}
@Override
public State onTrailingHeadersReceived(HttpHeaders headers) throws Exception {
fireOnHeaderReceived(headers);
return super.onHeadersReceived(headers);
}
@Override
public State onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
State s = State.CONTINUE;
if (accumulateResponseBytes) {
s = super.onBodyPartReceived(content);
}
fireOnBytesReceived(content.getBodyPartBytes());
return s;
}
@Override
public @Nullable Response onCompleted(@Nullable Response response) throws Exception {
fireOnEnd();
return response;
}
@Override
public State onHeadersWritten() {
if (headers != null) {
fireOnHeadersSent(headers);
}
return State.CONTINUE;
}
@Override
public State onContentWriteProgress(long amount, long current, long total) {
fireOnBytesSent(amount, current, total);
return State.CONTINUE;
}
@Override
public void onThrowable(Throwable t) {
fireOnThrowable(t);
}
private void fireOnHeadersSent(HttpHeaders headers) {<FILL_FUNCTION_BODY>}
private void fireOnHeaderReceived(HttpHeaders headers) {
for (TransferListener l : listeners) {
try {
l.onResponseHeadersReceived(headers);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnEnd() {
for (TransferListener l : listeners) {
try {
l.onRequestResponseCompleted();
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnBytesReceived(byte[] b) {
for (TransferListener l : listeners) {
try {
l.onBytesReceived(b);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnBytesSent(long amount, long current, long total) {
for (TransferListener l : listeners) {
try {
l.onBytesSent(amount, current, total);
} catch (Throwable t) {
l.onThrowable(t);
}
}
}
private void fireOnThrowable(Throwable t) {
for (TransferListener l : listeners) {
try {
l.onThrowable(t);
} catch (Throwable t2) {
logger.warn("onThrowable", t2);
}
}
}
}
|
for (TransferListener l : listeners) {
try {
l.onRequestHeadersSent(headers);
} catch (Throwable t) {
l.onThrowable(t);
}
}
| 1,090
| 56
| 1,146
|
<methods>public non-sealed void <init>() ,public org.asynchttpclient.Response onCompleted(org.asynchttpclient.Response) throws java.lang.Exception<variables>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/handler/resumable/PropertiesBasedResumableProcessor.java
|
PropertiesBasedResumableProcessor
|
load
|
class PropertiesBasedResumableProcessor implements ResumableAsyncHandler.ResumableProcessor {
private static final Logger log = LoggerFactory.getLogger(PropertiesBasedResumableProcessor.class);
private static final File TMP = new File(System.getProperty("java.io.tmpdir"), "ahc");
private static final String storeName = "ResumableAsyncHandler.properties";
private final ConcurrentHashMap<String, Long> properties = new ConcurrentHashMap<>();
private static String append(Map.Entry<String, Long> e) {
return e.getKey() + '=' + e.getValue() + '\n';
}
@Override
public void put(String url, long transferredBytes) {
properties.put(url, transferredBytes);
}
@Override
public void remove(String uri) {
if (uri != null) {
properties.remove(uri);
}
}
@Override
public void save(Map<String, Long> map) {
log.debug("Saving current download state {}", properties);
OutputStream os = null;
try {
if (!TMP.exists() && !TMP.mkdirs()) {
throw new IllegalStateException("Unable to create directory: " + TMP.getAbsolutePath());
}
File f = new File(TMP, storeName);
if (!f.exists() && !f.createNewFile()) {
throw new IllegalStateException("Unable to create temp file: " + f.getAbsolutePath());
}
if (!f.canWrite()) {
throw new IllegalStateException();
}
os = Files.newOutputStream(f.toPath());
for (Map.Entry<String, Long> e : properties.entrySet()) {
os.write(append(e).getBytes(UTF_8));
}
os.flush();
} catch (Throwable e) {
log.warn(e.getMessage(), e);
} finally {
closeSilently(os);
}
}
@Override
public Map<String, Long> load() {<FILL_FUNCTION_BODY>}
}
|
Scanner scan = null;
try {
scan = new Scanner(new File(TMP, storeName), UTF_8);
scan.useDelimiter("[=\n]");
String key;
String value;
while (scan.hasNext()) {
key = scan.next().trim();
value = scan.next().trim();
properties.put(key, Long.valueOf(value));
}
log.debug("Loading previous download state {}", properties);
} catch (FileNotFoundException ex) {
log.debug("Missing {}", storeName);
} catch (Throwable ex) {
// Survive any exceptions
log.warn(ex.getMessage(), ex);
} finally {
if (scan != null) {
scan.close();
}
}
return Collections.unmodifiableMap(properties);
| 535
| 218
| 753
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableIOExceptionFilter.java
|
ResumableIOExceptionFilter
|
filter
|
class ResumableIOExceptionFilter implements IOExceptionFilter {
@Override
public <T> FilterContext<T> filter(FilterContext<T> ctx) {<FILL_FUNCTION_BODY>}
}
|
if (ctx.getIOException() != null && ctx.getAsyncHandler() instanceof ResumableAsyncHandler) {
Request request = ((ResumableAsyncHandler) ctx.getAsyncHandler()).adjustRequestRange(ctx.getRequest());
return new FilterContext.FilterContextBuilder<>(ctx).request(request).replayRequest(true).build();
}
return ctx;
| 51
| 92
| 143
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/handler/resumable/ResumableRandomAccessFileListener.java
|
ResumableRandomAccessFileListener
|
length
|
class ResumableRandomAccessFileListener implements ResumableListener {
private final RandomAccessFile file;
public ResumableRandomAccessFileListener(RandomAccessFile file) {
this.file = file;
}
/**
* This method uses the last valid bytes written on disk to position a {@link RandomAccessFile}, allowing
* resumable file download.
*
* @param buffer a {@link ByteBuffer}
* @throws IOException exception while writing into the file
*/
@Override
public void onBytesReceived(ByteBuffer buffer) throws IOException {
file.seek(file.length());
if (buffer.hasArray()) {
file.write(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
} else { // if the buffer is direct or backed by a String...
byte[] b = new byte[buffer.remaining()];
int pos = buffer.position();
buffer.get(b);
buffer.position(pos);
file.write(b);
}
}
@Override
public void onAllBytesReceived() {
closeSilently(file);
}
@Override
public long length() {<FILL_FUNCTION_BODY>}
}
|
try {
return file.length();
} catch (IOException e) {
return -1;
}
| 307
| 32
| 339
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/NettyResponse.java
|
NettyResponse
|
buildCookies
|
class NettyResponse implements Response {
private final List<HttpResponseBodyPart> bodyParts;
private final HttpHeaders headers;
private final HttpResponseStatus status;
private List<Cookie> cookies;
public NettyResponse(HttpResponseStatus status,
HttpHeaders headers,
List<HttpResponseBodyPart> bodyParts) {
this.bodyParts = bodyParts;
this.headers = headers;
this.status = status;
}
private List<Cookie> buildCookies() {<FILL_FUNCTION_BODY>}
@Override
public final int getStatusCode() {
return status.getStatusCode();
}
@Override
public final String getStatusText() {
return status.getStatusText();
}
@Override
public final Uri getUri() {
return status.getUri();
}
@Override
public SocketAddress getRemoteAddress() {
return status.getRemoteAddress();
}
@Override
public SocketAddress getLocalAddress() {
return status.getLocalAddress();
}
@Override
public final String getContentType() {
return headers != null ? getHeader(CONTENT_TYPE) : null;
}
@Override
public final String getHeader(CharSequence name) {
return headers != null ? getHeaders().get(name) : null;
}
@Override
public final List<String> getHeaders(CharSequence name) {
return headers != null ? getHeaders().getAll(name) : Collections.emptyList();
}
@Override
public final HttpHeaders getHeaders() {
return headers != null ? headers : EmptyHttpHeaders.INSTANCE;
}
@Override
public final boolean isRedirected() {
switch (status.getStatusCode()) {
case 301:
case 302:
case 303:
case 307:
case 308:
return true;
default:
return false;
}
}
@Override
public List<Cookie> getCookies() {
if (headers == null) {
return Collections.emptyList();
}
if (cookies == null) {
cookies = buildCookies();
}
return cookies;
}
@Override
public boolean hasResponseStatus() {
return status != null;
}
@Override
public boolean hasResponseHeaders() {
return headers != null && !headers.isEmpty();
}
@Override
public boolean hasResponseBody() {
return isNonEmpty(bodyParts);
}
@Override
public byte[] getResponseBodyAsBytes() {
return getResponseBodyAsByteBuffer().array();
}
@Override
public ByteBuffer getResponseBodyAsByteBuffer() {
int length = 0;
for (HttpResponseBodyPart part : bodyParts) {
length += part.length();
}
ByteBuffer target = ByteBuffer.wrap(new byte[length]);
for (HttpResponseBodyPart part : bodyParts) {
target.put(part.getBodyPartBytes());
}
target.flip();
return target;
}
@Override
public ByteBuf getResponseBodyAsByteBuf() {
CompositeByteBuf compositeByteBuf = ByteBufAllocator.DEFAULT.compositeBuffer(bodyParts.size());
for (HttpResponseBodyPart part : bodyParts) {
compositeByteBuf.addComponent(true, part.getBodyByteBuf());
}
return compositeByteBuf;
}
@Override
public String getResponseBody() {
return getResponseBody(withDefault(extractContentTypeCharsetAttribute(getContentType()), UTF_8));
}
@Override
public String getResponseBody(Charset charset) {
return new String(getResponseBodyAsBytes(), charset);
}
@Override
public InputStream getResponseBodyAsStream() {
return new ByteArrayInputStream(getResponseBodyAsBytes());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()).append(" {\n")
.append("\tstatusCode=").append(getStatusCode()).append('\n')
.append("\theaders=\n");
for (Map.Entry<String, String> header : getHeaders()) {
sb.append("\t\t").append(header.getKey()).append(": ").append(header.getValue()).append('\n');
}
return sb.append("\tbody=\n").append(getResponseBody()).append('\n')
.append('}').toString();
}
}
|
List<String> setCookieHeaders = headers.getAll(SET_COOKIE2);
if (!isNonEmpty(setCookieHeaders)) {
setCookieHeaders = headers.getAll(SET_COOKIE);
}
if (isNonEmpty(setCookieHeaders)) {
List<Cookie> cookies = new ArrayList<>(1);
for (String value : setCookieHeaders) {
Cookie c = ClientCookieDecoder.STRICT.decode(value);
if (c != null) {
cookies.add(c);
}
}
return Collections.unmodifiableList(cookies);
}
return Collections.emptyList();
| 1,194
| 177
| 1,371
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/SimpleChannelFutureListener.java
|
SimpleChannelFutureListener
|
operationComplete
|
class SimpleChannelFutureListener implements ChannelFutureListener {
@Override
public final void operationComplete(ChannelFuture future) {<FILL_FUNCTION_BODY>}
public abstract void onSuccess(Channel channel);
public abstract void onFailure(Channel channel, Throwable cause);
}
|
Channel channel = future.channel();
if (future.isSuccess()) {
onSuccess(channel);
} else {
onFailure(channel, future.cause());
}
| 72
| 48
| 120
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/SimpleFutureListener.java
|
SimpleFutureListener
|
operationComplete
|
class SimpleFutureListener<V> implements FutureListener<V> {
@Override
public final void operationComplete(Future<V> future) throws Exception {<FILL_FUNCTION_BODY>}
protected abstract void onSuccess(V value) throws Exception;
protected abstract void onFailure(Throwable t) throws Exception;
}
|
if (future.isSuccess()) {
onSuccess(future.getNow());
} else {
onFailure(future.cause());
}
| 82
| 40
| 122
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/CombinedConnectionSemaphore.java
|
CombinedConnectionSemaphore
|
acquireChannelLock
|
class CombinedConnectionSemaphore extends PerHostConnectionSemaphore {
protected final MaxConnectionSemaphore globalMaxConnectionSemaphore;
CombinedConnectionSemaphore(int maxConnections, int maxConnectionsPerHost, int acquireTimeout) {
super(maxConnectionsPerHost, acquireTimeout);
globalMaxConnectionSemaphore = new MaxConnectionSemaphore(maxConnections, acquireTimeout);
}
@Override
public void acquireChannelLock(Object partitionKey) throws IOException {<FILL_FUNCTION_BODY>}
protected void releaseGlobal(Object partitionKey) {
globalMaxConnectionSemaphore.releaseChannelLock(partitionKey);
}
protected long acquireGlobal(Object partitionKey) throws IOException {
globalMaxConnectionSemaphore.acquireChannelLock(partitionKey);
return 0;
}
/*
* Acquires the global lock and returns the remaining time, in millis, to acquire the per-host lock
*/
protected long acquireGlobalTimed(Object partitionKey) throws IOException {
long beforeGlobalAcquire = System.currentTimeMillis();
acquireGlobal(partitionKey);
long lockTime = System.currentTimeMillis() - beforeGlobalAcquire;
return acquireTimeout - lockTime;
}
@Override
public void releaseChannelLock(Object partitionKey) {
globalMaxConnectionSemaphore.releaseChannelLock(partitionKey);
super.releaseChannelLock(partitionKey);
}
}
|
long remainingTime = acquireTimeout > 0 ? acquireGlobalTimed(partitionKey) : acquireGlobal(partitionKey);
try {
if (remainingTime < 0 || !getFreeConnectionsForHost(partitionKey).tryAcquire(remainingTime, TimeUnit.MILLISECONDS)) {
releaseGlobal(partitionKey);
throw tooManyConnectionsPerHost;
}
} catch (InterruptedException e) {
releaseGlobal(partitionKey);
throw new RuntimeException(e);
}
| 356
| 125
| 481
|
<methods>public void acquireChannelLock(java.lang.Object) throws java.io.IOException,public void releaseChannelLock(java.lang.Object) <variables>protected final non-sealed int acquireTimeout,protected final ConcurrentHashMap<java.lang.Object,java.util.concurrent.Semaphore> freeChannelsPerHost,protected final non-sealed int maxConnectionsPerHost,protected final non-sealed java.io.IOException tooManyConnectionsPerHost
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/DefaultChannelPool.java
|
IdleChannelDetector
|
closeChannels
|
class IdleChannelDetector implements TimerTask {
private boolean isIdleTimeoutExpired(IdleChannel idleChannel, long now) {
return maxIdleTimeEnabled && now - idleChannel.start >= maxIdleTime;
}
private List<IdleChannel> expiredChannels(ConcurrentLinkedDeque<IdleChannel> partition, long now) {
// lazy create
List<IdleChannel> idleTimeoutChannels = null;
for (IdleChannel idleChannel : partition) {
boolean isIdleTimeoutExpired = isIdleTimeoutExpired(idleChannel, now);
boolean isRemotelyClosed = !Channels.isChannelActive(idleChannel.channel);
boolean isTtlExpired = isTtlExpired(idleChannel.channel, now);
if (isIdleTimeoutExpired || isRemotelyClosed || isTtlExpired) {
LOGGER.debug("Adding Candidate expired Channel {} isIdleTimeoutExpired={} isRemotelyClosed={} isTtlExpired={}",
idleChannel.channel, isIdleTimeoutExpired, isRemotelyClosed, isTtlExpired);
if (idleTimeoutChannels == null) {
idleTimeoutChannels = new ArrayList<>(1);
}
idleTimeoutChannels.add(idleChannel);
}
}
return idleTimeoutChannels != null ? idleTimeoutChannels : Collections.emptyList();
}
private List<IdleChannel> closeChannels(List<IdleChannel> candidates) {<FILL_FUNCTION_BODY>}
@Override
public void run(Timeout timeout) {
if (isClosed.get()) {
return;
}
if (LOGGER.isDebugEnabled()) {
for (Map.Entry<Object, ConcurrentLinkedDeque<IdleChannel>> entry : partitions.entrySet()) {
int size = entry.getValue().size();
if (size > 0) {
LOGGER.debug("Entry count for : {} : {}", entry.getKey(), size);
}
}
}
long start = unpreciseMillisTime();
int closedCount = 0;
int totalCount = 0;
for (ConcurrentLinkedDeque<IdleChannel> partition : partitions.values()) {
// store in intermediate unsynchronized lists to minimize
// the impact on the ConcurrentLinkedDeque
if (LOGGER.isDebugEnabled()) {
totalCount += partition.size();
}
List<IdleChannel> closedChannels = closeChannels(expiredChannels(partition, start));
if (!closedChannels.isEmpty()) {
partition.removeAll(closedChannels);
closedCount += closedChannels.size();
}
}
if (LOGGER.isDebugEnabled()) {
long duration = unpreciseMillisTime() - start;
if (closedCount > 0) {
LOGGER.debug("Closed {} connections out of {} in {} ms", closedCount, totalCount, duration);
}
}
scheduleNewIdleChannelDetector(timeout.task());
}
}
|
// lazy create, only if we hit a non-closeable channel
List<IdleChannel> closedChannels = null;
for (int i = 0; i < candidates.size(); i++) {
// We call takeOwnership here to avoid closing a channel that has just been taken out
// of the pool, otherwise we risk closing an active connection.
IdleChannel idleChannel = candidates.get(i);
if (idleChannel.takeOwnership()) {
LOGGER.debug("Closing Idle Channel {}", idleChannel.channel);
close(idleChannel.channel);
if (closedChannels != null) {
closedChannels.add(idleChannel);
}
} else if (closedChannels == null) {
// first non-closeable to be skipped, copy all
// previously skipped closeable channels
closedChannels = new ArrayList<>(candidates.size());
for (int j = 0; j < i; j++) {
closedChannels.add(candidates.get(j));
}
}
}
return closedChannels != null ? closedChannels : candidates;
| 785
| 283
| 1,068
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/DefaultConnectionSemaphoreFactory.java
|
DefaultConnectionSemaphoreFactory
|
newConnectionSemaphore
|
class DefaultConnectionSemaphoreFactory implements ConnectionSemaphoreFactory {
@Override
public ConnectionSemaphore newConnectionSemaphore(AsyncHttpClientConfig config) {<FILL_FUNCTION_BODY>}
}
|
int acquireFreeChannelTimeout = Math.max(0, config.getAcquireFreeChannelTimeout());
int maxConnections = config.getMaxConnections();
int maxConnectionsPerHost = config.getMaxConnectionsPerHost();
if (maxConnections > 0 && maxConnectionsPerHost > 0) {
return new CombinedConnectionSemaphore(maxConnections, maxConnectionsPerHost, acquireFreeChannelTimeout);
}
if (maxConnections > 0) {
return new MaxConnectionSemaphore(maxConnections, acquireFreeChannelTimeout);
}
if (maxConnectionsPerHost > 0) {
return new CombinedConnectionSemaphore(maxConnections, maxConnectionsPerHost, acquireFreeChannelTimeout);
}
return new NoopConnectionSemaphore();
| 54
| 194
| 248
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/EpollTransportFactory.java
|
EpollTransportFactory
|
isAvailable
|
class EpollTransportFactory implements TransportFactory<EpollSocketChannel, EpollEventLoopGroup> {
static boolean isAvailable() {<FILL_FUNCTION_BODY>}
@Override
public EpollSocketChannel newChannel() {
return new EpollSocketChannel();
}
@Override
public EpollEventLoopGroup newEventLoopGroup(int ioThreadsCount, ThreadFactory threadFactory) {
return new EpollEventLoopGroup(ioThreadsCount, threadFactory);
}
}
|
try {
Class.forName("io.netty.channel.epoll.Epoll");
} catch (ClassNotFoundException e) {
return false;
}
return Epoll.isAvailable();
| 124
| 55
| 179
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/IoUringIncubatorTransportFactory.java
|
IoUringIncubatorTransportFactory
|
isAvailable
|
class IoUringIncubatorTransportFactory implements TransportFactory<IOUringSocketChannel, IOUringEventLoopGroup> {
static boolean isAvailable() {<FILL_FUNCTION_BODY>}
@Override
public IOUringSocketChannel newChannel() {
return new IOUringSocketChannel();
}
@Override
public IOUringEventLoopGroup newEventLoopGroup(int ioThreadsCount, ThreadFactory threadFactory) {
return new IOUringEventLoopGroup(ioThreadsCount, threadFactory);
}
}
|
try {
Class.forName("io.netty.incubator.channel.uring.IOUring");
} catch (ClassNotFoundException e) {
return false;
}
return IOUring.isAvailable();
| 135
| 60
| 195
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/KQueueTransportFactory.java
|
KQueueTransportFactory
|
isAvailable
|
class KQueueTransportFactory implements TransportFactory<KQueueSocketChannel, KQueueEventLoopGroup> {
static boolean isAvailable() {<FILL_FUNCTION_BODY>}
@Override
public KQueueSocketChannel newChannel() {
return new KQueueSocketChannel();
}
@Override
public KQueueEventLoopGroup newEventLoopGroup(int ioThreadsCount, ThreadFactory threadFactory) {
return new KQueueEventLoopGroup(ioThreadsCount, threadFactory);
}
}
|
try {
Class.forName("io.netty.channel.kqueue.KQueue");
} catch (ClassNotFoundException e) {
return false;
}
return KQueue.isAvailable();
| 124
| 55
| 179
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/MaxConnectionSemaphore.java
|
MaxConnectionSemaphore
|
acquireChannelLock
|
class MaxConnectionSemaphore implements ConnectionSemaphore {
protected final Semaphore freeChannels;
protected final IOException tooManyConnections;
protected final int acquireTimeout;
MaxConnectionSemaphore(int maxConnections, int acquireTimeout) {
tooManyConnections = unknownStackTrace(new TooManyConnectionsException(maxConnections), MaxConnectionSemaphore.class, "acquireChannelLock");
freeChannels = maxConnections > 0 ? new Semaphore(maxConnections) : InfiniteSemaphore.INSTANCE;
this.acquireTimeout = Math.max(0, acquireTimeout);
}
@Override
public void acquireChannelLock(Object partitionKey) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void releaseChannelLock(Object partitionKey) {
freeChannels.release();
}
}
|
try {
if (!freeChannels.tryAcquire(acquireTimeout, TimeUnit.MILLISECONDS)) {
throw tooManyConnections;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
| 212
| 67
| 279
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/NettyChannelConnector.java
|
NettyChannelConnector
|
connect
|
class NettyChannelConnector {
private static final Logger LOGGER = LoggerFactory.getLogger(NettyChannelConnector.class);
private static final AtomicIntegerFieldUpdater<NettyChannelConnector> I_UPDATER = AtomicIntegerFieldUpdater
.newUpdater(NettyChannelConnector.class, "i");
private final AsyncHandler<?> asyncHandler;
private final InetSocketAddress localAddress;
private final List<InetSocketAddress> remoteAddresses;
private final AsyncHttpClientState clientState;
private volatile int i;
public NettyChannelConnector(InetAddress localAddress, List<InetSocketAddress> remoteAddresses, AsyncHandler<?> asyncHandler, AsyncHttpClientState clientState) {
this.localAddress = localAddress != null ? new InetSocketAddress(localAddress, 0) : null;
this.remoteAddresses = remoteAddresses;
this.asyncHandler = asyncHandler;
this.clientState = clientState;
}
private boolean pickNextRemoteAddress() {
I_UPDATER.incrementAndGet(this);
return i < remoteAddresses.size();
}
public void connect(final Bootstrap bootstrap, final NettyConnectListener<?> connectListener) {<FILL_FUNCTION_BODY>}
private void connect0(Bootstrap bootstrap, final NettyConnectListener<?> connectListener, InetSocketAddress remoteAddress) {
bootstrap.connect(remoteAddress, localAddress)
.addListener(new SimpleChannelFutureListener() {
@Override
public void onSuccess(Channel channel) {
try {
asyncHandler.onTcpConnectSuccess(remoteAddress, channel);
} catch (Exception e) {
LOGGER.error("onTcpConnectSuccess crashed", e);
connectListener.onFailure(channel, e);
return;
}
connectListener.onSuccess(channel, remoteAddress);
}
@Override
public void onFailure(Channel channel, Throwable t) {
try {
asyncHandler.onTcpConnectFailure(remoteAddress, t);
} catch (Exception e) {
LOGGER.error("onTcpConnectFailure crashed", e);
connectListener.onFailure(channel, e);
return;
}
boolean retry = pickNextRemoteAddress();
if (retry) {
connect(bootstrap, connectListener);
} else {
connectListener.onFailure(channel, t);
}
}
});
}
}
|
final InetSocketAddress remoteAddress = remoteAddresses.get(i);
try {
asyncHandler.onTcpConnectAttempt(remoteAddress);
} catch (Exception e) {
LOGGER.error("onTcpConnectAttempt crashed", e);
connectListener.onFailure(null, e);
return;
}
try {
connect0(bootstrap, connectListener, remoteAddress);
} catch (RejectedExecutionException e) {
if (clientState.isClosed()) {
LOGGER.info("Connect crash but engine is shutting down");
} else {
connectListener.onFailure(null, e);
}
}
| 631
| 168
| 799
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/NettyConnectListener.java
|
NettyConnectListener
|
onSuccess
|
class NettyConnectListener<T> {
private static final Logger LOGGER = LoggerFactory.getLogger(NettyConnectListener.class);
private final NettyRequestSender requestSender;
private final NettyResponseFuture<T> future;
private final ChannelManager channelManager;
private final ConnectionSemaphore connectionSemaphore;
public NettyConnectListener(NettyResponseFuture<T> future, NettyRequestSender requestSender, ChannelManager channelManager, ConnectionSemaphore connectionSemaphore) {
this.future = future;
this.requestSender = requestSender;
this.channelManager = channelManager;
this.connectionSemaphore = connectionSemaphore;
}
private boolean futureIsAlreadyCancelled(Channel channel) {
// If Future is cancelled then we will close the channel silently
if (future.isCancelled()) {
Channels.silentlyCloseChannel(channel);
return true;
}
return false;
}
private void writeRequest(Channel channel) {
if (futureIsAlreadyCancelled(channel)) {
return;
}
if (LOGGER.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
LOGGER.debug("Using new Channel '{}' for '{}' to '{}'", channel, httpRequest.method(), httpRequest.uri());
}
Channels.setAttribute(channel, future);
channelManager.registerOpenChannel(channel);
future.attachChannel(channel, false);
requestSender.writeRequest(future, channel);
}
public void onSuccess(Channel channel, InetSocketAddress remoteAddress) {<FILL_FUNCTION_BODY>}
public void onFailure(Channel channel, Throwable cause) {
// beware, channel can be null
Channels.silentlyCloseChannel(channel);
boolean canRetry = future.incrementRetryAndCheck();
LOGGER.debug("Trying to recover from failing to connect channel {} with a retry value of {} ", channel, canRetry);
if (canRetry//
&& cause != null // FIXME when can we have a null cause?
&& (future.getChannelState() != ChannelState.NEW || StackTraceInspector.recoverOnNettyDisconnectException(cause))) {
if (requestSender.retry(future)) {
return;
}
}
LOGGER.debug("Failed to recover from connect exception: {} with channel {}", cause, channel);
String message = cause.getMessage() != null ? cause.getMessage() : future.getUri().getBaseUrl();
ConnectException e = new ConnectException(message);
e.initCause(cause);
future.abort(e);
}
}
|
if (connectionSemaphore != null) {
// transfer lock from future to channel
Object partitionKeyLock = future.takePartitionKeyLock();
if (partitionKeyLock != null) {
channel.closeFuture().addListener(future -> connectionSemaphore.releaseChannelLock(partitionKeyLock));
}
}
Channels.setActiveToken(channel);
TimeoutsHolder timeoutsHolder = future.getTimeoutsHolder();
if (futureIsAlreadyCancelled(channel)) {
return;
}
Request request = future.getTargetRequest();
Uri uri = request.getUri();
timeoutsHolder.setResolvedRemoteAddress(remoteAddress);
ProxyServer proxyServer = future.getProxyServer();
// in case of proxy tunneling, we'll add the SslHandler later, after the CONNECT request
if ((proxyServer == null || proxyServer.getProxyType().isSocks()) && uri.isSecured()) {
SslHandler sslHandler;
try {
sslHandler = channelManager.addSslHandler(channel.pipeline(), uri, request.getVirtualHost(), proxyServer != null);
} catch (Exception sslError) {
onFailure(channel, sslError);
return;
}
final AsyncHandler<?> asyncHandler = future.getAsyncHandler();
try {
asyncHandler.onTlsHandshakeAttempt();
} catch (Exception e) {
LOGGER.error("onTlsHandshakeAttempt crashed", e);
onFailure(channel, e);
return;
}
sslHandler.handshakeFuture().addListener(new SimpleFutureListener<Channel>() {
@Override
protected void onSuccess(Channel value) {
try {
asyncHandler.onTlsHandshakeSuccess(sslHandler.engine().getSession());
} catch (Exception e) {
LOGGER.error("onTlsHandshakeSuccess crashed", e);
NettyConnectListener.this.onFailure(channel, e);
return;
}
writeRequest(channel);
}
@Override
protected void onFailure(Throwable cause) {
try {
asyncHandler.onTlsHandshakeFailure(cause);
} catch (Exception e) {
LOGGER.error("onTlsHandshakeFailure crashed", e);
NettyConnectListener.this.onFailure(channel, e);
return;
}
NettyConnectListener.this.onFailure(channel, cause);
}
});
} else {
writeRequest(channel);
}
| 694
| 650
| 1,344
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/channel/PerHostConnectionSemaphore.java
|
PerHostConnectionSemaphore
|
acquireChannelLock
|
class PerHostConnectionSemaphore implements ConnectionSemaphore {
protected final ConcurrentHashMap<Object, Semaphore> freeChannelsPerHost = new ConcurrentHashMap<>();
protected final int maxConnectionsPerHost;
protected final IOException tooManyConnectionsPerHost;
protected final int acquireTimeout;
PerHostConnectionSemaphore(int maxConnectionsPerHost, int acquireTimeout) {
tooManyConnectionsPerHost = unknownStackTrace(new TooManyConnectionsPerHostException(maxConnectionsPerHost),
PerHostConnectionSemaphore.class, "acquireChannelLock");
this.maxConnectionsPerHost = maxConnectionsPerHost;
this.acquireTimeout = Math.max(0, acquireTimeout);
}
@Override
public void acquireChannelLock(Object partitionKey) throws IOException {<FILL_FUNCTION_BODY>}
@Override
public void releaseChannelLock(Object partitionKey) {
getFreeConnectionsForHost(partitionKey).release();
}
protected Semaphore getFreeConnectionsForHost(Object partitionKey) {
return maxConnectionsPerHost > 0 ?
freeChannelsPerHost.computeIfAbsent(partitionKey, pk -> new Semaphore(maxConnectionsPerHost)) :
InfiniteSemaphore.INSTANCE;
}
}
|
try {
if (!getFreeConnectionsForHost(partitionKey).tryAcquire(acquireTimeout, TimeUnit.MILLISECONDS)) {
throw tooManyConnectionsPerHost;
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
| 322
| 75
| 397
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/future/StackTraceInspector.java
|
StackTraceInspector
|
recoverOnConnectCloseException
|
class StackTraceInspector {
private StackTraceInspector() {
// Prevent outside initialization
}
private static boolean exceptionInMethod(Throwable t, String className, String methodName) {
try {
for (StackTraceElement element : t.getStackTrace()) {
if (element.getClassName().equals(className) && element.getMethodName().equals(methodName)) {
return true;
}
}
} catch (Throwable ignore) {
}
return false;
}
private static boolean recoverOnConnectCloseException(Throwable t) {<FILL_FUNCTION_BODY>}
public static boolean recoverOnNettyDisconnectException(Throwable t) {
return t instanceof ClosedChannelException
|| exceptionInMethod(t, "io.netty.handler.ssl.SslHandler", "disconnect")
|| t.getCause() != null && recoverOnConnectCloseException(t.getCause());
}
public static boolean recoverOnReadOrWriteException(Throwable t) {
while (true) {
if (t instanceof IOException && "Connection reset by peer".equalsIgnoreCase(t.getMessage())) {
return true;
}
try {
for (StackTraceElement element : t.getStackTrace()) {
String className = element.getClassName();
String methodName = element.getMethodName();
if ("sun.nio.ch.SocketDispatcher".equals(className) && ("read".equals(methodName) || "write".equals(methodName))) {
return true;
}
}
} catch (Throwable ignore) {
}
if (t.getCause() == null) {
return false;
}
t = t.getCause();
}
}
}
|
while (true) {
if (exceptionInMethod(t, "sun.nio.ch.SocketChannelImpl", "checkConnect")) {
return true;
}
if (t.getCause() == null) {
return false;
}
t = t.getCause();
}
| 443
| 80
| 523
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/AsyncHttpClientHandler.java
|
AsyncHttpClientHandler
|
exceptionCaught
|
class AsyncHttpClientHandler extends ChannelInboundHandlerAdapter {
protected final Logger logger = LoggerFactory.getLogger(getClass());
protected final AsyncHttpClientConfig config;
protected final ChannelManager channelManager;
protected final NettyRequestSender requestSender;
final Interceptors interceptors;
final boolean hasIOExceptionFilters;
AsyncHttpClientHandler(AsyncHttpClientConfig config,
ChannelManager channelManager,
NettyRequestSender requestSender) {
this.config = config;
this.channelManager = channelManager;
this.requestSender = requestSender;
interceptors = new Interceptors(config, channelManager, requestSender);
hasIOExceptionFilters = !config.getIoExceptionFilters().isEmpty();
}
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
Channel channel = ctx.channel();
Object attribute = Channels.getAttribute(channel);
try {
if (attribute instanceof OnLastHttpContentCallback) {
if (msg instanceof LastHttpContent) {
((OnLastHttpContentCallback) attribute).call();
}
} else if (attribute instanceof NettyResponseFuture) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
future.touch();
handleRead(channel, future, msg);
} else if (attribute != DiscardEvent.DISCARD) {
// unhandled message
logger.debug("Orphan channel {} with attribute {} received message {}, closing", channel, attribute, msg);
Channels.silentlyCloseChannel(channel);
}
} finally {
ReferenceCountUtil.release(msg);
}
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
if (requestSender.isClosed()) {
return;
}
Channel channel = ctx.channel();
channelManager.removeAll(channel);
Object attribute = Channels.getAttribute(channel);
logger.debug("Channel Closed: {} with attribute {}", channel, attribute);
if (attribute instanceof OnLastHttpContentCallback) {
OnLastHttpContentCallback callback = (OnLastHttpContentCallback) attribute;
Channels.setAttribute(channel, callback.future());
callback.call();
} else if (attribute instanceof NettyResponseFuture<?>) {
NettyResponseFuture<?> future = (NettyResponseFuture<?>) attribute;
future.touch();
if (hasIOExceptionFilters && requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel)) {
return;
}
handleChannelInactive(future);
requestSender.handleUnexpectedClosedChannel(channel, future);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable e) {<FILL_FUNCTION_BODY>}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.read();
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.read();
}
void finishUpdate(NettyResponseFuture<?> future, Channel channel, boolean close) {
future.cancelTimeouts();
if (close) {
channelManager.closeChannel(channel);
} else {
channelManager.tryToOfferChannelToPool(channel, future.getAsyncHandler(), true, future.getPartitionKey());
}
try {
future.done();
} catch (Exception t) {
// Never propagate exception once we know we are done.
logger.debug(t.getMessage(), t);
}
}
public abstract void handleRead(Channel channel, NettyResponseFuture<?> future, Object message) throws Exception;
public abstract void handleException(NettyResponseFuture<?> future, Throwable error);
public abstract void handleChannelInactive(NettyResponseFuture<?> future);
}
|
Throwable cause = getCause(e);
if (cause instanceof PrematureChannelClosureException || cause instanceof ClosedChannelException) {
return;
}
Channel channel = ctx.channel();
NettyResponseFuture<?> future = null;
logger.debug("Unexpected I/O exception on channel {}", channel, cause);
try {
Object attribute = Channels.getAttribute(channel);
if (attribute instanceof NettyResponseFuture<?>) {
future = (NettyResponseFuture<?>) attribute;
future.attachChannel(null, false);
future.touch();
if (cause instanceof IOException) {
// FIXME why drop the original exception and throw a new one?
if (hasIOExceptionFilters) {
if (!requestSender.applyIoExceptionFiltersAndReplayRequest(future, ChannelClosedException.INSTANCE, channel)) {
// Close the channel so the recovering can occurs.
Channels.silentlyCloseChannel(channel);
}
return;
}
}
if (StackTraceInspector.recoverOnReadOrWriteException(cause)) {
logger.debug("Trying to recover from dead Channel: {}", channel);
future.pendingException = cause;
return;
}
} else if (attribute instanceof OnLastHttpContentCallback) {
future = ((OnLastHttpContentCallback) attribute).future();
}
} catch (Throwable t) {
cause = t;
}
if (future != null) {
try {
logger.debug("Was unable to recover Future: {}", future);
requestSender.abort(channel, future, cause);
handleException(future, e);
} catch (Throwable t) {
logger.error(t.getMessage(), t);
}
}
channelManager.closeChannel(channel);
// FIXME not really sure
// ctx.fireChannelRead(e);
Channels.silentlyCloseChannel(channel);
| 992
| 497
| 1,489
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/HttpHandler.java
|
HttpHandler
|
handleHttpResponse
|
class HttpHandler extends AsyncHttpClientHandler {
public HttpHandler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) {
super(config, channelManager, requestSender);
}
private static boolean abortAfterHandlingStatus(AsyncHandler<?> handler, NettyResponseStatus status) throws Exception {
return handler.onStatusReceived(status) == State.ABORT;
}
private static boolean abortAfterHandlingHeaders(AsyncHandler<?> handler, HttpHeaders responseHeaders) throws Exception {
return !responseHeaders.isEmpty() && handler.onHeadersReceived(responseHeaders) == State.ABORT;
}
private void handleHttpResponse(final HttpResponse response, final Channel channel, final NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {<FILL_FUNCTION_BODY>}
private void handleChunk(HttpContent chunk, final Channel channel, final NettyResponseFuture<?> future, AsyncHandler<?> handler) throws Exception {
boolean abort = false;
boolean last = chunk instanceof LastHttpContent;
// Netty 4: the last chunk is not empty
if (last) {
LastHttpContent lastChunk = (LastHttpContent) chunk;
HttpHeaders trailingHeaders = lastChunk.trailingHeaders();
if (!trailingHeaders.isEmpty()) {
abort = handler.onTrailingHeadersReceived(trailingHeaders) == State.ABORT;
}
}
ByteBuf buf = chunk.content();
if (!abort && (buf.isReadable() || last)) {
HttpResponseBodyPart bodyPart = config.getResponseBodyPartFactory().newResponseBodyPart(buf, last);
abort = handler.onBodyPartReceived(bodyPart) == State.ABORT;
}
if (abort || last) {
boolean close = abort || !future.isKeepAlive();
finishUpdate(future, channel, close);
}
}
@Override
public void handleRead(final Channel channel, final NettyResponseFuture<?> future, final Object e) throws Exception {
// future is already done because of an exception or a timeout
if (future.isDone()) {
// FIXME isn't the channel already properly closed?
channelManager.closeChannel(channel);
return;
}
AsyncHandler<?> handler = future.getAsyncHandler();
try {
if (e instanceof DecoderResultProvider) {
DecoderResultProvider object = (DecoderResultProvider) e;
Throwable t = object.decoderResult().cause();
if (t != null) {
readFailed(channel, future, t);
return;
}
}
if (e instanceof HttpResponse) {
handleHttpResponse((HttpResponse) e, channel, future, handler);
} else if (e instanceof HttpContent) {
handleChunk((HttpContent) e, channel, future, handler);
}
} catch (Exception t) {
// e.g. an IOException when trying to open a connection and send the
// next request
if (hasIOExceptionFilters && t instanceof IOException && requestSender.applyIoExceptionFiltersAndReplayRequest(future, (IOException) t, channel)) {
return;
}
readFailed(channel, future, t);
throw t;
}
}
private void readFailed(Channel channel, NettyResponseFuture<?> future, Throwable t) {
try {
requestSender.abort(channel, future, t);
} catch (Exception abortException) {
logger.debug("Abort failed", abortException);
} finally {
finishUpdate(future, channel, true);
}
}
@Override
public void handleException(NettyResponseFuture<?> future, Throwable error) {
}
@Override
public void handleChannelInactive(NettyResponseFuture<?> future) {
}
}
|
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
future.setKeepAlive(config.getKeepAliveStrategy().keepAlive((InetSocketAddress) channel.remoteAddress(), future.getTargetRequest(), httpRequest, response));
NettyResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
HttpHeaders responseHeaders = response.headers();
if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
boolean abort = abortAfterHandlingStatus(handler, status) || abortAfterHandlingHeaders(handler, responseHeaders);
if (abort) {
finishUpdate(future, channel, true);
}
}
| 985
| 207
| 1,192
|
<methods>public void channelActive(ChannelHandlerContext) ,public void channelInactive(ChannelHandlerContext) throws java.lang.Exception,public void channelRead(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception,public void channelReadComplete(ChannelHandlerContext) ,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract void handleChannelInactive(NettyResponseFuture<?>) ,public abstract void handleException(NettyResponseFuture<?>, java.lang.Throwable) ,public abstract void handleRead(Channel, NettyResponseFuture<?>, java.lang.Object) throws java.lang.Exception<variables>protected final non-sealed org.asynchttpclient.netty.channel.ChannelManager channelManager,protected final non-sealed org.asynchttpclient.AsyncHttpClientConfig config,final non-sealed boolean hasIOExceptionFilters,final non-sealed org.asynchttpclient.netty.handler.intercept.Interceptors interceptors,protected final Logger logger,protected final non-sealed org.asynchttpclient.netty.request.NettyRequestSender requestSender
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/WebSocketHandler.java
|
WebSocketHandler
|
upgrade
|
class WebSocketHandler extends AsyncHttpClientHandler {
public WebSocketHandler(AsyncHttpClientConfig config, ChannelManager channelManager, NettyRequestSender requestSender) {
super(config, channelManager, requestSender);
}
private static WebSocketUpgradeHandler getWebSocketUpgradeHandler(NettyResponseFuture<?> future) {
return (WebSocketUpgradeHandler) future.getAsyncHandler();
}
private static NettyWebSocket getNettyWebSocket(NettyResponseFuture<?> future) throws Exception {
return getWebSocketUpgradeHandler(future).onCompleted();
}
private void upgrade(Channel channel, NettyResponseFuture<?> future, WebSocketUpgradeHandler handler, HttpResponse response, HttpHeaders responseHeaders) throws Exception {<FILL_FUNCTION_BODY>}
private void abort(Channel channel, NettyResponseFuture<?> future, WebSocketUpgradeHandler handler, HttpResponseStatus status) {
try {
handler.onThrowable(new IOException("Invalid Status code=" + status.getStatusCode() + " text=" + status.getStatusText()));
} finally {
finishUpdate(future, channel, true);
}
}
@Override
public void handleRead(Channel channel, NettyResponseFuture<?> future, Object e) throws Exception {
if (e instanceof HttpResponse) {
HttpResponse response = (HttpResponse) e;
if (logger.isDebugEnabled()) {
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
logger.debug("\n\nRequest {}\n\nResponse {}\n", httpRequest, response);
}
WebSocketUpgradeHandler handler = getWebSocketUpgradeHandler(future);
HttpResponseStatus status = new NettyResponseStatus(future.getUri(), response, channel);
HttpHeaders responseHeaders = response.headers();
if (!interceptors.exitAfterIntercept(channel, future, handler, response, status, responseHeaders)) {
if (handler.onStatusReceived(status) == State.CONTINUE) {
upgrade(channel, future, handler, response, responseHeaders);
} else {
abort(channel, future, handler, status);
}
}
} else if (e instanceof WebSocketFrame) {
WebSocketFrame frame = (WebSocketFrame) e;
NettyWebSocket webSocket = getNettyWebSocket(future);
// retain because we might buffer the frame
if (webSocket.isReady()) {
webSocket.handleFrame(frame);
} else {
// WebSocket hasn't been opened yet, but upgrading the pipeline triggered a read and a frame was sent along the HTTP upgrade response
// as we want to keep sequential order (but can't notify user of open before upgrading, so he doesn't try to send immediately), we have to buffer
webSocket.bufferFrame(frame);
}
} else if (!(e instanceof LastHttpContent)) {
// ignore, end of handshake response
logger.error("Invalid message {}", e);
}
}
@Override
public void handleException(NettyResponseFuture<?> future, Throwable e) {
logger.warn("onError", e);
try {
NettyWebSocket webSocket = getNettyWebSocket(future);
if (webSocket != null) {
webSocket.onError(e);
webSocket.sendCloseFrame();
}
} catch (Throwable t) {
logger.error("onError", t);
}
}
@Override
public void handleChannelInactive(NettyResponseFuture<?> future) {
logger.trace("Connection was closed abnormally (that is, with no close frame being received).");
try {
NettyWebSocket webSocket = getNettyWebSocket(future);
if (webSocket != null) {
webSocket.onClose(1006, "Connection was closed abnormally (that is, with no close frame being received).");
}
} catch (Throwable t) {
logger.error("onError", t);
}
}
}
|
boolean validStatus = response.status().equals(SWITCHING_PROTOCOLS);
boolean validUpgrade = response.headers().get(UPGRADE) != null;
String connection = response.headers().get(CONNECTION);
boolean validConnection = HttpHeaderValues.UPGRADE.contentEqualsIgnoreCase(connection);
final boolean headerOK = handler.onHeadersReceived(responseHeaders) == State.CONTINUE;
if (!headerOK || !validStatus || !validUpgrade || !validConnection) {
requestSender.abort(channel, future, new IOException("Invalid handshake response"));
return;
}
String accept = response.headers().get(SEC_WEBSOCKET_ACCEPT);
String key = getAcceptKey(future.getNettyRequest().getHttpRequest().headers().get(SEC_WEBSOCKET_KEY));
if (accept == null || !accept.equals(key)) {
requestSender.abort(channel, future, new IOException("Invalid challenge. Actual: " + accept + ". Expected: " + key));
}
// set back the future so the protocol gets notified of frames
// removing the HttpClientCodec from the pipeline might trigger a read with a WebSocket message
// if it comes in the same frame as the HTTP Upgrade response
Channels.setAttribute(channel, future);
final NettyWebSocket webSocket = new NettyWebSocket(channel, responseHeaders);
handler.setWebSocket(webSocket);
channelManager.upgradePipelineForWebSockets(channel.pipeline());
// We don't need to synchronize as replacing the "ws-decoder" will
// process using the same thread.
try {
handler.onOpen(webSocket);
} catch (Exception ex) {
logger.warn("onSuccess unexpected exception", ex);
}
future.done();
| 1,012
| 462
| 1,474
|
<methods>public void channelActive(ChannelHandlerContext) ,public void channelInactive(ChannelHandlerContext) throws java.lang.Exception,public void channelRead(ChannelHandlerContext, java.lang.Object) throws java.lang.Exception,public void channelReadComplete(ChannelHandlerContext) ,public void exceptionCaught(ChannelHandlerContext, java.lang.Throwable) ,public abstract void handleChannelInactive(NettyResponseFuture<?>) ,public abstract void handleException(NettyResponseFuture<?>, java.lang.Throwable) ,public abstract void handleRead(Channel, NettyResponseFuture<?>, java.lang.Object) throws java.lang.Exception<variables>protected final non-sealed org.asynchttpclient.netty.channel.ChannelManager channelManager,protected final non-sealed org.asynchttpclient.AsyncHttpClientConfig config,final non-sealed boolean hasIOExceptionFilters,final non-sealed org.asynchttpclient.netty.handler.intercept.Interceptors interceptors,protected final Logger logger,protected final non-sealed org.asynchttpclient.netty.request.NettyRequestSender requestSender
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ConnectSuccessInterceptor.java
|
ConnectSuccessInterceptor
|
exitAfterHandlingConnect
|
class ConnectSuccessInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectSuccessInterceptor.class);
private final ChannelManager channelManager;
private final NettyRequestSender requestSender;
ConnectSuccessInterceptor(ChannelManager channelManager, NettyRequestSender requestSender) {
this.channelManager = channelManager;
this.requestSender = requestSender;
}
public boolean exitAfterHandlingConnect(Channel channel, NettyResponseFuture<?> future, Request request, ProxyServer proxyServer) {<FILL_FUNCTION_BODY>}
}
|
if (future.isKeepAlive()) {
future.attachChannel(channel, true);
}
Uri requestUri = request.getUri();
LOGGER.debug("Connecting to proxy {} for scheme {}", proxyServer, requestUri.getScheme());
final Future<Channel> whenHandshaked = channelManager.updatePipelineForHttpTunneling(channel.pipeline(), requestUri);
future.setReuseChannel(true);
future.setConnectAllowed(false);
Request targetRequest = future.getTargetRequest().toBuilder().build();
if (whenHandshaked == null) {
requestSender.drainChannelAndExecuteNextRequest(channel, future, targetRequest);
} else {
requestSender.drainChannelAndExecuteNextRequest(channel, future, targetRequest, whenHandshaked);
}
return true;
| 153
| 214
| 367
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Continue100Interceptor.java
|
Continue100Interceptor
|
exitAfterHandling100
|
class Continue100Interceptor {
private final NettyRequestSender requestSender;
Continue100Interceptor(NettyRequestSender requestSender) {
this.requestSender = requestSender;
}
public boolean exitAfterHandling100(final Channel channel, final NettyResponseFuture<?> future) {<FILL_FUNCTION_BODY>}
}
|
future.setHeadersAlreadyWrittenOnContinue(true);
future.setDontWriteBodyBecauseExpectContinue(false);
// directly send the body
Channels.setAttribute(channel, new OnLastHttpContentCallback(future) {
@Override
public void call() {
Channels.setAttribute(channel, future);
requestSender.writeRequest(future, channel);
}
});
return true;
| 104
| 110
| 214
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Interceptors.java
|
Interceptors
|
exitAfterIntercept
|
class Interceptors {
private final AsyncHttpClientConfig config;
private final Unauthorized401Interceptor unauthorized401Interceptor;
private final ProxyUnauthorized407Interceptor proxyUnauthorized407Interceptor;
private final Continue100Interceptor continue100Interceptor;
private final Redirect30xInterceptor redirect30xInterceptor;
private final ConnectSuccessInterceptor connectSuccessInterceptor;
private final ResponseFiltersInterceptor responseFiltersInterceptor;
private final boolean hasResponseFilters;
private final ClientCookieDecoder cookieDecoder;
public Interceptors(AsyncHttpClientConfig config,
ChannelManager channelManager,
NettyRequestSender requestSender) {
this.config = config;
unauthorized401Interceptor = new Unauthorized401Interceptor(channelManager, requestSender);
proxyUnauthorized407Interceptor = new ProxyUnauthorized407Interceptor(channelManager, requestSender);
continue100Interceptor = new Continue100Interceptor(requestSender);
redirect30xInterceptor = new Redirect30xInterceptor(channelManager, config, requestSender);
connectSuccessInterceptor = new ConnectSuccessInterceptor(channelManager, requestSender);
responseFiltersInterceptor = new ResponseFiltersInterceptor(config, requestSender);
hasResponseFilters = !config.getResponseFilters().isEmpty();
cookieDecoder = config.isUseLaxCookieEncoder() ? ClientCookieDecoder.LAX : ClientCookieDecoder.STRICT;
}
public boolean exitAfterIntercept(Channel channel, NettyResponseFuture<?> future, AsyncHandler<?> handler, HttpResponse response,
HttpResponseStatus status, HttpHeaders responseHeaders) throws Exception {<FILL_FUNCTION_BODY>}
}
|
HttpRequest httpRequest = future.getNettyRequest().getHttpRequest();
ProxyServer proxyServer = future.getProxyServer();
int statusCode = response.status().code();
Request request = future.getCurrentRequest();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
// This MUST BE called before Redirect30xInterceptor because latter assumes cookie store is already updated
CookieStore cookieStore = config.getCookieStore();
if (cookieStore != null) {
for (String cookieStr : responseHeaders.getAll(SET_COOKIE)) {
Cookie c = cookieDecoder.decode(cookieStr);
if (c != null) {
// Set-Cookie header could be invalid/malformed
cookieStore.add(future.getCurrentRequest().getUri(), c);
}
}
}
if (hasResponseFilters && responseFiltersInterceptor.exitAfterProcessingFilters(channel, future, handler, status, responseHeaders)) {
return true;
}
if (statusCode == UNAUTHORIZED_401) {
return unauthorized401Interceptor.exitAfterHandling401(channel, future, response, request, realm, httpRequest);
}
if (statusCode == PROXY_AUTHENTICATION_REQUIRED_407) {
return proxyUnauthorized407Interceptor.exitAfterHandling407(channel, future, response, request, proxyServer, httpRequest);
}
if (statusCode == CONTINUE_100) {
return continue100Interceptor.exitAfterHandling100(channel, future);
}
if (Redirect30xInterceptor.REDIRECT_STATUSES.contains(statusCode)) {
return redirect30xInterceptor.exitAfterHandlingRedirect(channel, future, response, request, statusCode, realm);
}
if (httpRequest.method() == HttpMethod.CONNECT && statusCode == OK_200) {
return connectSuccessInterceptor.exitAfterHandlingConnect(channel, future, request, proxyServer);
}
return false;
| 486
| 560
| 1,046
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ProxyUnauthorized407Interceptor.java
|
ProxyUnauthorized407Interceptor
|
exitAfterHandling407
|
class ProxyUnauthorized407Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(ProxyUnauthorized407Interceptor.class);
private final ChannelManager channelManager;
private final NettyRequestSender requestSender;
ProxyUnauthorized407Interceptor(ChannelManager channelManager, NettyRequestSender requestSender) {
this.channelManager = channelManager;
this.requestSender = requestSender;
}
public boolean exitAfterHandling407(Channel channel, NettyResponseFuture<?> future, HttpResponse response, Request request,
ProxyServer proxyServer, HttpRequest httpRequest) {<FILL_FUNCTION_BODY>}
private static void kerberosProxyChallenge(Realm proxyRealm, ProxyServer proxyServer, HttpHeaders headers) throws SpnegoEngineException {
String challengeHeader = SpnegoEngine.instance(proxyRealm.getPrincipal(),
proxyRealm.getPassword(),
proxyRealm.getServicePrincipalName(),
proxyRealm.getRealmName(),
proxyRealm.isUseCanonicalHostname(),
proxyRealm.getCustomLoginConfig(),
proxyRealm.getLoginContextName()).generateToken(proxyServer.getHost());
headers.set(PROXY_AUTHORIZATION, NEGOTIATE + ' ' + challengeHeader);
}
private static void ntlmProxyChallenge(String authenticateHeader, HttpHeaders requestHeaders, Realm proxyRealm, NettyResponseFuture<?> future) {
if ("NTLM".equals(authenticateHeader)) {
// server replied bare NTLM => we didn't preemptively send Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
future.setInProxyAuth(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.generateType3Msg(proxyRealm.getPrincipal(), proxyRealm.getPassword(), proxyRealm.getNtlmDomain(),
proxyRealm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(PROXY_AUTHORIZATION, "NTLM " + challengeHeader);
}
}
}
|
if (future.isAndSetInProxyAuth(true)) {
LOGGER.info("Can't handle 407 as auth was already performed");
return false;
}
Realm proxyRealm = future.getProxyRealm();
if (proxyRealm == null) {
LOGGER.debug("Can't handle 407 as there's no proxyRealm");
return false;
}
List<String> proxyAuthHeaders = response.headers().getAll(PROXY_AUTHENTICATE);
if (proxyAuthHeaders.isEmpty()) {
LOGGER.info("Can't handle 407 as response doesn't contain Proxy-Authenticate headers");
return false;
}
// FIXME what's this???
future.setChannelState(ChannelState.NEW);
HttpHeaders requestHeaders = new DefaultHttpHeaders().add(request.getHeaders());
switch (proxyRealm.getScheme()) {
case BASIC:
if (getHeaderWithPrefix(proxyAuthHeaders, "Basic") == null) {
LOGGER.info("Can't handle 407 with Basic realm as Proxy-Authenticate headers don't match");
return false;
}
if (proxyRealm.isUsePreemptiveAuth()) {
// FIXME do we need this, as future.getAndSetAuth
// was tested above?
// auth was already performed, most likely auth
// failed
LOGGER.info("Can't handle 407 with Basic realm as auth was preemptive and already performed");
return false;
}
// FIXME do we want to update the realm, or directly
// set the header?
Realm newBasicRealm = realm(proxyRealm)
.setUsePreemptiveAuth(true)
.build();
future.setProxyRealm(newBasicRealm);
break;
case DIGEST:
String digestHeader = getHeaderWithPrefix(proxyAuthHeaders, "Digest");
if (digestHeader == null) {
LOGGER.info("Can't handle 407 with Digest realm as Proxy-Authenticate headers don't match");
return false;
}
Realm newDigestRealm = realm(proxyRealm)
.setUri(request.getUri())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseProxyAuthenticateHeader(digestHeader)
.build();
future.setProxyRealm(newDigestRealm);
break;
case NTLM:
String ntlmHeader = getHeaderWithPrefix(proxyAuthHeaders, "NTLM");
if (ntlmHeader == null) {
LOGGER.info("Can't handle 407 with NTLM realm as Proxy-Authenticate headers don't match");
return false;
}
ntlmProxyChallenge(ntlmHeader, requestHeaders, proxyRealm, future);
Realm newNtlmRealm = realm(proxyRealm)
.setUsePreemptiveAuth(true)
.build();
future.setProxyRealm(newNtlmRealm);
break;
case KERBEROS:
case SPNEGO:
if (getHeaderWithPrefix(proxyAuthHeaders, NEGOTIATE) == null) {
LOGGER.info("Can't handle 407 with Kerberos or Spnego realm as Proxy-Authenticate headers don't match");
return false;
}
try {
kerberosProxyChallenge(proxyRealm, proxyServer, requestHeaders);
} catch (SpnegoEngineException e) {
String ntlmHeader2 = getHeaderWithPrefix(proxyAuthHeaders, "NTLM");
if (ntlmHeader2 != null) {
LOGGER.warn("Kerberos/Spnego proxy auth failed, proceeding with NTLM");
ntlmProxyChallenge(ntlmHeader2, requestHeaders, proxyRealm, future);
Realm newNtlmRealm2 = realm(proxyRealm)
.setScheme(AuthScheme.NTLM)
.setUsePreemptiveAuth(true)
.build();
future.setProxyRealm(newNtlmRealm2);
} else {
requestSender.abort(channel, future, e);
return false;
}
}
break;
default:
throw new IllegalStateException("Invalid Authentication scheme " + proxyRealm.getScheme());
}
RequestBuilder nextRequestBuilder = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders);
if (future.getCurrentRequest().getUri().isSecured()) {
nextRequestBuilder.setMethod(CONNECT);
}
final Request nextRequest = nextRequestBuilder.build();
LOGGER.debug("Sending proxy authentication to {}", request.getUri());
if (future.isKeepAlive()
&& !HttpUtil.isTransferEncodingChunked(httpRequest)
&& !HttpUtil.isTransferEncodingChunked(response)) {
future.setConnectAllowed(true);
future.setReuseChannel(true);
requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
} else {
channelManager.closeChannel(channel);
requestSender.sendNextRequest(nextRequest, future);
}
return true;
| 653
| 1,358
| 2,011
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Redirect30xInterceptor.java
|
Redirect30xInterceptor
|
exitAfterHandlingRedirect
|
class Redirect30xInterceptor {
public static final Set<Integer> REDIRECT_STATUSES = new HashSet<>();
private static final Logger LOGGER = LoggerFactory.getLogger(Redirect30xInterceptor.class);
static {
REDIRECT_STATUSES.add(MOVED_PERMANENTLY_301);
REDIRECT_STATUSES.add(FOUND_302);
REDIRECT_STATUSES.add(SEE_OTHER_303);
REDIRECT_STATUSES.add(TEMPORARY_REDIRECT_307);
REDIRECT_STATUSES.add(PERMANENT_REDIRECT_308);
}
private final ChannelManager channelManager;
private final AsyncHttpClientConfig config;
private final NettyRequestSender requestSender;
private final MaxRedirectException maxRedirectException;
Redirect30xInterceptor(ChannelManager channelManager, AsyncHttpClientConfig config, NettyRequestSender requestSender) {
this.channelManager = channelManager;
this.config = config;
this.requestSender = requestSender;
maxRedirectException = unknownStackTrace(new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects()),
Redirect30xInterceptor.class, "exitAfterHandlingRedirect");
}
public boolean exitAfterHandlingRedirect(Channel channel, NettyResponseFuture<?> future, HttpResponse response, Request request,
int statusCode, Realm realm) throws Exception {<FILL_FUNCTION_BODY>}
private static HttpHeaders propagatedHeaders(Request request, Realm realm, boolean keepBody) {
HttpHeaders headers = request.getHeaders()
.remove(HOST)
.remove(CONTENT_LENGTH);
if (!keepBody) {
headers.remove(CONTENT_TYPE);
}
if (realm != null && realm.getScheme() == AuthScheme.NTLM) {
headers.remove(AUTHORIZATION)
.remove(PROXY_AUTHORIZATION);
}
return headers;
}
}
|
if (followRedirect(config, request)) {
if (future.incrementAndGetCurrentRedirectCount() >= config.getMaxRedirects()) {
throw maxRedirectException;
} else {
// We must allow auth handling again.
future.setInAuth(false);
future.setInProxyAuth(false);
String originalMethod = request.getMethod();
boolean switchToGet = !originalMethod.equals(GET) &&
!originalMethod.equals(OPTIONS) &&
!originalMethod.equals(HEAD) &&
(statusCode == MOVED_PERMANENTLY_301 || statusCode == SEE_OTHER_303 || statusCode == FOUND_302 && !config.isStrict302Handling());
boolean keepBody = statusCode == TEMPORARY_REDIRECT_307 || statusCode == PERMANENT_REDIRECT_308 || statusCode == FOUND_302 && config.isStrict302Handling();
final RequestBuilder requestBuilder = new RequestBuilder(switchToGet ? GET : originalMethod)
.setChannelPoolPartitioning(request.getChannelPoolPartitioning())
.setFollowRedirect(true)
.setLocalAddress(request.getLocalAddress())
.setNameResolver(request.getNameResolver())
.setProxyServer(request.getProxyServer())
.setRealm(request.getRealm())
.setRequestTimeout(request.getRequestTimeout());
if (keepBody) {
requestBuilder.setCharset(request.getCharset());
if (isNonEmpty(request.getFormParams())) {
requestBuilder.setFormParams(request.getFormParams());
} else if (request.getStringData() != null) {
requestBuilder.setBody(request.getStringData());
} else if (request.getByteData() != null) {
requestBuilder.setBody(request.getByteData());
} else if (request.getByteBufferData() != null) {
requestBuilder.setBody(request.getByteBufferData());
} else if (request.getBodyGenerator() != null) {
requestBuilder.setBody(request.getBodyGenerator());
} else if (isNonEmpty(request.getBodyParts())) {
requestBuilder.setBodyParts(request.getBodyParts());
}
}
requestBuilder.setHeaders(propagatedHeaders(request, realm, keepBody));
// in case of a redirect from HTTP to HTTPS, future
// attributes might change
final boolean initialConnectionKeepAlive = future.isKeepAlive();
final Object initialPartitionKey = future.getPartitionKey();
HttpHeaders responseHeaders = response.headers();
String location = responseHeaders.get(LOCATION);
Uri newUri = Uri.create(future.getUri(), location);
LOGGER.debug("Redirecting to {}", newUri);
CookieStore cookieStore = config.getCookieStore();
if (cookieStore != null) {
// Update request's cookies assuming that cookie store is already updated by Interceptors
List<Cookie> cookies = cookieStore.get(newUri);
if (!cookies.isEmpty()) {
for (Cookie cookie : cookies) {
requestBuilder.addOrReplaceCookie(cookie);
}
}
}
boolean sameBase = request.getUri().isSameBase(newUri);
if (sameBase) {
// we can only assume the virtual host is still valid if the baseUrl is the same
requestBuilder.setVirtualHost(request.getVirtualHost());
}
final Request nextRequest = requestBuilder.setUri(newUri).build();
future.setTargetRequest(nextRequest);
LOGGER.debug("Sending redirect to {}", newUri);
if (future.isKeepAlive() && !HttpUtil.isTransferEncodingChunked(response)) {
if (sameBase) {
future.setReuseChannel(true);
// we can't directly send the next request because we still have to received LastContent
requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
} else {
channelManager.drainChannelAndOffer(channel, future, initialConnectionKeepAlive, initialPartitionKey);
requestSender.sendNextRequest(nextRequest, future);
}
} else {
// redirect + chunking = WAT
channelManager.closeChannel(channel);
requestSender.sendNextRequest(nextRequest, future);
}
return true;
}
}
return false;
| 554
| 1,137
| 1,691
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/ResponseFiltersInterceptor.java
|
ResponseFiltersInterceptor
|
exitAfterProcessingFilters
|
class ResponseFiltersInterceptor {
private final AsyncHttpClientConfig config;
private final NettyRequestSender requestSender;
ResponseFiltersInterceptor(AsyncHttpClientConfig config, NettyRequestSender requestSender) {
this.config = config;
this.requestSender = requestSender;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public boolean exitAfterProcessingFilters(Channel channel,
NettyResponseFuture<?> future,
AsyncHandler<?> handler,
HttpResponseStatus status,
HttpHeaders responseHeaders) {<FILL_FUNCTION_BODY>}
}
|
FilterContext fc = new FilterContext.FilterContextBuilder(handler, future.getCurrentRequest()).responseStatus(status)
.responseHeaders(responseHeaders).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
try {
fc = asyncFilter.filter(fc);
// FIXME Is it worth protecting against this?
// requireNonNull(fc, "filterContext");
} catch (FilterException fe) {
requestSender.abort(channel, future, fe);
}
}
// The handler may have been wrapped.
future.setAsyncHandler(fc.getAsyncHandler());
// The request has changed
if (fc.replayRequest()) {
requestSender.replayRequest(future, fc, channel);
return true;
}
return false;
| 170
| 208
| 378
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/handler/intercept/Unauthorized401Interceptor.java
|
Unauthorized401Interceptor
|
exitAfterHandling401
|
class Unauthorized401Interceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(Unauthorized401Interceptor.class);
private final ChannelManager channelManager;
private final NettyRequestSender requestSender;
Unauthorized401Interceptor(ChannelManager channelManager, NettyRequestSender requestSender) {
this.channelManager = channelManager;
this.requestSender = requestSender;
}
public boolean exitAfterHandling401(Channel channel, NettyResponseFuture<?> future, HttpResponse response, Request request, Realm realm, HttpRequest httpRequest) {<FILL_FUNCTION_BODY>}
private static void ntlmChallenge(String authenticateHeader,
HttpHeaders requestHeaders,
Realm realm,
NettyResponseFuture<?> future) {
if ("NTLM".equals(authenticateHeader)) {
// server replied bare NTLM => we didn't preemptively send Type1Msg
String challengeHeader = NtlmEngine.INSTANCE.generateType1Msg();
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(AUTHORIZATION, "NTLM " + challengeHeader);
future.setInAuth(false);
} else {
String serverChallenge = authenticateHeader.substring("NTLM ".length()).trim();
String challengeHeader = NtlmEngine.generateType3Msg(realm.getPrincipal(), realm.getPassword(),
realm.getNtlmDomain(), realm.getNtlmHost(), serverChallenge);
// FIXME we might want to filter current NTLM and add (leave other
// Authorization headers untouched)
requestHeaders.set(AUTHORIZATION, "NTLM " + challengeHeader);
}
}
private static void kerberosChallenge(Realm realm, Request request, HttpHeaders headers) throws SpnegoEngineException {
Uri uri = request.getUri();
String host = withDefault(request.getVirtualHost(), uri.getHost());
String challengeHeader = SpnegoEngine.instance(realm.getPrincipal(),
realm.getPassword(),
realm.getServicePrincipalName(),
realm.getRealmName(),
realm.isUseCanonicalHostname(),
realm.getCustomLoginConfig(),
realm.getLoginContextName()).generateToken(host);
headers.set(AUTHORIZATION, NEGOTIATE + ' ' + challengeHeader);
}
}
|
if (realm == null) {
LOGGER.debug("Can't handle 401 as there's no realm");
return false;
}
if (future.isAndSetInAuth(true)) {
LOGGER.info("Can't handle 401 as auth was already performed");
return false;
}
List<String> wwwAuthHeaders = response.headers().getAll(WWW_AUTHENTICATE);
if (wwwAuthHeaders.isEmpty()) {
LOGGER.info("Can't handle 401 as response doesn't contain WWW-Authenticate headers");
return false;
}
// FIXME what's this???
future.setChannelState(ChannelState.NEW);
HttpHeaders requestHeaders = new DefaultHttpHeaders().add(request.getHeaders());
switch (realm.getScheme()) {
case BASIC:
if (getHeaderWithPrefix(wwwAuthHeaders, "Basic") == null) {
LOGGER.info("Can't handle 401 with Basic realm as WWW-Authenticate headers don't match");
return false;
}
if (realm.isUsePreemptiveAuth()) {
// FIXME do we need this, as future.getAndSetAuth
// was tested above?
// auth was already performed, most likely auth
// failed
LOGGER.info("Can't handle 401 with Basic realm as auth was preemptive and already performed");
return false;
}
// FIXME do we want to update the realm, or directly
// set the header?
Realm newBasicRealm = realm(realm)
.setUsePreemptiveAuth(true)
.build();
future.setRealm(newBasicRealm);
break;
case DIGEST:
String digestHeader = getHeaderWithPrefix(wwwAuthHeaders, "Digest");
if (digestHeader == null) {
LOGGER.info("Can't handle 401 with Digest realm as WWW-Authenticate headers don't match");
return false;
}
Realm newDigestRealm = realm(realm)
.setUri(request.getUri())
.setMethodName(request.getMethod())
.setUsePreemptiveAuth(true)
.parseWWWAuthenticateHeader(digestHeader)
.build();
future.setRealm(newDigestRealm);
break;
case NTLM:
String ntlmHeader = getHeaderWithPrefix(wwwAuthHeaders, "NTLM");
if (ntlmHeader == null) {
LOGGER.info("Can't handle 401 with NTLM realm as WWW-Authenticate headers don't match");
return false;
}
ntlmChallenge(ntlmHeader, requestHeaders, realm, future);
Realm newNtlmRealm = realm(realm)
.setUsePreemptiveAuth(true)
.build();
future.setRealm(newNtlmRealm);
break;
case KERBEROS:
case SPNEGO:
if (getHeaderWithPrefix(wwwAuthHeaders, NEGOTIATE) == null) {
LOGGER.info("Can't handle 401 with Kerberos or Spnego realm as WWW-Authenticate headers don't match");
return false;
}
try {
kerberosChallenge(realm, request, requestHeaders);
} catch (SpnegoEngineException e) {
String ntlmHeader2 = getHeaderWithPrefix(wwwAuthHeaders, "NTLM");
if (ntlmHeader2 != null) {
LOGGER.warn("Kerberos/Spnego auth failed, proceeding with NTLM");
ntlmChallenge(ntlmHeader2, requestHeaders, realm, future);
Realm newNtlmRealm2 = realm(realm)
.setScheme(AuthScheme.NTLM)
.setUsePreemptiveAuth(true)
.build();
future.setRealm(newNtlmRealm2);
} else {
requestSender.abort(channel, future, e);
return false;
}
}
break;
default:
throw new IllegalStateException("Invalid Authentication scheme " + realm.getScheme());
}
final Request nextRequest = future.getCurrentRequest().toBuilder().setHeaders(requestHeaders).build();
LOGGER.debug("Sending authentication to {}", request.getUri());
if (future.isKeepAlive() && !HttpUtil.isTransferEncodingChunked(httpRequest) && !HttpUtil.isTransferEncodingChunked(response)) {
future.setReuseChannel(true);
requestSender.drainChannelAndExecuteNextRequest(channel, future, nextRequest);
} else {
channelManager.closeChannel(channel);
requestSender.sendNextRequest(nextRequest, future);
}
return true;
| 639
| 1,255
| 1,894
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/WriteListener.java
|
WriteListener
|
operationComplete
|
class WriteListener {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteListener.class);
protected final NettyResponseFuture<?> future;
final ProgressAsyncHandler<?> progressAsyncHandler;
final boolean notifyHeaders;
WriteListener(NettyResponseFuture<?> future, boolean notifyHeaders) {
this.future = future;
progressAsyncHandler = future.getAsyncHandler() instanceof ProgressAsyncHandler ? (ProgressAsyncHandler<?>) future.getAsyncHandler() : null;
this.notifyHeaders = notifyHeaders;
}
private void abortOnThrowable(Channel channel, Throwable cause) {
if (future.getChannelState() == ChannelState.POOLED && (cause instanceof IllegalStateException ||
cause instanceof ClosedChannelException ||
cause instanceof SSLException ||
StackTraceInspector.recoverOnReadOrWriteException(cause))) {
LOGGER.debug("Write exception on pooled channel, letting retry trigger", cause);
} else {
future.abort(cause);
}
Channels.silentlyCloseChannel(channel);
}
void operationComplete(Channel channel, Throwable cause) {<FILL_FUNCTION_BODY>}
}
|
future.touch();
// The write operation failed. If the channel was pooled, it means it got asynchronously closed.
// Let's retry a second time.
if (cause != null) {
abortOnThrowable(channel, cause);
return;
}
if (progressAsyncHandler != null) {
// We need to make sure we aren't in the middle of an authorization process before publishing events as we will re-publish again the same event after the authorization,
// causing unpredictable behavior.
boolean startPublishing = !future.isInAuth() && !future.isInProxyAuth();
if (startPublishing) {
if (notifyHeaders) {
progressAsyncHandler.onHeadersWritten();
} else {
progressAsyncHandler.onContentWritten();
}
}
}
| 298
| 213
| 511
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/WriteProgressListener.java
|
WriteProgressListener
|
operationProgressed
|
class WriteProgressListener extends WriteListener implements ChannelProgressiveFutureListener {
private final long expectedTotal;
private long lastProgress;
public WriteProgressListener(NettyResponseFuture<?> future, boolean notifyHeaders, long expectedTotal) {
super(future, notifyHeaders);
this.expectedTotal = expectedTotal;
}
@Override
public void operationComplete(ChannelProgressiveFuture cf) {
operationComplete(cf.channel(), cf.cause());
}
@Override
public void operationProgressed(ChannelProgressiveFuture f, long progress, long total) {<FILL_FUNCTION_BODY>}
}
|
future.touch();
if (progressAsyncHandler != null && !notifyHeaders) {
long lastLastProgress = lastProgress;
lastProgress = progress;
if (total < 0) {
total = expectedTotal;
}
if (progress != lastLastProgress) {
progressAsyncHandler.onContentWriteProgress(progress - lastLastProgress, progress, total);
}
}
| 154
| 101
| 255
|
<methods><variables>private static final Logger LOGGER,protected final non-sealed NettyResponseFuture<?> future,final non-sealed boolean notifyHeaders,final non-sealed ProgressAsyncHandler<?> progressAsyncHandler
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/BodyChunkedInput.java
|
BodyChunkedInput
|
readChunk
|
class BodyChunkedInput implements ChunkedInput<ByteBuf> {
public static final int DEFAULT_CHUNK_SIZE = 8 * 1024;
private final Body body;
private final int chunkSize;
private final long contentLength;
private boolean endOfInput;
private long progress;
BodyChunkedInput(Body body) {
this.body = requireNonNull(body, "body");
contentLength = body.getContentLength();
if (contentLength <= 0) {
chunkSize = DEFAULT_CHUNK_SIZE;
} else {
chunkSize = (int) Math.min(contentLength, DEFAULT_CHUNK_SIZE);
}
}
@Override
@Deprecated
public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception {
return readChunk(ctx.alloc());
}
@Override
public ByteBuf readChunk(ByteBufAllocator alloc) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public boolean isEndOfInput() {
return endOfInput;
}
@Override
public void close() throws Exception {
body.close();
}
@Override
public long length() {
return contentLength;
}
@Override
public long progress() {
return progress;
}
}
|
if (endOfInput) {
return null;
}
ByteBuf buffer = alloc.buffer(chunkSize);
Body.BodyState state = body.transferTo(buffer);
progress += buffer.writerIndex();
switch (state) {
case STOP:
endOfInput = true;
return buffer;
case SUSPEND:
// this will suspend the stream in ChunkedWriteHandler
buffer.release();
return null;
case CONTINUE:
return buffer;
default:
throw new IllegalStateException("Unknown state: " + state);
}
| 341
| 153
| 494
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/BodyFileRegion.java
|
BodyFileRegion
|
transferTo
|
class BodyFileRegion extends AbstractReferenceCounted implements FileRegion {
private final RandomAccessBody body;
private long transferred;
BodyFileRegion(RandomAccessBody body) {
this.body = requireNonNull(body, "body");
}
@Override
public long position() {
return 0;
}
@Override
public long count() {
return body.getContentLength();
}
@Override
public long transfered() {
return transferred();
}
@Override
public long transferred() {
return transferred;
}
@Override
public FileRegion retain() {
super.retain();
return this;
}
@Override
public FileRegion retain(int increment) {
super.retain(increment);
return this;
}
@Override
public FileRegion touch() {
return this;
}
@Override
public FileRegion touch(Object hint) {
return this;
}
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {<FILL_FUNCTION_BODY>}
@Override
protected void deallocate() {
closeSilently(body);
}
}
|
long written = body.transferTo(target);
if (written > 0) {
transferred += written;
}
return written;
| 318
| 39
| 357
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/NettyBodyBody.java
|
NettyBodyBody
|
write
|
class NettyBodyBody implements NettyBody {
private final Body body;
private final AsyncHttpClientConfig config;
public NettyBodyBody(Body body, AsyncHttpClientConfig config) {
this.body = body;
this.config = config;
}
public Body getBody() {
return body;
}
@Override
public long getContentLength() {
return body.getContentLength();
}
@Override
public void write(final Channel channel, NettyResponseFuture<?> future) {<FILL_FUNCTION_BODY>}
}
|
Object msg;
if (body instanceof RandomAccessBody && !ChannelManager.isSslHandlerConfigured(channel.pipeline()) && !config.isDisableZeroCopy() && getContentLength() > 0) {
msg = new BodyFileRegion((RandomAccessBody) body);
} else {
msg = new BodyChunkedInput(body);
BodyGenerator bg = future.getTargetRequest().getBodyGenerator();
if (bg instanceof FeedableBodyGenerator) {
final ChunkedWriteHandler chunkedWriteHandler = channel.pipeline().get(ChunkedWriteHandler.class);
((FeedableBodyGenerator) bg).setListener(new FeedListener() {
@Override
public void onContentAdded() {
chunkedWriteHandler.resumeTransfer();
}
@Override
public void onError(Throwable t) {
}
});
}
}
channel.write(msg, channel.newProgressivePromise())
.addListener(new WriteProgressListener(future, false, getContentLength()) {
@Override
public void operationComplete(ChannelProgressiveFuture cf) {
closeSilently(body);
super.operationComplete(cf);
}
});
channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, channel.voidPromise());
| 151
| 326
| 477
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/NettyDirectBody.java
|
NettyDirectBody
|
write
|
class NettyDirectBody implements NettyBody {
public abstract ByteBuf byteBuf();
@Override
public void write(Channel channel, NettyResponseFuture<?> future) {<FILL_FUNCTION_BODY>}
}
|
throw new UnsupportedOperationException("This kind of body is supposed to be written directly");
| 59
| 23
| 82
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/NettyFileBody.java
|
NettyFileBody
|
write
|
class NettyFileBody implements NettyBody {
private final File file;
private final long offset;
private final long length;
private final AsyncHttpClientConfig config;
public NettyFileBody(File file, AsyncHttpClientConfig config) {
this(file, 0, file.length(), config);
}
public NettyFileBody(File file, long offset, long length, AsyncHttpClientConfig config) {
if (!file.isFile()) {
throw new IllegalArgumentException(String.format("File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
this.file = file;
this.offset = offset;
this.length = length;
this.config = config;
}
public File getFile() {
return file;
}
@Override
public long getContentLength() {
return length;
}
@Override
public void write(Channel channel, NettyResponseFuture<?> future) throws IOException {<FILL_FUNCTION_BODY>}
}
|
@SuppressWarnings("resource")
// netty will close the FileChannel
FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();
boolean noZeroCopy = ChannelManager.isSslHandlerConfigured(channel.pipeline()) || config.isDisableZeroCopy();
Object body = noZeroCopy ? new ChunkedNioFile(fileChannel, offset, length, config.getChunkedFileChunkSize()) : new DefaultFileRegion(fileChannel, offset, length);
channel.write(body, channel.newProgressivePromise())
.addListener(new WriteProgressListener(future, false, length));
channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, channel.voidPromise());
| 266
| 185
| 451
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/request/body/NettyInputStreamBody.java
|
NettyInputStreamBody
|
write
|
class NettyInputStreamBody implements NettyBody {
private static final Logger LOGGER = LoggerFactory.getLogger(NettyInputStreamBody.class);
private final InputStream inputStream;
private final long contentLength;
public NettyInputStreamBody(InputStream inputStream) {
this(inputStream, -1L);
}
public NettyInputStreamBody(InputStream inputStream, long contentLength) {
this.inputStream = inputStream;
this.contentLength = contentLength;
}
public InputStream getInputStream() {
return inputStream;
}
@Override
public long getContentLength() {
return contentLength;
}
@Override
public void write(Channel channel, NettyResponseFuture<?> future) throws IOException {<FILL_FUNCTION_BODY>}
}
|
final InputStream is = inputStream;
if (future.isStreamConsumed()) {
if (is.markSupported()) {
is.reset();
} else {
LOGGER.warn("Stream has already been consumed and cannot be reset");
return;
}
} else {
future.setStreamConsumed(true);
}
channel.write(new ChunkedStream(is), channel.newProgressivePromise()).addListener(
new WriteProgressListener(future, false, getContentLength()) {
@Override
public void operationComplete(ChannelProgressiveFuture cf) {
closeSilently(is);
super.operationComplete(cf);
}
});
channel.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT, channel.voidPromise());
| 205
| 203
| 408
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/ssl/DefaultSslEngineFactory.java
|
DefaultSslEngineFactory
|
newSslEngine
|
class DefaultSslEngineFactory extends SslEngineFactoryBase {
private volatile SslContext sslContext;
private SslContext buildSslContext(AsyncHttpClientConfig config) throws SSLException {
if (config.getSslContext() != null) {
return config.getSslContext();
}
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()
.sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)
.sessionCacheSize(config.getSslSessionCacheSize())
.sessionTimeout(config.getSslSessionTimeout());
if (isNonEmpty(config.getEnabledProtocols())) {
sslContextBuilder.protocols(config.getEnabledProtocols());
}
if (isNonEmpty(config.getEnabledCipherSuites())) {
sslContextBuilder.ciphers(Arrays.asList(config.getEnabledCipherSuites()));
} else if (!config.isFilterInsecureCipherSuites()) {
sslContextBuilder.ciphers(null, IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS);
}
if (config.isUseInsecureTrustManager()) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
return configureSslContextBuilder(sslContextBuilder).build();
}
@Override
public SSLEngine newSslEngine(AsyncHttpClientConfig config, String peerHost, int peerPort) {<FILL_FUNCTION_BODY>}
@Override
public void init(AsyncHttpClientConfig config) throws SSLException {
sslContext = buildSslContext(config);
}
@Override
public void destroy() {
ReferenceCountUtil.release(sslContext);
}
/**
* The last step of configuring the SslContextBuilder used to create an SslContext when no context is provided in the {@link AsyncHttpClientConfig}. This defaults to no-op and
* is intended to be overridden as needed.
*
* @param builder builder with normal configuration applied
* @return builder to be used to build context (can be the same object as the input)
*/
protected SslContextBuilder configureSslContextBuilder(SslContextBuilder builder) {
// default to no op
return builder;
}
}
|
SSLEngine sslEngine = config.isDisableHttpsEndpointIdentificationAlgorithm() ?
sslContext.newEngine(ByteBufAllocator.DEFAULT) :
sslContext.newEngine(ByteBufAllocator.DEFAULT, domain(peerHost), peerPort);
configureSslEngine(sslEngine, config);
return sslEngine;
| 605
| 89
| 694
|
<methods>public non-sealed void <init>() <variables>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/ssl/JsseSslEngineFactory.java
|
JsseSslEngineFactory
|
newSslEngine
|
class JsseSslEngineFactory extends SslEngineFactoryBase {
private final SSLContext sslContext;
public JsseSslEngineFactory(SSLContext sslContext) {
this.sslContext = sslContext;
}
@Override
public SSLEngine newSslEngine(AsyncHttpClientConfig config, String peerHost, int peerPort) {<FILL_FUNCTION_BODY>}
}
|
SSLEngine sslEngine = sslContext.createSSLEngine(domain(peerHost), peerPort);
configureSslEngine(sslEngine, config);
return sslEngine;
| 106
| 51
| 157
|
<methods>public non-sealed void <init>() <variables>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/ssl/SslEngineFactoryBase.java
|
SslEngineFactoryBase
|
configureSslEngine
|
class SslEngineFactoryBase implements SslEngineFactory {
protected String domain(String hostname) {
int fqdnLength = hostname.length() - 1;
return hostname.charAt(fqdnLength) == '.' ? hostname.substring(0, fqdnLength) : hostname;
}
protected void configureSslEngine(SSLEngine sslEngine, AsyncHttpClientConfig config) {<FILL_FUNCTION_BODY>}
}
|
sslEngine.setUseClientMode(true);
if (!config.isDisableHttpsEndpointIdentificationAlgorithm()) {
SSLParameters params = sslEngine.getSSLParameters();
params.setEndpointIdentificationAlgorithm("HTTPS");
sslEngine.setSSLParameters(params);
}
| 120
| 79
| 199
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/timeout/ReadTimeoutTimerTask.java
|
ReadTimeoutTimerTask
|
run
|
class ReadTimeoutTimerTask extends TimeoutTimerTask {
private final long readTimeout;
ReadTimeoutTimerTask(NettyResponseFuture<?> nettyResponseFuture, NettyRequestSender requestSender, TimeoutsHolder timeoutsHolder, long readTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.readTimeout = readTimeout;
}
@Override
public void run(Timeout timeout) {<FILL_FUNCTION_BODY>}
}
|
if (done.getAndSet(true) || requestSender.isClosed()) {
return;
}
if (nettyResponseFuture.isDone()) {
timeoutsHolder.cancel();
return;
}
long now = unpreciseMillisTime();
long currentReadTimeoutInstant = readTimeout + nettyResponseFuture.getLastTouch();
long durationBeforeCurrentReadTimeout = currentReadTimeoutInstant - now;
if (durationBeforeCurrentReadTimeout <= 0L) {
// idleConnectTimeout reached
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder().append("Read timeout to ");
appendRemoteAddress(sb);
String message = sb.append(" after ").append(readTimeout).append(" ms").toString();
long durationSinceLastTouch = now - nettyResponseFuture.getLastTouch();
expire(message, durationSinceLastTouch);
// cancel request timeout sibling
timeoutsHolder.cancel();
} else {
done.set(false);
timeoutsHolder.startReadTimeout(this);
}
| 121
| 263
| 384
|
<methods>public void clean() <variables>private static final Logger LOGGER,protected final java.util.concurrent.atomic.AtomicBoolean done,volatile NettyResponseFuture<?> nettyResponseFuture,protected final non-sealed org.asynchttpclient.netty.request.NettyRequestSender requestSender,final non-sealed org.asynchttpclient.netty.timeout.TimeoutsHolder timeoutsHolder
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/timeout/RequestTimeoutTimerTask.java
|
RequestTimeoutTimerTask
|
run
|
class RequestTimeoutTimerTask extends TimeoutTimerTask {
private final long requestTimeout;
RequestTimeoutTimerTask(NettyResponseFuture<?> nettyResponseFuture,
NettyRequestSender requestSender,
TimeoutsHolder timeoutsHolder,
long requestTimeout) {
super(nettyResponseFuture, requestSender, timeoutsHolder);
this.requestTimeout = requestTimeout;
}
@Override
public void run(Timeout timeout) {<FILL_FUNCTION_BODY>}
}
|
if (done.getAndSet(true) || requestSender.isClosed()) {
return;
}
// in any case, cancel possible readTimeout sibling
timeoutsHolder.cancel();
if (nettyResponseFuture.isDone()) {
return;
}
StringBuilder sb = StringBuilderPool.DEFAULT.stringBuilder().append("Request timeout to ");
appendRemoteAddress(sb);
String message = sb.append(" after ").append(requestTimeout).append(" ms").toString();
long age = unpreciseMillisTime() - nettyResponseFuture.getStart();
expire(message, age);
| 127
| 158
| 285
|
<methods>public void clean() <variables>private static final Logger LOGGER,protected final java.util.concurrent.atomic.AtomicBoolean done,volatile NettyResponseFuture<?> nettyResponseFuture,protected final non-sealed org.asynchttpclient.netty.request.NettyRequestSender requestSender,final non-sealed org.asynchttpclient.netty.timeout.TimeoutsHolder timeoutsHolder
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/timeout/TimeoutTimerTask.java
|
TimeoutTimerTask
|
expire
|
class TimeoutTimerTask implements TimerTask {
private static final Logger LOGGER = LoggerFactory.getLogger(TimeoutTimerTask.class);
protected final AtomicBoolean done = new AtomicBoolean();
protected final NettyRequestSender requestSender;
final TimeoutsHolder timeoutsHolder;
volatile NettyResponseFuture<?> nettyResponseFuture;
TimeoutTimerTask(NettyResponseFuture<?> nettyResponseFuture, NettyRequestSender requestSender, TimeoutsHolder timeoutsHolder) {
this.nettyResponseFuture = nettyResponseFuture;
this.requestSender = requestSender;
this.timeoutsHolder = timeoutsHolder;
}
void expire(String message, long time) {<FILL_FUNCTION_BODY>}
/**
* When the timeout is cancelled, it could still be referenced for quite some time in the Timer. Holding a reference to the future might mean holding a reference to the
* channel, and heavy objects such as SslEngines
*/
public void clean() {
if (done.compareAndSet(false, true)) {
nettyResponseFuture = null;
}
}
void appendRemoteAddress(StringBuilder sb) {
InetSocketAddress remoteAddress = timeoutsHolder.remoteAddress();
sb.append(remoteAddress.getHostString());
if (!remoteAddress.isUnresolved()) {
sb.append('/').append(remoteAddress.getAddress().getHostAddress());
}
sb.append(':').append(remoteAddress.getPort());
}
}
|
LOGGER.debug("{} for {} after {} ms", message, nettyResponseFuture, time);
requestSender.abort(nettyResponseFuture.channel(), nettyResponseFuture, new TimeoutException(message));
| 385
| 54
| 439
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/netty/timeout/TimeoutsHolder.java
|
TimeoutsHolder
|
startReadTimeout
|
class TimeoutsHolder {
private final Timeout requestTimeout;
private final AtomicBoolean cancelled = new AtomicBoolean();
private final Timer nettyTimer;
private final NettyRequestSender requestSender;
private final long requestTimeoutMillisTime;
private final long readTimeoutValue;
private volatile Timeout readTimeout;
private final NettyResponseFuture<?> nettyResponseFuture;
private volatile InetSocketAddress remoteAddress;
public TimeoutsHolder(Timer nettyTimer, NettyResponseFuture<?> nettyResponseFuture, NettyRequestSender requestSender,
AsyncHttpClientConfig config, InetSocketAddress originalRemoteAddress) {
this.nettyTimer = nettyTimer;
this.nettyResponseFuture = nettyResponseFuture;
this.requestSender = requestSender;
remoteAddress = originalRemoteAddress;
final Request targetRequest = nettyResponseFuture.getTargetRequest();
final long readTimeoutInMs = targetRequest.getReadTimeout().toMillis();
readTimeoutValue = readTimeoutInMs == 0 ? config.getReadTimeout().toMillis() : readTimeoutInMs;
long requestTimeoutInMs = targetRequest.getRequestTimeout().toMillis();
if (requestTimeoutInMs == 0) {
requestTimeoutInMs = config.getRequestTimeout().toMillis();
}
if (requestTimeoutInMs > -1) {
requestTimeoutMillisTime = unpreciseMillisTime() + requestTimeoutInMs;
requestTimeout = newTimeout(new RequestTimeoutTimerTask(nettyResponseFuture, requestSender, this, requestTimeoutInMs), requestTimeoutInMs);
} else {
requestTimeoutMillisTime = -1L;
requestTimeout = null;
}
}
public void setResolvedRemoteAddress(InetSocketAddress address) {
remoteAddress = address;
}
InetSocketAddress remoteAddress() {
return remoteAddress;
}
public void startReadTimeout() {
if (readTimeoutValue != -1) {
startReadTimeout(null);
}
}
void startReadTimeout(ReadTimeoutTimerTask task) {<FILL_FUNCTION_BODY>}
public void cancel() {
if (cancelled.compareAndSet(false, true)) {
if (requestTimeout != null) {
requestTimeout.cancel();
((TimeoutTimerTask) requestTimeout.task()).clean();
}
if (readTimeout != null) {
readTimeout.cancel();
((TimeoutTimerTask) readTimeout.task()).clean();
}
}
}
private Timeout newTimeout(TimerTask task, long delay) {
return requestSender.isClosed() ? null : nettyTimer.newTimeout(task, delay, TimeUnit.MILLISECONDS);
}
}
|
if (requestTimeout == null || !requestTimeout.isExpired() && readTimeoutValue < requestTimeoutMillisTime - unpreciseMillisTime()) {
// only schedule a new readTimeout if the requestTimeout doesn't happen first
if (task == null) {
// first call triggered from outside (else is read timeout is re-scheduling itself)
task = new ReadTimeoutTimerTask(nettyResponseFuture, requestSender, this, readTimeoutValue);
}
readTimeout = newTimeout(task, readTimeoutValue);
} else if (task != null) {
// read timeout couldn't re-scheduling itself, clean up
task.clean();
}
| 697
| 166
| 863
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/proxy/ProxyServer.java
|
Builder
|
build
|
class Builder {
private final String host;
private final int port;
private int securedPort;
private @Nullable Realm realm;
private @Nullable List<String> nonProxyHosts;
private @Nullable ProxyType proxyType;
private @Nullable Function<Request, HttpHeaders> customHeaders;
public Builder(String host, int port) {
this.host = host;
this.port = port;
securedPort = port;
}
public Builder setSecuredPort(int securedPort) {
this.securedPort = securedPort;
return this;
}
public Builder setRealm(@Nullable Realm realm) {
this.realm = realm;
return this;
}
public Builder setRealm(Realm.Builder realm) {
this.realm = realm.build();
return this;
}
public Builder setNonProxyHost(String nonProxyHost) {
if (nonProxyHosts == null) {
nonProxyHosts = new ArrayList<>(1);
}
nonProxyHosts.add(nonProxyHost);
return this;
}
public Builder setNonProxyHosts(List<String> nonProxyHosts) {
this.nonProxyHosts = nonProxyHosts;
return this;
}
public Builder setProxyType(ProxyType proxyType) {
this.proxyType = proxyType;
return this;
}
public Builder setCustomHeaders(Function<Request, HttpHeaders> customHeaders) {
this.customHeaders = customHeaders;
return this;
}
public ProxyServer build() {<FILL_FUNCTION_BODY>}
}
|
List<String> nonProxyHosts = this.nonProxyHosts != null ? Collections.unmodifiableList(this.nonProxyHosts) : Collections.emptyList();
ProxyType proxyType = this.proxyType != null ? this.proxyType : ProxyType.HTTP;
return new ProxyServer(host, port, securedPort, realm, nonProxyHosts, proxyType, customHeaders);
| 419
| 101
| 520
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/generator/ByteArrayBodyGenerator.java
|
ByteBody
|
transferTo
|
class ByteBody implements Body {
private boolean eof;
private int lastPosition;
@Override
public long getContentLength() {
return bytes.length;
}
@Override
public BodyState transferTo(ByteBuf target) {<FILL_FUNCTION_BODY>}
@Override
public void close() {
lastPosition = 0;
eof = false;
}
}
|
if (eof) {
return BodyState.STOP;
}
final int remaining = bytes.length - lastPosition;
final int initialTargetWritableBytes = target.writableBytes();
if (remaining <= initialTargetWritableBytes) {
target.writeBytes(bytes, lastPosition, remaining);
eof = true;
} else {
target.writeBytes(bytes, lastPosition, initialTargetWritableBytes);
lastPosition += initialTargetWritableBytes;
}
return BodyState.CONTINUE;
| 107
| 139
| 246
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/generator/FileBodyGenerator.java
|
FileBodyGenerator
|
createBody
|
class FileBodyGenerator implements BodyGenerator {
private final File file;
private final long regionSeek;
private final long regionLength;
public FileBodyGenerator(File file) {
this(file, 0L, file.length());
}
public FileBodyGenerator(File file, long regionSeek, long regionLength) {
this.file = requireNonNull(file, "file");
this.regionLength = regionLength;
this.regionSeek = regionSeek;
}
public File getFile() {
return file;
}
public long getRegionLength() {
return regionLength;
}
public long getRegionSeek() {
return regionSeek;
}
@Override
public RandomAccessBody createBody() {<FILL_FUNCTION_BODY>}
}
|
throw new UnsupportedOperationException("FileBodyGenerator.createBody isn't used, Netty direclt sends the file");
| 210
| 32
| 242
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/generator/InputStreamBodyGenerator.java
|
InputStreamBody
|
transferTo
|
class InputStreamBody implements Body {
private final InputStream inputStream;
private final long contentLength;
private byte[] chunk;
private InputStreamBody(InputStream inputStream, long contentLength) {
this.inputStream = inputStream;
this.contentLength = contentLength;
}
@Override
public long getContentLength() {
return contentLength;
}
@Override
public BodyState transferTo(ByteBuf target) {<FILL_FUNCTION_BODY>}
@Override
public void close() throws IOException {
inputStream.close();
}
}
|
// To be safe.
chunk = new byte[target.writableBytes() - 10];
int read = -1;
boolean write = false;
try {
read = inputStream.read(chunk);
} catch (IOException ex) {
LOGGER.warn("Unable to read", ex);
}
if (read > 0) {
target.writeBytes(chunk, 0, read);
write = true;
}
return write ? BodyState.CONTINUE : BodyState.STOP;
| 153
| 139
| 292
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/generator/PushBody.java
|
PushBody
|
readNextChunk
|
class PushBody implements Body {
private final Queue<BodyChunk> queue;
private BodyState state = BodyState.CONTINUE;
public PushBody(Queue<BodyChunk> queue) {
this.queue = queue;
}
@Override
public long getContentLength() {
return -1;
}
@Override
public BodyState transferTo(final ByteBuf target) {
switch (state) {
case CONTINUE:
return readNextChunk(target);
case STOP:
return BodyState.STOP;
default:
throw new IllegalStateException("Illegal process state.");
}
}
private BodyState readNextChunk(ByteBuf target) {<FILL_FUNCTION_BODY>}
private void readChunk(ByteBuf target, BodyChunk part) {
target.writeBytes(part.buffer);
if (!part.buffer.isReadable()) {
if (part.last) {
state = BodyState.STOP;
}
queue.remove();
}
}
@Override
public void close() {
}
}
|
BodyState res = BodyState.SUSPEND;
while (target.isWritable() && state != BodyState.STOP) {
BodyChunk nextChunk = queue.peek();
if (nextChunk == null) {
// Nothing in the queue. suspend stream if nothing was read. (reads == 0)
return res;
} else if (!nextChunk.buffer.isReadable() && !nextChunk.last) {
// skip empty buffers
queue.remove();
} else {
res = BodyState.CONTINUE;
readChunk(target, nextChunk);
}
}
return res;
| 290
| 167
| 457
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/generator/QueueBasedFeedableBodyGenerator.java
|
QueueBasedFeedableBodyGenerator
|
feed
|
class QueueBasedFeedableBodyGenerator<T extends Queue<BodyChunk>> implements FeedableBodyGenerator {
protected final T queue;
private FeedListener listener;
protected QueueBasedFeedableBodyGenerator(T queue) {
this.queue = queue;
}
@Override
public Body createBody() {
return new PushBody(queue);
}
protected abstract boolean offer(BodyChunk chunk) throws Exception;
@Override
public boolean feed(final ByteBuf buffer, final boolean isLast) throws Exception {<FILL_FUNCTION_BODY>}
@Override
public void setListener(FeedListener listener) {
this.listener = listener;
}
}
|
boolean offered = offer(new BodyChunk(buffer, isLast));
if (offered && listener != null) {
listener.onContentAdded();
}
return offered;
| 176
| 49
| 225
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/multipart/FileLikePart.java
|
FileLikePart
|
computeContentType
|
class FileLikePart extends PartBase {
private static final MimetypesFileTypeMap MIME_TYPES_FILE_TYPE_MAP;
static {
try (InputStream is = FileLikePart.class.getResourceAsStream("ahc-mime.types")) {
MIME_TYPES_FILE_TYPE_MAP = new MimetypesFileTypeMap(is);
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
/**
* Default content encoding of file attachments.
*/
private final String fileName;
/**
* FilePart Constructor.
*
* @param name the name for this part
* @param contentType the content type for this part, if {@code null} try to figure out from the fileName mime type
* @param charset the charset encoding for this part
* @param fileName the fileName
* @param contentId the content id
* @param transferEncoding the transfer encoding
*/
protected FileLikePart(String name, String contentType, Charset charset, String fileName, String contentId, String transferEncoding) {
super(name,
computeContentType(contentType, fileName),
charset,
contentId,
transferEncoding);
this.fileName = fileName;
}
private static String computeContentType(String contentType, String fileName) {<FILL_FUNCTION_BODY>}
public String getFileName() {
return fileName;
}
@Override
public String toString() {
return super.toString() + " filename=" + fileName;
}
}
|
return contentType != null ? contentType : MIME_TYPES_FILE_TYPE_MAP.getContentType(withDefault(fileName, ""));
| 409
| 40
| 449
|
<methods>public void addCustomHeader(java.lang.String, java.lang.String) ,public java.nio.charset.Charset getCharset() ,public java.lang.String getContentId() ,public java.lang.String getContentType() ,public List<org.asynchttpclient.Param> getCustomHeaders() ,public java.lang.String getDispositionType() ,public java.lang.String getName() ,public java.lang.String getTransferEncoding() ,public void setCustomHeaders(List<org.asynchttpclient.Param>) ,public void setDispositionType(java.lang.String) ,public java.lang.String toString() <variables>private final non-sealed java.nio.charset.Charset charset,private final non-sealed java.lang.String contentId,private final non-sealed java.lang.String contentType,private List<org.asynchttpclient.Param> customHeaders,private java.lang.String dispositionType,private final non-sealed java.lang.String name,private final non-sealed java.lang.String transferEncoding
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/multipart/MultipartBody.java
|
MultipartBody
|
transferTo
|
class MultipartBody implements RandomAccessBody {
private static final Logger LOGGER = LoggerFactory.getLogger(MultipartBody.class);
private final List<MultipartPart<? extends Part>> parts;
private final String contentType;
private final byte[] boundary;
private final long contentLength;
private int currentPartIndex;
private boolean done;
private final AtomicBoolean closed = new AtomicBoolean();
public MultipartBody(List<MultipartPart<? extends Part>> parts, String contentType, byte[] boundary) {
this.boundary = boundary;
this.contentType = contentType;
this.parts = requireNonNull(parts, "parts");
contentLength = computeContentLength();
}
private long computeContentLength() {
try {
long total = 0;
for (MultipartPart<? extends Part> part : parts) {
long l = part.length();
if (l < 0) {
return -1;
}
total += l;
}
return total;
} catch (Exception e) {
LOGGER.error("An exception occurred while getting the length of the parts", e);
return 0L;
}
}
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
for (MultipartPart<? extends Part> part : parts) {
closeSilently(part);
}
}
}
@Override
public long getContentLength() {
return contentLength;
}
public String getContentType() {
return contentType;
}
public byte[] getBoundary() {
return boundary;
}
// Regular Body API
@Override
public BodyState transferTo(ByteBuf target) throws IOException {<FILL_FUNCTION_BODY>}
// RandomAccessBody API, suited for HTTP but not for HTTPS (zero-copy)
@Override
public long transferTo(WritableByteChannel target) throws IOException {
if (done) {
return -1L;
}
long transferred = 0L;
boolean slowTarget = false;
while (transferred < BodyChunkedInput.DEFAULT_CHUNK_SIZE && !done && !slowTarget) {
MultipartPart<? extends Part> currentPart = parts.get(currentPartIndex);
transferred += currentPart.transferTo(target);
slowTarget = currentPart.isTargetSlow();
if (currentPart.getState() == MultipartState.DONE) {
currentPartIndex++;
if (currentPartIndex == parts.size()) {
done = true;
}
}
}
return transferred;
}
}
|
if (done) {
return BodyState.STOP;
}
while (target.isWritable() && !done) {
MultipartPart<? extends Part> currentPart = parts.get(currentPartIndex);
currentPart.transferTo(target);
if (currentPart.getState() == MultipartState.DONE) {
currentPartIndex++;
if (currentPartIndex == parts.size()) {
done = true;
}
}
}
return BodyState.CONTINUE;
| 682
| 137
| 819
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/multipart/MultipartUtils.java
|
MultipartUtils
|
newMultipartBody
|
class MultipartUtils {
private MultipartUtils() {
// Prevent outside initialization
}
/**
* Creates a new multipart entity containing the given parts.
*
* @param parts the parts to include.
* @param requestHeaders the request headers
* @return a MultipartBody
*/
public static MultipartBody newMultipartBody(List<Part> parts, HttpHeaders requestHeaders) {<FILL_FUNCTION_BODY>}
public static List<MultipartPart<? extends Part>> generateMultipartParts(List<Part> parts, byte[] boundary) {
List<MultipartPart<? extends Part>> multipartParts = new ArrayList<>(parts.size());
for (Part part : parts) {
if (part instanceof FilePart) {
multipartParts.add(new FileMultipartPart((FilePart) part, boundary));
} else if (part instanceof ByteArrayPart) {
multipartParts.add(new ByteArrayMultipartPart((ByteArrayPart) part, boundary));
} else if (part instanceof StringPart) {
multipartParts.add(new StringMultipartPart((StringPart) part, boundary));
} else if (part instanceof InputStreamPart) {
multipartParts.add(new InputStreamMultipartPart((InputStreamPart) part, boundary));
} else {
throw new IllegalArgumentException("Unknown part type: " + part);
}
}
// add an extra fake part for terminating the message
multipartParts.add(new MessageEndMultipartPart(boundary));
return multipartParts;
}
}
|
requireNonNull(parts, "parts");
byte[] boundary;
String contentType;
String contentTypeHeader = requestHeaders.get(CONTENT_TYPE);
if (isNonEmpty(contentTypeHeader)) {
int boundaryLocation = contentTypeHeader.indexOf("boundary=");
if (boundaryLocation != -1) {
// boundary defined in existing Content-Type
contentType = contentTypeHeader;
boundary = contentTypeHeader.substring(boundaryLocation + "boundary=".length()).trim().getBytes(US_ASCII);
} else {
// generate boundary and append it to existing Content-Type
boundary = computeMultipartBoundary();
contentType = patchContentTypeWithBoundaryAttribute(contentTypeHeader, boundary);
}
} else {
boundary = computeMultipartBoundary();
contentType = patchContentTypeWithBoundaryAttribute(HttpHeaderValues.MULTIPART_FORM_DATA.toString(), boundary);
}
List<MultipartPart<? extends Part>> multipartParts = generateMultipartParts(parts, boundary);
return new MultipartBody(multipartParts, contentType, boundary);
| 398
| 283
| 681
|
<no_super_class>
|
AsyncHttpClient_async-http-client
|
async-http-client/client/src/main/java/org/asynchttpclient/request/body/multipart/PartBase.java
|
PartBase
|
addCustomHeader
|
class PartBase implements Part {
/**
* The name of the form field, part of the Content-Disposition header
*/
private final String name;
/**
* The main part of the Content-Type header
*/
private final String contentType;
/**
* The charset (part of Content-Type header)
*/
private final Charset charset;
/**
* The Content-Transfer-Encoding header value.
*/
private final String transferEncoding;
/**
* The Content-Id
*/
private final String contentId;
/**
* The disposition type (part of Content-Disposition)
*/
private String dispositionType;
/**
* Additional part headers
*/
private List<Param> customHeaders;
/**
* Constructor.
*
* @param name The name of the part, or {@code null}
* @param contentType The content type, or {@code null}
* @param charset The character encoding, or {@code null}
* @param contentId The content id, or {@code null}
* @param transferEncoding The transfer encoding, or {@code null}
*/
protected PartBase(String name, String contentType, Charset charset, String contentId, String transferEncoding) {
this.name = name;
this.contentType = contentType;
this.charset = charset;
this.contentId = contentId;
this.transferEncoding = transferEncoding;
}
@Override
public String getName() {
return name;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public Charset getCharset() {
return charset;
}
@Override
public String getTransferEncoding() {
return transferEncoding;
}
@Override
public String getContentId() {
return contentId;
}
@Override
public String getDispositionType() {
return dispositionType;
}
public void setDispositionType(String dispositionType) {
this.dispositionType = dispositionType;
}
@Override
public List<Param> getCustomHeaders() {
return customHeaders;
}
public void setCustomHeaders(List<Param> customHeaders) {
this.customHeaders = customHeaders;
}
public void addCustomHeader(String name, String value) {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return getClass().getSimpleName() +
" name=" + getName() +
" contentType=" + getContentType() +
" charset=" + getCharset() +
" transferEncoding=" + getTransferEncoding() +
" contentId=" + getContentId() +
" dispositionType=" + getDispositionType();
}
}
|
if (customHeaders == null) {
customHeaders = new ArrayList<>(2);
}
customHeaders.add(new Param(name, value));
| 728
| 42
| 770
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.