id
stringlengths 5
19
| content
stringlengths 94
57.5k
| max_stars_repo_path
stringlengths 36
95
|
---|---|---|
Gson-11 | public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NULL:
in.nextNull();
return null;
case NUMBER:
return new LazilyParsedNumber(in.nextString());
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
}
public Number read(JsonReader in) throws IOException {
JsonToken jsonToken = in.peek();
switch (jsonToken) {
case NULL:
in.nextNull();
return null;
case NUMBER:
case STRING:
return new LazilyParsedNumber(in.nextString());
default:
throw new JsonSyntaxException("Expecting number, got: " + jsonToken);
}
} | gson/src/main/java/com/google/gson/internal/bind/TypeAdapters.java |
Gson-12 | @Override public void skipValue() throws IOException {
if (peek() == JsonToken.NAME) {
nextName();
pathNames[stackSize - 2] = "null";
} else {
popStack();
pathNames[stackSize - 1] = "null";
}
pathIndices[stackSize - 1]++;
}
@Override public void skipValue() throws IOException {
if (peek() == JsonToken.NAME) {
nextName();
pathNames[stackSize - 2] = "null";
} else {
popStack();
if (stackSize > 0) {
pathNames[stackSize - 1] = "null";
}
}
if (stackSize > 0) {
pathIndices[stackSize - 1]++;
}
} | gson/src/main/java/com/google/gson/internal/bind/JsonTreeReader.java |
Gson-13 | private int peekNumber() throws IOException {
// Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
char[] buffer = this.buffer;
int p = pos;
int l = limit;
long value = 0; // Negative to accommodate Long.MIN_VALUE more easily.
boolean negative = false;
boolean fitsInLong = true;
int last = NUMBER_CHAR_NONE;
int i = 0;
charactersOfNumber:
for (; true; i++) {
if (p + i == l) {
if (i == buffer.length) {
// Though this looks like a well-formed number, it's too long to continue reading. Give up
// and let the application handle this as an unquoted literal.
return PEEKED_NONE;
}
if (!fillBuffer(i + 1)) {
break;
}
p = pos;
l = limit;
}
char c = buffer[p + i];
switch (c) {
case '-':
if (last == NUMBER_CHAR_NONE) {
negative = true;
last = NUMBER_CHAR_SIGN;
continue;
} else if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN;
continue;
}
return PEEKED_NONE;
case '+':
if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN;
continue;
}
return PEEKED_NONE;
case 'e':
case 'E':
if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
last = NUMBER_CHAR_EXP_E;
continue;
}
return PEEKED_NONE;
case '.':
if (last == NUMBER_CHAR_DIGIT) {
last = NUMBER_CHAR_DECIMAL;
continue;
}
return PEEKED_NONE;
default:
if (c < '0' || c > '9') {
if (!isLiteral(c)) {
break charactersOfNumber;
}
return PEEKED_NONE;
}
if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {
value = -(c - '0');
last = NUMBER_CHAR_DIGIT;
} else if (last == NUMBER_CHAR_DIGIT) {
if (value == 0) {
return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal).
}
long newValue = value * 10 - (c - '0');
fitsInLong &= value > MIN_INCOMPLETE_INTEGER
|| (value == MIN_INCOMPLETE_INTEGER && newValue < value);
value = newValue;
} else if (last == NUMBER_CHAR_DECIMAL) {
last = NUMBER_CHAR_FRACTION_DIGIT;
} else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {
last = NUMBER_CHAR_EXP_DIGIT;
}
}
}
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative)) {
peekedLong = negative ? value : -value;
pos += i;
return peeked = PEEKED_LONG;
} else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT
|| last == NUMBER_CHAR_EXP_DIGIT) {
peekedNumberLength = i;
return peeked = PEEKED_NUMBER;
} else {
return PEEKED_NONE;
}
}
private int peekNumber() throws IOException {
// Like nextNonWhitespace, this uses locals 'p' and 'l' to save inner-loop field access.
char[] buffer = this.buffer;
int p = pos;
int l = limit;
long value = 0; // Negative to accommodate Long.MIN_VALUE more easily.
boolean negative = false;
boolean fitsInLong = true;
int last = NUMBER_CHAR_NONE;
int i = 0;
charactersOfNumber:
for (; true; i++) {
if (p + i == l) {
if (i == buffer.length) {
// Though this looks like a well-formed number, it's too long to continue reading. Give up
// and let the application handle this as an unquoted literal.
return PEEKED_NONE;
}
if (!fillBuffer(i + 1)) {
break;
}
p = pos;
l = limit;
}
char c = buffer[p + i];
switch (c) {
case '-':
if (last == NUMBER_CHAR_NONE) {
negative = true;
last = NUMBER_CHAR_SIGN;
continue;
} else if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN;
continue;
}
return PEEKED_NONE;
case '+':
if (last == NUMBER_CHAR_EXP_E) {
last = NUMBER_CHAR_EXP_SIGN;
continue;
}
return PEEKED_NONE;
case 'e':
case 'E':
if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT) {
last = NUMBER_CHAR_EXP_E;
continue;
}
return PEEKED_NONE;
case '.':
if (last == NUMBER_CHAR_DIGIT) {
last = NUMBER_CHAR_DECIMAL;
continue;
}
return PEEKED_NONE;
default:
if (c < '0' || c > '9') {
if (!isLiteral(c)) {
break charactersOfNumber;
}
return PEEKED_NONE;
}
if (last == NUMBER_CHAR_SIGN || last == NUMBER_CHAR_NONE) {
value = -(c - '0');
last = NUMBER_CHAR_DIGIT;
} else if (last == NUMBER_CHAR_DIGIT) {
if (value == 0) {
return PEEKED_NONE; // Leading '0' prefix is not allowed (since it could be octal).
}
long newValue = value * 10 - (c - '0');
fitsInLong &= value > MIN_INCOMPLETE_INTEGER
|| (value == MIN_INCOMPLETE_INTEGER && newValue < value);
value = newValue;
} else if (last == NUMBER_CHAR_DECIMAL) {
last = NUMBER_CHAR_FRACTION_DIGIT;
} else if (last == NUMBER_CHAR_EXP_E || last == NUMBER_CHAR_EXP_SIGN) {
last = NUMBER_CHAR_EXP_DIGIT;
}
}
}
// We've read a complete number. Decide if it's a PEEKED_LONG or a PEEKED_NUMBER.
if (last == NUMBER_CHAR_DIGIT && fitsInLong && (value != Long.MIN_VALUE || negative) && (value!=0 || false==negative)) {
peekedLong = negative ? value : -value;
pos += i;
return peeked = PEEKED_LONG;
} else if (last == NUMBER_CHAR_DIGIT || last == NUMBER_CHAR_FRACTION_DIGIT
|| last == NUMBER_CHAR_EXP_DIGIT) {
peekedNumberLength = i;
return peeked = PEEKED_NUMBER;
} else {
return PEEKED_NONE;
}
} | gson/src/main/java/com/google/gson/stream/JsonReader.java |
Gson-15 | public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (Double.isNaN(value) || Double.isInfinite(value)) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Double.toString(value));
return this;
}
public JsonWriter value(double value) throws IOException {
writeDeferredName();
if (!lenient && (Double.isNaN(value) || Double.isInfinite(value))) {
throw new IllegalArgumentException("Numeric values must be finite, but was " + value);
}
beforeValue();
out.append(Double.toString(value));
return this;
} | gson/src/main/java/com/google/gson/stream/JsonWriter.java |
Gson-16 | private static Type resolve(Type context, Class<?> contextRawType, Type toResolve,
Collection<TypeVariable> visitedTypeVariables) {
// this implementation is made a little more complicated in an attempt to avoid object-creation
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
// cannot reduce due to infinite recursion
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
return toResolve;
}
} else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
Class<?> original = (Class<?>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
return componentType == newComponentType
? original
: arrayOf(newComponentType);
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
return componentType == newComponentType
? original
: arrayOf(newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed
? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)
: original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
if (lowerBound != originalLowerBound[0]) {
return supertypeOf(lowerBound);
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
if (upperBound != originalUpperBound[0]) {
return subtypeOf(upperBound);
}
}
return original;
} else {
return toResolve;
}
}
}
private static Type resolve(Type context, Class<?> contextRawType, Type toResolve,
Collection<TypeVariable> visitedTypeVariables) {
// this implementation is made a little more complicated in an attempt to avoid object-creation
while (true) {
if (toResolve instanceof TypeVariable) {
TypeVariable<?> typeVariable = (TypeVariable<?>) toResolve;
if (visitedTypeVariables.contains(typeVariable)) {
// cannot reduce due to infinite recursion
return toResolve;
} else {
visitedTypeVariables.add(typeVariable);
}
toResolve = resolveTypeVariable(context, contextRawType, typeVariable);
if (toResolve == typeVariable) {
return toResolve;
}
} else if (toResolve instanceof Class && ((Class<?>) toResolve).isArray()) {
Class<?> original = (Class<?>) toResolve;
Type componentType = original.getComponentType();
Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
return componentType == newComponentType
? original
: arrayOf(newComponentType);
} else if (toResolve instanceof GenericArrayType) {
GenericArrayType original = (GenericArrayType) toResolve;
Type componentType = original.getGenericComponentType();
Type newComponentType = resolve(context, contextRawType, componentType, visitedTypeVariables);
return componentType == newComponentType
? original
: arrayOf(newComponentType);
} else if (toResolve instanceof ParameterizedType) {
ParameterizedType original = (ParameterizedType) toResolve;
Type ownerType = original.getOwnerType();
Type newOwnerType = resolve(context, contextRawType, ownerType, visitedTypeVariables);
boolean changed = newOwnerType != ownerType;
Type[] args = original.getActualTypeArguments();
for (int t = 0, length = args.length; t < length; t++) {
Type resolvedTypeArgument = resolve(context, contextRawType, args[t], visitedTypeVariables);
if (resolvedTypeArgument != args[t]) {
if (!changed) {
args = args.clone();
changed = true;
}
args[t] = resolvedTypeArgument;
}
}
return changed
? newParameterizedTypeWithOwner(newOwnerType, original.getRawType(), args)
: original;
} else if (toResolve instanceof WildcardType) {
WildcardType original = (WildcardType) toResolve;
Type[] originalLowerBound = original.getLowerBounds();
Type[] originalUpperBound = original.getUpperBounds();
if (originalLowerBound.length == 1) {
Type lowerBound = resolve(context, contextRawType, originalLowerBound[0], visitedTypeVariables);
if (lowerBound != originalLowerBound[0]) {
return supertypeOf(lowerBound);
}
} else if (originalUpperBound.length == 1) {
Type upperBound = resolve(context, contextRawType, originalUpperBound[0], visitedTypeVariables);
if (upperBound != originalUpperBound[0]) {
return subtypeOf(upperBound);
}
}
return original;
} else {
return toResolve;
}
}
} | gson/src/main/java/com/google/gson/internal/$Gson$Types.java |
Gson-17 | public Date read(JsonReader in) throws IOException {
if (in.peek() != JsonToken.STRING) {
throw new JsonParseException("The date should be a string value");
}
Date date = deserializeToDate(in.nextString());
if (dateType == Date.class) {
return date;
} else if (dateType == Timestamp.class) {
return new Timestamp(date.getTime());
} else if (dateType == java.sql.Date.class) {
return new java.sql.Date(date.getTime());
} else {
// This must never happen: dateType is guarded in the primary constructor
throw new AssertionError();
}
}
public Date read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
Date date = deserializeToDate(in.nextString());
if (dateType == Date.class) {
return date;
} else if (dateType == Timestamp.class) {
return new Timestamp(date.getTime());
} else if (dateType == java.sql.Date.class) {
return new java.sql.Date(date.getTime());
} else {
// This must never happen: dateType is guarded in the primary constructor
throw new AssertionError();
}
} | gson/src/main/java/com/google/gson/DefaultDateTypeAdapter.java |
Gson-18 | static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
// wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead
checkArgument(supertype.isAssignableFrom(contextRawType));
return resolve(context, contextRawType,
$Gson$Types.getGenericSupertype(context, contextRawType, supertype));
}
static Type getSupertype(Type context, Class<?> contextRawType, Class<?> supertype) {
if (context instanceof WildcardType) {
// wildcards are useless for resolving supertypes. As the upper bound has the same raw type, use it instead
context = ((WildcardType)context).getUpperBounds()[0];
}
checkArgument(supertype.isAssignableFrom(contextRawType));
return resolve(context, contextRawType,
$Gson$Types.getGenericSupertype(context, contextRawType, supertype));
} | gson/src/main/java/com/google/gson/internal/$Gson$Types.java |
Gson-5 | public static Date parse(String date, ParsePosition pos) throws ParseException {
Exception fail = null;
try {
int offset = pos.getIndex();
// extract year
int year = parseInt(date, offset, offset += 4);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract month
int month = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract day
int day = parseInt(date, offset, offset += 2);
// default time value
int hour = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
// if the value has no time component (and no time zone), we are done
boolean hasT = checkOffset(date, offset, 'T');
if (!hasT && (date.length() <= offset)) {
Calendar calendar = new GregorianCalendar(year, month - 1, day);
pos.setIndex(offset);
return calendar.getTime();
}
if (hasT) {
// extract hours, minutes, seconds and milliseconds
hour = parseInt(date, offset += 1, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
minutes = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
// second and milliseconds can be optional
if (date.length() > offset) {
char c = date.charAt(offset);
if (c != 'Z' && c != '+' && c != '-') {
seconds = parseInt(date, offset, offset += 2);
if (seconds > 59 && seconds < 63) seconds = 59; // truncate up to 3 leap seconds
// milliseconds can be optional in the format
if (checkOffset(date, offset, '.')) {
offset += 1;
int endOffset = indexOfNonDigit(date, offset + 1); // assume at least one digit
int parseEndOffset = Math.min(endOffset, offset + 3); // parse up to 3 digits
int fraction = parseInt(date, offset, parseEndOffset);
// compensate for "missing" digits
switch (parseEndOffset - offset) { // number of digits parsed
case 2:
milliseconds = fraction * 10;
break;
case 1:
milliseconds = fraction * 100;
break;
default:
milliseconds = fraction;
}
offset = endOffset;
}
}
}
}
// extract timezone
if (date.length() <= offset) {
throw new IllegalArgumentException("No time zone indicator");
}
TimeZone timezone = null;
char timezoneIndicator = date.charAt(offset);
if (timezoneIndicator == 'Z') {
timezone = TIMEZONE_UTC;
offset += 1;
} else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
String timezoneOffset = date.substring(offset);
// When timezone has no minutes, we should append it, valid timezones are, for example: +00:00, +0000 and +00
offset += timezoneOffset.length();
// 18-Jun-2015, tatu: Minor simplification, skip offset of "+0000"/"+00:00"
if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) {
timezone = TIMEZONE_UTC;
} else {
// 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
// not sure why, but that's the way it looks. Further, Javadocs for
// `java.util.TimeZone` specifically instruct use of GMT as base for
// custom timezones... odd.
String timezoneId = "GMT" + timezoneOffset;
// String timezoneId = "UTC" + timezoneOffset;
timezone = TimeZone.getTimeZone(timezoneId);
String act = timezone.getID();
if (!act.equals(timezoneId)) {
/* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
* one without. If so, don't sweat.
* Yes, very inefficient. Hopefully not hit often.
* If it becomes a perf problem, add 'loose' comparison instead.
*/
String cleaned = act.replace(":", "");
if (!cleaned.equals(timezoneId)) {
throw new IndexOutOfBoundsException("Mismatching time zone indicator: "+timezoneId+" given, resolves to "
+timezone.getID());
}
}
}
} else {
throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator+"'");
}
Calendar calendar = new GregorianCalendar(timezone);
calendar.setLenient(false);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, seconds);
calendar.set(Calendar.MILLISECOND, milliseconds);
pos.setIndex(offset);
return calendar.getTime();
// If we get a ParseException it'll already have the right message/offset.
// Other exception types can convert here.
} catch (IndexOutOfBoundsException e) {
fail = e;
} catch (NumberFormatException e) {
fail = e;
} catch (IllegalArgumentException e) {
fail = e;
}
String input = (date == null) ? null : ('"' + date + "'");
String msg = fail.getMessage();
if (msg == null || msg.isEmpty()) {
msg = "("+fail.getClass().getName()+")";
}
ParseException ex = new ParseException("Failed to parse date [" + input + "]: " + msg, pos.getIndex());
ex.initCause(fail);
throw ex;
}
public static Date parse(String date, ParsePosition pos) throws ParseException {
Exception fail = null;
try {
int offset = pos.getIndex();
// extract year
int year = parseInt(date, offset, offset += 4);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract month
int month = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, '-')) {
offset += 1;
}
// extract day
int day = parseInt(date, offset, offset += 2);
// default time value
int hour = 0;
int minutes = 0;
int seconds = 0;
int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
// if the value has no time component (and no time zone), we are done
boolean hasT = checkOffset(date, offset, 'T');
if (!hasT && (date.length() <= offset)) {
Calendar calendar = new GregorianCalendar(year, month - 1, day);
pos.setIndex(offset);
return calendar.getTime();
}
if (hasT) {
// extract hours, minutes, seconds and milliseconds
hour = parseInt(date, offset += 1, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
minutes = parseInt(date, offset, offset += 2);
if (checkOffset(date, offset, ':')) {
offset += 1;
}
// second and milliseconds can be optional
if (date.length() > offset) {
char c = date.charAt(offset);
if (c != 'Z' && c != '+' && c != '-') {
seconds = parseInt(date, offset, offset += 2);
if (seconds > 59 && seconds < 63) seconds = 59; // truncate up to 3 leap seconds
// milliseconds can be optional in the format
if (checkOffset(date, offset, '.')) {
offset += 1;
int endOffset = indexOfNonDigit(date, offset + 1); // assume at least one digit
int parseEndOffset = Math.min(endOffset, offset + 3); // parse up to 3 digits
int fraction = parseInt(date, offset, parseEndOffset);
// compensate for "missing" digits
switch (parseEndOffset - offset) { // number of digits parsed
case 2:
milliseconds = fraction * 10;
break;
case 1:
milliseconds = fraction * 100;
break;
default:
milliseconds = fraction;
}
offset = endOffset;
}
}
}
}
// extract timezone
if (date.length() <= offset) {
throw new IllegalArgumentException("No time zone indicator");
}
TimeZone timezone = null;
char timezoneIndicator = date.charAt(offset);
if (timezoneIndicator == 'Z') {
timezone = TIMEZONE_UTC;
offset += 1;
} else if (timezoneIndicator == '+' || timezoneIndicator == '-') {
String timezoneOffset = date.substring(offset);
// When timezone has no minutes, we should append it, valid timezones are, for example: +00:00, +0000 and +00
timezoneOffset = timezoneOffset.length() >= 5 ? timezoneOffset : timezoneOffset + "00";
offset += timezoneOffset.length();
// 18-Jun-2015, tatu: Minor simplification, skip offset of "+0000"/"+00:00"
if ("+0000".equals(timezoneOffset) || "+00:00".equals(timezoneOffset)) {
timezone = TIMEZONE_UTC;
} else {
// 18-Jun-2015, tatu: Looks like offsets only work from GMT, not UTC...
// not sure why, but that's the way it looks. Further, Javadocs for
// `java.util.TimeZone` specifically instruct use of GMT as base for
// custom timezones... odd.
String timezoneId = "GMT" + timezoneOffset;
// String timezoneId = "UTC" + timezoneOffset;
timezone = TimeZone.getTimeZone(timezoneId);
String act = timezone.getID();
if (!act.equals(timezoneId)) {
/* 22-Jan-2015, tatu: Looks like canonical version has colons, but we may be given
* one without. If so, don't sweat.
* Yes, very inefficient. Hopefully not hit often.
* If it becomes a perf problem, add 'loose' comparison instead.
*/
String cleaned = act.replace(":", "");
if (!cleaned.equals(timezoneId)) {
throw new IndexOutOfBoundsException("Mismatching time zone indicator: "+timezoneId+" given, resolves to "
+timezone.getID());
}
}
}
} else {
throw new IndexOutOfBoundsException("Invalid time zone indicator '" + timezoneIndicator+"'");
}
Calendar calendar = new GregorianCalendar(timezone);
calendar.setLenient(false);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month - 1);
calendar.set(Calendar.DAY_OF_MONTH, day);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, seconds);
calendar.set(Calendar.MILLISECOND, milliseconds);
pos.setIndex(offset);
return calendar.getTime();
// If we get a ParseException it'll already have the right message/offset.
// Other exception types can convert here.
} catch (IndexOutOfBoundsException e) {
fail = e;
} catch (NumberFormatException e) {
fail = e;
} catch (IllegalArgumentException e) {
fail = e;
}
String input = (date == null) ? null : ('"' + date + "'");
String msg = fail.getMessage();
if (msg == null || msg.isEmpty()) {
msg = "("+fail.getClass().getName()+")";
}
ParseException ex = new ParseException("Failed to parse date [" + input + "]: " + msg, pos.getIndex());
ex.initCause(fail);
throw ex;
} | gson/src/main/java/com/google/gson/internal/bind/util/ISO8601Utils.java |
Gson-6 | static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
TypeToken<?> fieldType, JsonAdapter annotation) {
Class<?> value = annotation.value();
TypeAdapter<?> typeAdapter;
if (TypeAdapter.class.isAssignableFrom(value)) {
Class<TypeAdapter<?>> typeAdapterClass = (Class<TypeAdapter<?>>) value;
typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();
} else if (TypeAdapterFactory.class.isAssignableFrom(value)) {
Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value;
typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))
.construct()
.create(gson, fieldType);
} else {
throw new IllegalArgumentException(
"@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.");
}
typeAdapter = typeAdapter.nullSafe();
return typeAdapter;
}
static TypeAdapter<?> getTypeAdapter(ConstructorConstructor constructorConstructor, Gson gson,
TypeToken<?> fieldType, JsonAdapter annotation) {
Class<?> value = annotation.value();
TypeAdapter<?> typeAdapter;
if (TypeAdapter.class.isAssignableFrom(value)) {
Class<TypeAdapter<?>> typeAdapterClass = (Class<TypeAdapter<?>>) value;
typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterClass)).construct();
} else if (TypeAdapterFactory.class.isAssignableFrom(value)) {
Class<TypeAdapterFactory> typeAdapterFactory = (Class<TypeAdapterFactory>) value;
typeAdapter = constructorConstructor.get(TypeToken.get(typeAdapterFactory))
.construct()
.create(gson, fieldType);
} else {
throw new IllegalArgumentException(
"@JsonAdapter value must be TypeAdapter or TypeAdapterFactory reference.");
}
if (typeAdapter != null) {
typeAdapter = typeAdapter.nullSafe();
}
return typeAdapter;
} | gson/src/main/java/com/google/gson/internal/bind/JsonAdapterAnnotationTypeAdapterFactory.java |
JacksonCore-11 | private void _verifySharing()
{
if (_hashShared) {
_hashArea = Arrays.copyOf(_hashArea, _hashArea.length);
_names = Arrays.copyOf(_names, _names.length);
_hashShared = false;
// 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure
// we rehash as needed, as need-rehash flag is not copied from parent
}
if (_needRehash) {
rehash();
}
}
private void _verifySharing()
{
if (_hashShared) {
_hashArea = Arrays.copyOf(_hashArea, _hashArea.length);
_names = Arrays.copyOf(_names, _names.length);
_hashShared = false;
// 09-Sep-2015, tatu: As per [jackson-core#216], also need to ensure
// we rehash as needed, as need-rehash flag is not copied from parent
_verifyNeedForRehash();
}
if (_needRehash) {
rehash();
}
} | src/main/java/com/fasterxml/jackson/core/sym/ByteQuadsCanonicalizer.java |
JacksonCore-15 | public JsonToken nextToken() throws IOException
{
//Check for _allowMultipleMatches - false and atleast there is one token - which is _currToken
// check for no buffered context _exposedContext - null
//If all the conditions matches then check for scalar / non-scalar property
//if not scalar and ended successfully, then return null
//else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
// then return null
// Anything buffered?
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
// all done with buffered stuff?
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
// Is this guaranteed to work without further checks?
// if (t != JsonToken.START_ARRAY) {
_currToken = t;
return t;
}
// Almost! Most likely still have the current token;
// with the sole exception of
/*
t = delegate.getCurrentToken();
if (t != JsonToken.FIELD_NAME) {
_currToken = t;
return t;
}
*/
break;
}
// If not, traverse down the context chain
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) { // should never occur
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
// If not, need to read more. If we got any:
JsonToken t = delegate.nextToken();
if (t == null) {
// no strict need to close, since we have no state here
return (_currToken = t);
}
// otherwise... to include or not?
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
// note: inclusion of surrounding Object handled separately via
// FIELD_NAME
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
// note: this will also set 'needToHandleName'
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
// Minor twist here: if parent NOT included, may need to induce output of
// surrounding START_OBJECT/END_OBJECT
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default: // scalar value
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
// Otherwise not included (leaves must be explicitly included)
break;
}
// We get here if token was not yet found; offlined handling
return _nextToken2();
}
public JsonToken nextToken() throws IOException
{
//Check for _allowMultipleMatches - false and atleast there is one token - which is _currToken
// check for no buffered context _exposedContext - null
//If all the conditions matches then check for scalar / non-scalar property
if(!_allowMultipleMatches && _currToken != null && _exposedContext == null){
//if not scalar and ended successfully, then return null
if((_currToken.isStructEnd() && _headContext.isStartHandled()) ){
return (_currToken = null);
}
//else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
// then return null
else if(_currToken.isScalarValue() && !_headContext.isStartHandled() && !_includePath
&& _itemFilter == TokenFilter.INCLUDE_ALL) {
return (_currToken = null);
}
}
// Anything buffered?
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
// all done with buffered stuff?
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
// Is this guaranteed to work without further checks?
// if (t != JsonToken.START_ARRAY) {
_currToken = t;
return t;
}
// Almost! Most likely still have the current token;
// with the sole exception of
/*
t = delegate.getCurrentToken();
if (t != JsonToken.FIELD_NAME) {
_currToken = t;
return t;
}
*/
break;
}
// If not, traverse down the context chain
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) { // should never occur
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
// If not, need to read more. If we got any:
JsonToken t = delegate.nextToken();
if (t == null) {
// no strict need to close, since we have no state here
return (_currToken = t);
}
// otherwise... to include or not?
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
// note: inclusion of surrounding Object handled separately via
// FIELD_NAME
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
// note: this will also set 'needToHandleName'
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
// Minor twist here: if parent NOT included, may need to induce output of
// surrounding START_OBJECT/END_OBJECT
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default: // scalar value
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
// Otherwise not included (leaves must be explicitly included)
break;
}
// We get here if token was not yet found; offlined handling
return _nextToken2();
} | src/main/java/com/fasterxml/jackson/core/filter/FilteringParserDelegate.java |
JacksonCore-20 | public void writeEmbeddedObject(Object object) throws IOException {
// 01-Sep-2016, tatu: As per [core#318], handle small number of cases
throw new JsonGenerationException("No native support for writing embedded objects",
this);
}
public void writeEmbeddedObject(Object object) throws IOException {
// 01-Sep-2016, tatu: As per [core#318], handle small number of cases
if (object == null) {
writeNull();
return;
}
if (object instanceof byte[]) {
writeBinary((byte[]) object);
return;
}
throw new JsonGenerationException("No native support for writing embedded objects of type "
+object.getClass().getName(),
this);
} | src/main/java/com/fasterxml/jackson/core/JsonGenerator.java |
JacksonCore-21 | public JsonToken nextToken() throws IOException
{
// 23-May-2017, tatu: To be honest, code here is rather hairy and I don't like all
// conditionals; and it seems odd to return `null` but NOT considering input
// as closed... would love a rewrite to simplify/clear up logic here.
// Check for _allowMultipleMatches - false and at least there is one token - which is _currToken
// check for no buffered context _exposedContext - null
// If all the conditions matches then check for scalar / non-scalar property
if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
//if not scalar and ended successfully, and !includePath, then return null
if (_currToken.isStructEnd()) {
if (_headContext.isStartHandled()) {
return (_currToken = null);
}
} else if (_currToken.isScalarValue()) {
//else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
// then return null
if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
return (_currToken = null);
}
}
}
// Anything buffered?
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
// all done with buffered stuff?
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
// Is this guaranteed to work without further checks?
// if (t != JsonToken.START_ARRAY) {
_currToken = t;
return t;
}
// Almost! Most likely still have the current token;
// with the sole exception of
/*
t = delegate.getCurrentToken();
if (t != JsonToken.FIELD_NAME) {
_currToken = t;
return t;
}
*/
break;
}
// If not, traverse down the context chain
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) { // should never occur
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
// If not, need to read more. If we got any:
JsonToken t = delegate.nextToken();
if (t == null) {
// no strict need to close, since we have no state here
_currToken = t;
return t;
}
// otherwise... to include or not?
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
// note: inclusion of surrounding Object handled separately via
// FIELD_NAME
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
// note: this will also set 'needToHandleName'
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
// Minor twist here: if parent NOT included, may need to induce output of
// surrounding START_OBJECT/END_OBJECT
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default: // scalar value
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
// Otherwise not included (leaves must be explicitly included)
break;
}
// We get here if token was not yet found; offlined handling
return _nextToken2();
}
public JsonToken nextToken() throws IOException
{
// 23-May-2017, tatu: To be honest, code here is rather hairy and I don't like all
// conditionals; and it seems odd to return `null` but NOT considering input
// as closed... would love a rewrite to simplify/clear up logic here.
// Check for _allowMultipleMatches - false and at least there is one token - which is _currToken
// check for no buffered context _exposedContext - null
// If all the conditions matches then check for scalar / non-scalar property
if (!_allowMultipleMatches && (_currToken != null) && (_exposedContext == null)) {
//if not scalar and ended successfully, and !includePath, then return null
if (!_includePath) {
if (_currToken.isStructEnd()) {
if (_headContext.isStartHandled()) {
return (_currToken = null);
}
} else if (_currToken.isScalarValue()) {
//else if scalar, and scalar not present in obj/array and !includePath and INCLUDE_ALL matched once
// then return null
if (!_headContext.isStartHandled() && (_itemFilter == TokenFilter.INCLUDE_ALL)) {
return (_currToken = null);
}
}
}
}
// Anything buffered?
TokenFilterContext ctxt = _exposedContext;
if (ctxt != null) {
while (true) {
JsonToken t = ctxt.nextTokenToRead();
if (t != null) {
_currToken = t;
return t;
}
// all done with buffered stuff?
if (ctxt == _headContext) {
_exposedContext = null;
if (ctxt.inArray()) {
t = delegate.getCurrentToken();
// Is this guaranteed to work without further checks?
// if (t != JsonToken.START_ARRAY) {
_currToken = t;
return t;
}
// Almost! Most likely still have the current token;
// with the sole exception of
/*
t = delegate.getCurrentToken();
if (t != JsonToken.FIELD_NAME) {
_currToken = t;
return t;
}
*/
break;
}
// If not, traverse down the context chain
ctxt = _headContext.findChildOf(ctxt);
_exposedContext = ctxt;
if (ctxt == null) { // should never occur
throw _constructError("Unexpected problem: chain of filtered context broken");
}
}
}
// If not, need to read more. If we got any:
JsonToken t = delegate.nextToken();
if (t == null) {
// no strict need to close, since we have no state here
_currToken = t;
return t;
}
// otherwise... to include or not?
TokenFilter f;
switch (t.id()) {
case ID_START_ARRAY:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartArray();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildArrayContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildArrayContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
case ID_START_OBJECT:
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
if (f == null) { // does this occur?
delegate.skipChildren();
break;
}
// Otherwise still iffy, need to check
f = _headContext.checkValue(f);
if (f == null) {
delegate.skipChildren();
break;
}
if (f != TokenFilter.INCLUDE_ALL) {
f = f.filterStartObject();
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
_headContext = _headContext.createChildObjectContext(f, true);
return (_currToken = t);
}
_headContext = _headContext.createChildObjectContext(f, false);
// Also: only need buffering if parent path to be included
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
// note: inclusion of surrounding Object handled separately via
// FIELD_NAME
break;
case ID_END_ARRAY:
case ID_END_OBJECT:
{
boolean returnEnd = _headContext.isStartHandled();
f = _headContext.getFilter();
if ((f != null) && (f != TokenFilter.INCLUDE_ALL)) {
f.filterFinishArray();
}
_headContext = _headContext.getParent();
_itemFilter = _headContext.getFilter();
if (returnEnd) {
return (_currToken = t);
}
}
break;
case ID_FIELD_NAME:
{
final String name = delegate.getCurrentName();
// note: this will also set 'needToHandleName'
f = _headContext.setFieldName(name);
if (f == TokenFilter.INCLUDE_ALL) {
_itemFilter = f;
if (!_includePath) {
// Minor twist here: if parent NOT included, may need to induce output of
// surrounding START_OBJECT/END_OBJECT
if (_includeImmediateParent && !_headContext.isStartHandled()) {
t = _headContext.nextTokenToRead(); // returns START_OBJECT but also marks it handled
_exposedContext = _headContext;
}
}
return (_currToken = t);
}
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
f = f.includeProperty(name);
if (f == null) {
delegate.nextToken();
delegate.skipChildren();
break;
}
_itemFilter = f;
if (f == TokenFilter.INCLUDE_ALL) {
if (_includePath) {
return (_currToken = t);
}
}
if (_includePath) {
t = _nextTokenWithBuffering(_headContext);
if (t != null) {
_currToken = t;
return t;
}
}
break;
}
default: // scalar value
f = _itemFilter;
if (f == TokenFilter.INCLUDE_ALL) {
return (_currToken = t);
}
if (f != null) {
f = _headContext.checkValue(f);
if ((f == TokenFilter.INCLUDE_ALL)
|| ((f != null) && f.includeValue(delegate))) {
return (_currToken = t);
}
}
// Otherwise not included (leaves must be explicitly included)
break;
}
// We get here if token was not yet found; offlined handling
return _nextToken2();
} | src/main/java/com/fasterxml/jackson/core/filter/FilteringParserDelegate.java |
JacksonCore-23 | public DefaultPrettyPrinter createInstance() {
return new DefaultPrettyPrinter(this);
}
public DefaultPrettyPrinter createInstance() {
if (getClass() != DefaultPrettyPrinter.class) { // since 2.10
throw new IllegalStateException("Failed `createInstance()`: "+getClass().getName()
+" does not override method; it has to");
}
return new DefaultPrettyPrinter(this);
} | src/main/java/com/fasterxml/jackson/core/util/DefaultPrettyPrinter.java |
JacksonCore-25 | private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException
{
_textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));
char[] outBuf = _textBuffer.getCurrentSegment();
int outPtr = _textBuffer.getCurrentSegmentSize();
final int maxCode = codes.length;
while (true) {
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) { // acceptable for now (will error out later)
break;
}
}
char c = _inputBuffer[_inputPtr];
int i = (int) c;
if (i <= maxCode) {
if (codes[i] != 0) {
break;
}
} else if (!Character.isJavaIdentifierPart(c)) {
break;
}
++_inputPtr;
hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;
// Ok, let's add char to output:
outBuf[outPtr++] = c;
// Need more room?
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
}
_textBuffer.setCurrentLength(outPtr);
{
TextBuffer tb = _textBuffer;
char[] buf = tb.getTextBuffer();
int start = tb.getTextOffset();
int len = tb.size();
return _symbols.findSymbol(buf, start, len, hash);
}
}
private String _handleOddName2(int startPtr, int hash, int[] codes) throws IOException
{
_textBuffer.resetWithShared(_inputBuffer, startPtr, (_inputPtr - startPtr));
char[] outBuf = _textBuffer.getCurrentSegment();
int outPtr = _textBuffer.getCurrentSegmentSize();
final int maxCode = codes.length;
while (true) {
if (_inputPtr >= _inputEnd) {
if (!_loadMore()) { // acceptable for now (will error out later)
break;
}
}
char c = _inputBuffer[_inputPtr];
int i = (int) c;
if (i < maxCode) {
if (codes[i] != 0) {
break;
}
} else if (!Character.isJavaIdentifierPart(c)) {
break;
}
++_inputPtr;
hash = (hash * CharsToNameCanonicalizer.HASH_MULT) + i;
// Ok, let's add char to output:
outBuf[outPtr++] = c;
// Need more room?
if (outPtr >= outBuf.length) {
outBuf = _textBuffer.finishCurrentSegment();
outPtr = 0;
}
}
_textBuffer.setCurrentLength(outPtr);
{
TextBuffer tb = _textBuffer;
char[] buf = tb.getTextBuffer();
int start = tb.getTextOffset();
int len = tb.size();
return _symbols.findSymbol(buf, start, len, hash);
}
} | src/main/java/com/fasterxml/jackson/core/json/ReaderBasedJsonParser.java |
JacksonCore-26 | public void feedInput(byte[] buf, int start, int end) throws IOException
{
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
if (end < start) {
_reportError("Input end (%d) may not be before start (%d)", end, start);
}
// and shouldn't have been marked as end-of-input
if (_endOfInput) {
_reportError("Already closed, can not feed more input");
}
// Time to update pointers first
_currInputProcessed += _origBufferLen;
// Also need to adjust row start, to work as if it extended into the past wrt new buffer
_currInputRowStart = start - (_inputEnd - _currInputRowStart);
// And then update buffer settings
_inputBuffer = buf;
_inputPtr = start;
_inputEnd = end;
_origBufferLen = end - start;
}
public void feedInput(byte[] buf, int start, int end) throws IOException
{
// Must not have remaining input
if (_inputPtr < _inputEnd) {
_reportError("Still have %d undecoded bytes, should not call 'feedInput'", _inputEnd - _inputPtr);
}
if (end < start) {
_reportError("Input end (%d) may not be before start (%d)", end, start);
}
// and shouldn't have been marked as end-of-input
if (_endOfInput) {
_reportError("Already closed, can not feed more input");
}
// Time to update pointers first
_currInputProcessed += _origBufferLen;
// Also need to adjust row start, to work as if it extended into the past wrt new buffer
_currInputRowStart = start - (_inputEnd - _currInputRowStart);
// And then update buffer settings
_currBufferStart = start;
_inputBuffer = buf;
_inputPtr = start;
_inputEnd = end;
_origBufferLen = end - start;
} | src/main/java/com/fasterxml/jackson/core/json/async/NonBlockingJsonParser.java |
JacksonCore-3 | public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,
ObjectCodec codec, BytesToNameCanonicalizer sym,
byte[] inputBuffer, int start, int end,
boolean bufferRecyclable)
{
super(ctxt, features);
_inputStream = in;
_objectCodec = codec;
_symbols = sym;
_inputBuffer = inputBuffer;
_inputPtr = start;
_inputEnd = end;
// If we have offset, need to omit that from byte offset, so:
_bufferRecyclable = bufferRecyclable;
}
public UTF8StreamJsonParser(IOContext ctxt, int features, InputStream in,
ObjectCodec codec, BytesToNameCanonicalizer sym,
byte[] inputBuffer, int start, int end,
boolean bufferRecyclable)
{
super(ctxt, features);
_inputStream = in;
_objectCodec = codec;
_symbols = sym;
_inputBuffer = inputBuffer;
_inputPtr = start;
_inputEnd = end;
_currInputRowStart = start;
// If we have offset, need to omit that from byte offset, so:
_currInputProcessed = -start;
_bufferRecyclable = bufferRecyclable;
} | src/main/java/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java |
JacksonCore-4 | public char[] expandCurrentSegment()
{
final char[] curr = _currentSegment;
// Let's grow by 50% by default
final int len = curr.length;
// but above intended maximum, slow to increase by 25%
int newLen = (len == MAX_SEGMENT_LEN) ? (MAX_SEGMENT_LEN+1) : Math.min(MAX_SEGMENT_LEN, len + (len >> 1));
return (_currentSegment = Arrays.copyOf(curr, newLen));
}
public char[] expandCurrentSegment()
{
final char[] curr = _currentSegment;
// Let's grow by 50% by default
final int len = curr.length;
int newLen = len + (len >> 1);
// but above intended maximum, slow to increase by 25%
if (newLen > MAX_SEGMENT_LEN) {
newLen = len + (len >> 2);
}
return (_currentSegment = Arrays.copyOf(curr, newLen));
} | src/main/java/com/fasterxml/jackson/core/util/TextBuffer.java |
JacksonCore-5 | private final static int _parseIndex(String str) {
final int len = str.length();
// [Issue#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
for (int i = 0; i < len; ++i) {
char c = str.charAt(i++);
if (c > '9' || c < '0') {
return -1;
}
}
if (len == 10) {
long l = NumberInput.parseLong(str);
if (l > Integer.MAX_VALUE) {
return -1;
}
}
return NumberInput.parseInt(str);
}
private final static int _parseIndex(String str) {
final int len = str.length();
// [Issue#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c > '9' || c < '0') {
return -1;
}
}
if (len == 10) {
long l = NumberInput.parseLong(str);
if (l > Integer.MAX_VALUE) {
return -1;
}
}
return NumberInput.parseInt(str);
} | src/main/java/com/fasterxml/jackson/core/JsonPointer.java |
JacksonCore-6 | private final static int _parseIndex(String str) {
final int len = str.length();
// [core#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
// [core#176]: no leading zeroes allowed
for (int i = 0; i < len; ++i) {
char c = str.charAt(i);
if (c > '9' || c < '0') {
return -1;
}
}
if (len == 10) {
long l = NumberInput.parseLong(str);
if (l > Integer.MAX_VALUE) {
return -1;
}
}
return NumberInput.parseInt(str);
}
private final static int _parseIndex(String str) {
final int len = str.length();
// [core#133]: beware of super long indexes; assume we never
// have arrays over 2 billion entries so ints are fine.
if (len == 0 || len > 10) {
return -1;
}
// [core#176]: no leading zeroes allowed
char c = str.charAt(0);
if (c <= '0') {
return (len == 1 && c == '0') ? 0 : -1;
}
if (c > '9') {
return -1;
}
for (int i = 1; i < len; ++i) {
c = str.charAt(i);
if (c > '9' || c < '0') {
return -1;
}
}
if (len == 10) {
long l = NumberInput.parseLong(str);
if (l > Integer.MAX_VALUE) {
return -1;
}
}
return NumberInput.parseInt(str);
} | src/main/java/com/fasterxml/jackson/core/JsonPointer.java |
JacksonCore-7 | public int writeValue() {
// Most likely, object:
if (_type == TYPE_OBJECT) {
_gotName = false;
++_index;
return STATUS_OK_AFTER_COLON;
}
// Ok, array?
if (_type == TYPE_ARRAY) {
int ix = _index;
++_index;
return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;
}
// Nope, root context
// No commas within root context, but need space
++_index;
return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;
}
public int writeValue() {
// Most likely, object:
if (_type == TYPE_OBJECT) {
if (!_gotName) {
return STATUS_EXPECT_NAME;
}
_gotName = false;
++_index;
return STATUS_OK_AFTER_COLON;
}
// Ok, array?
if (_type == TYPE_ARRAY) {
int ix = _index;
++_index;
return (ix < 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_COMMA;
}
// Nope, root context
// No commas within root context, but need space
++_index;
return (_index == 0) ? STATUS_OK_AS_IS : STATUS_OK_AFTER_SPACE;
} | src/main/java/com/fasterxml/jackson/core/json/JsonWriteContext.java |
JacksonCore-8 | public char[] getTextBuffer()
{
// Are we just using shared input buffer?
if (_inputStart >= 0) return _inputBuffer;
if (_resultArray != null) return _resultArray;
if (_resultString != null) {
return (_resultArray = _resultString.toCharArray());
}
// Nope; but does it fit in just one segment?
if (!_hasSegments) return _currentSegment;
// Nope, need to have/create a non-segmented array and return it
return contentsAsArray();
}
public char[] getTextBuffer()
{
// Are we just using shared input buffer?
if (_inputStart >= 0) return _inputBuffer;
if (_resultArray != null) return _resultArray;
if (_resultString != null) {
return (_resultArray = _resultString.toCharArray());
}
// Nope; but does it fit in just one segment?
if (!_hasSegments && _currentSegment != null) return _currentSegment;
// Nope, need to have/create a non-segmented array and return it
return contentsAsArray();
} | src/main/java/com/fasterxml/jackson/core/util/TextBuffer.java |
JacksonDatabind-1 | public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)
throws Exception
{
Object value = get(bean);
if (value == null) { // nulls need specialized handling
if (_nullSerializer != null) {
_nullSerializer.serialize(null, jgen, prov);
} else { // can NOT suppress entries in tabular output
jgen.writeNull();
}
}
// otherwise find serializer to use
JsonSerializer<Object> ser = _serializer;
if (ser == null) {
Class<?> cls = value.getClass();
PropertySerializerMap map = _dynamicSerializers;
ser = map.serializerFor(cls);
if (ser == null) {
ser = _findAndAddDynamic(map, cls, prov);
}
}
// and then see if we must suppress certain values (default, empty)
if (_suppressableValue != null) {
if (MARKER_FOR_EMPTY == _suppressableValue) {
if (ser.isEmpty(value)) { // can NOT suppress entries in tabular output
serializeAsPlaceholder(bean, jgen, prov);
return;
}
} else if (_suppressableValue.equals(value)) { // can NOT suppress entries in tabular output
serializeAsPlaceholder(bean, jgen, prov);
return;
}
}
// For non-nulls: simple check for direct cycles
if (value == bean) {
_handleSelfReference(bean, ser);
}
if (_typeSerializer == null) {
ser.serialize(value, jgen, prov);
} else {
ser.serializeWithType(value, jgen, prov, _typeSerializer);
}
}
public void serializeAsColumn(Object bean, JsonGenerator jgen, SerializerProvider prov)
throws Exception
{
Object value = get(bean);
if (value == null) { // nulls need specialized handling
if (_nullSerializer != null) {
_nullSerializer.serialize(null, jgen, prov);
} else { // can NOT suppress entries in tabular output
jgen.writeNull();
}
return;
}
// otherwise find serializer to use
JsonSerializer<Object> ser = _serializer;
if (ser == null) {
Class<?> cls = value.getClass();
PropertySerializerMap map = _dynamicSerializers;
ser = map.serializerFor(cls);
if (ser == null) {
ser = _findAndAddDynamic(map, cls, prov);
}
}
// and then see if we must suppress certain values (default, empty)
if (_suppressableValue != null) {
if (MARKER_FOR_EMPTY == _suppressableValue) {
if (ser.isEmpty(value)) { // can NOT suppress entries in tabular output
serializeAsPlaceholder(bean, jgen, prov);
return;
}
} else if (_suppressableValue.equals(value)) { // can NOT suppress entries in tabular output
serializeAsPlaceholder(bean, jgen, prov);
return;
}
}
// For non-nulls: simple check for direct cycles
if (value == bean) {
_handleSelfReference(bean, ser);
}
if (_typeSerializer == null) {
ser.serialize(value, jgen, prov);
} else {
ser.serializeWithType(value, jgen, prov, _typeSerializer);
}
} | src/main/java/com/fasterxml/jackson/databind/ser/BeanPropertyWriter.java |
JacksonDatabind-100 | public byte[] getBinaryValue(Base64Variant b64variant)
throws IOException, JsonParseException
{
// Multiple possibilities...
JsonNode n = currentNode();
if (n != null) {
// [databind#2096]: although `binaryValue()` works for real binary node
// and embedded "POJO" node, coercion from TextNode may require variant, so:
byte[] data = n.binaryValue();
if (data != null) {
return data;
}
if (n.isPojo()) {
Object ob = ((POJONode) n).getPojo();
if (ob instanceof byte[]) {
return (byte[]) ob;
}
}
}
// otherwise return null to mark we have no binary content
return null;
}
public byte[] getBinaryValue(Base64Variant b64variant)
throws IOException, JsonParseException
{
// Multiple possibilities...
JsonNode n = currentNode();
if (n != null) {
// [databind#2096]: although `binaryValue()` works for real binary node
// and embedded "POJO" node, coercion from TextNode may require variant, so:
if (n instanceof TextNode) {
return ((TextNode) n).getBinaryValue(b64variant);
}
return n.binaryValue();
}
// otherwise return null to mark we have no binary content
return null;
} | src/main/java/com/fasterxml/jackson/databind/node/TreeTraversingParser.java |
JacksonDatabind-101 | protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)
throws IOException
{
// 01-Dec-2016, tatu: Note: This IS legal to call, but only when unwrapped
// value itself is NOT passed via `CreatorProperty` (which isn't supported).
// Ok however to pass via setter or field.
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p, ctxt);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
// Last creator property to set?
if (buffer.assignParameter(creatorProp,
_deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
bean = wrapInstantiationProblem(e, ctxt);
}
// [databind#631]: Assign current value, to be accessible by custom serializers
p.setCurrentValue(bean);
// if so, need to copy all remaining tokens into buffer
while (t == JsonToken.FIELD_NAME) {
// NOTE: do NOT skip name as it needs to be copied; `copyCurrentStructure` does that
p.nextToken();
tokens.copyCurrentStructure(p);
t = p.nextToken();
}
// 28-Aug-2018, tatu: Let's add sanity check here, easier to catch off-by-some
// problems if we maintain invariants
tokens.writeEndObject();
if (bean.getClass() != _beanType.getRawClass()) {
// !!! 08-Jul-2011, tatu: Could probably support; but for now
// it's too complicated, so bail out
ctxt.reportInputMismatch(creatorProp,
"Cannot create polymorphic instances with unwrapped values");
return null;
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));
continue;
}
// Things marked as ignorable should not be passed to any setter
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
// 29-Nov-2016, tatu: probably should try to avoid sending content
// both to any setter AND buffer... but, for now, the only thing
// we can do.
// how about any setter? We'll get copies but...
if (_anySetter == null) {
// but... others should be passed to unwrapped property deserializers
tokens.writeFieldName(propName);
tokens.copyCurrentStructure(p);
} else {
// Need to copy to a separate buffer first
TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);
tokens.writeFieldName(propName);
tokens.append(b2);
try {
buffer.bufferAnyProperty(_anySetter, propName,
_anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));
} catch (Exception e) {
wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
}
continue;
}
}
// We hit END_OBJECT, so:
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
wrapInstantiationProblem(e, ctxt);
return null; // never gets here
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p, DeserializationContext ctxt)
throws IOException
{
// 01-Dec-2016, tatu: Note: This IS legal to call, but only when unwrapped
// value itself is NOT passed via `CreatorProperty` (which isn't supported).
// Ok however to pass via setter or field.
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p, ctxt);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
// Last creator property to set?
if (buffer.assignParameter(creatorProp,
_deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
bean = wrapInstantiationProblem(e, ctxt);
}
// [databind#631]: Assign current value, to be accessible by custom serializers
p.setCurrentValue(bean);
// if so, need to copy all remaining tokens into buffer
while (t == JsonToken.FIELD_NAME) {
// NOTE: do NOT skip name as it needs to be copied; `copyCurrentStructure` does that
tokens.copyCurrentStructure(p);
t = p.nextToken();
}
// 28-Aug-2018, tatu: Let's add sanity check here, easier to catch off-by-some
// problems if we maintain invariants
if (t != JsonToken.END_OBJECT) {
ctxt.reportWrongTokenException(this, JsonToken.END_OBJECT,
"Attempted to unwrap '%s' value",
handledType().getName());
}
tokens.writeEndObject();
if (bean.getClass() != _beanType.getRawClass()) {
// !!! 08-Jul-2011, tatu: Could probably support; but for now
// it's too complicated, so bail out
ctxt.reportInputMismatch(creatorProp,
"Cannot create polymorphic instances with unwrapped values");
return null;
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, _deserializeWithErrorWrapping(p, ctxt, prop));
continue;
}
// Things marked as ignorable should not be passed to any setter
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
// 29-Nov-2016, tatu: probably should try to avoid sending content
// both to any setter AND buffer... but, for now, the only thing
// we can do.
// how about any setter? We'll get copies but...
if (_anySetter == null) {
// but... others should be passed to unwrapped property deserializers
tokens.writeFieldName(propName);
tokens.copyCurrentStructure(p);
} else {
// Need to copy to a separate buffer first
TokenBuffer b2 = TokenBuffer.asCopyOfValue(p);
tokens.writeFieldName(propName);
tokens.append(b2);
try {
buffer.bufferAnyProperty(_anySetter, propName,
_anySetter.deserialize(b2.asParserOnFirstToken(), ctxt));
} catch (Exception e) {
wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
}
continue;
}
}
// We hit END_OBJECT, so:
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
wrapInstantiationProblem(e, ctxt);
return null; // never gets here
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
} | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializer.java |
JacksonDatabind-102 | public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
// Note! Should not skip if `property` null since that'd skip check
// for config overrides, in case of root value
if (property == null) {
return this;
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format == null) {
return this;
}
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
// 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
// First: custom pattern will override things
if (format.hasPattern()) {
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);
TimeZone tz = format.hasTimeZone() ? format.getTimeZone()
: serializers.getTimeZone();
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
// Otherwise, need one of these changes:
final boolean hasLocale = format.hasLocale();
final boolean hasTZ = format.hasTimeZone();
final boolean asString = (shape == JsonFormat.Shape.STRING);
if (!hasLocale && !hasTZ && !asString) {
return this;
}
DateFormat df0 = serializers.getConfig().getDateFormat();
// Jackson's own `StdDateFormat` is quite easy to deal with...
if (df0 instanceof StdDateFormat) {
StdDateFormat std = (StdDateFormat) df0;
if (format.hasLocale()) {
std = std.withLocale(format.getLocale());
}
if (format.hasTimeZone()) {
std = std.withTimeZone(format.getTimeZone());
}
return withFormat(Boolean.FALSE, std);
}
// 08-Jun-2017, tatu: Unfortunately there's no generally usable
// mechanism for changing `DateFormat` instances (or even clone()ing)
// So: require it be `SimpleDateFormat`; can't config other types
if (!(df0 instanceof SimpleDateFormat)) {
serializers.reportBadDefinition(handledType(), String.format(
"Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`",
df0.getClass().getName()));
}
SimpleDateFormat df = (SimpleDateFormat) df0;
if (hasLocale) {
// Ugh. No way to change `Locale`, create copy; must re-crete completely:
df = new SimpleDateFormat(df.toPattern(), format.getLocale());
} else {
df = (SimpleDateFormat) df.clone();
}
TimeZone newTz = format.getTimeZone();
boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());
if (changeTZ) {
df.setTimeZone(newTz);
}
return withFormat(Boolean.FALSE, df);
}
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
// Note! Should not skip if `property` null since that'd skip check
// for config overrides, in case of root value
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format == null) {
return this;
}
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
// 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
// First: custom pattern will override things
if (format.hasPattern()) {
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);
TimeZone tz = format.hasTimeZone() ? format.getTimeZone()
: serializers.getTimeZone();
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
// Otherwise, need one of these changes:
final boolean hasLocale = format.hasLocale();
final boolean hasTZ = format.hasTimeZone();
final boolean asString = (shape == JsonFormat.Shape.STRING);
if (!hasLocale && !hasTZ && !asString) {
return this;
}
DateFormat df0 = serializers.getConfig().getDateFormat();
// Jackson's own `StdDateFormat` is quite easy to deal with...
if (df0 instanceof StdDateFormat) {
StdDateFormat std = (StdDateFormat) df0;
if (format.hasLocale()) {
std = std.withLocale(format.getLocale());
}
if (format.hasTimeZone()) {
std = std.withTimeZone(format.getTimeZone());
}
return withFormat(Boolean.FALSE, std);
}
// 08-Jun-2017, tatu: Unfortunately there's no generally usable
// mechanism for changing `DateFormat` instances (or even clone()ing)
// So: require it be `SimpleDateFormat`; can't config other types
if (!(df0 instanceof SimpleDateFormat)) {
serializers.reportBadDefinition(handledType(), String.format(
"Configured `DateFormat` (%s) not a `SimpleDateFormat`; cannot configure `Locale` or `TimeZone`",
df0.getClass().getName()));
}
SimpleDateFormat df = (SimpleDateFormat) df0;
if (hasLocale) {
// Ugh. No way to change `Locale`, create copy; must re-crete completely:
df = new SimpleDateFormat(df.toPattern(), format.getLocale());
} else {
df = (SimpleDateFormat) df.clone();
}
TimeZone newTz = format.getTimeZone();
boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());
if (changeTZ) {
df.setTimeZone(newTz);
}
return withFormat(Boolean.FALSE, df);
} | src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java |
JacksonDatabind-107 | protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [databind#305], need to provide contextual info. But for
* backwards compatibility, let's start by only supporting this
* for base class, not via interface. Later on we can add this
* to the interface, assuming deprecation at base class helps.
*/
JavaType type = _idResolver.typeFromId(ctxt, typeId);
if (type == null) {
// use the default impl if no type id available:
deser = _findDefaultImplDeserializer(ctxt);
if (deser == null) {
// 10-May-2016, tatu: We may get some help...
JavaType actual = _handleUnknownTypeId(ctxt, typeId);
if (actual == null) { // what should this be taken to mean?
// 17-Jan-2019, tatu: As per [databind#2221], better NOT return `null` but...
return null;
}
// ... would this actually work?
deser = ctxt.findContextualValueDeserializer(actual, _property);
}
} else {
/* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
* we actually now need to explicitly narrow from base type (which may have parameterization)
* using raw type.
*
* One complication, though; cannot change 'type class' (simple type to container); otherwise
* we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
* type in process (getting SimpleType of Map.class which will not work as expected)
*/
if ((_baseType != null)
&& _baseType.getClass() == type.getClass()) {
/* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
* but it appears to check that JavaType impl class is the same which is
* important for some reason?
* Disabling the check will break 2 Enum-related tests.
*/
// 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
// generic type with custom type resolvers. If so, should try to retain them.
// Whether this is sufficient to avoid problems remains to be seen, but for
// now it should improve things.
if (!type.hasGenericTypes()) {
type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
}
}
deser = ctxt.findContextualValueDeserializer(type, _property);
}
_deserializers.put(typeId, deser);
}
return deser;
}
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [databind#305], need to provide contextual info. But for
* backwards compatibility, let's start by only supporting this
* for base class, not via interface. Later on we can add this
* to the interface, assuming deprecation at base class helps.
*/
JavaType type = _idResolver.typeFromId(ctxt, typeId);
if (type == null) {
// use the default impl if no type id available:
deser = _findDefaultImplDeserializer(ctxt);
if (deser == null) {
// 10-May-2016, tatu: We may get some help...
JavaType actual = _handleUnknownTypeId(ctxt, typeId);
if (actual == null) { // what should this be taken to mean?
// 17-Jan-2019, tatu: As per [databind#2221], better NOT return `null` but...
return NullifyingDeserializer.instance;
}
// ... would this actually work?
deser = ctxt.findContextualValueDeserializer(actual, _property);
}
} else {
/* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
* we actually now need to explicitly narrow from base type (which may have parameterization)
* using raw type.
*
* One complication, though; cannot change 'type class' (simple type to container); otherwise
* we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
* type in process (getting SimpleType of Map.class which will not work as expected)
*/
if ((_baseType != null)
&& _baseType.getClass() == type.getClass()) {
/* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
* but it appears to check that JavaType impl class is the same which is
* important for some reason?
* Disabling the check will break 2 Enum-related tests.
*/
// 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
// generic type with custom type resolvers. If so, should try to retain them.
// Whether this is sufficient to avoid problems remains to be seen, but for
// now it should improve things.
if (!type.hasGenericTypes()) {
type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
}
}
deser = ctxt.findContextualValueDeserializer(type, _property);
}
_deserializers.put(typeId, deser);
}
return deser;
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/TypeDeserializerBase.java |
JacksonDatabind-11 | protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context)
{
final String name = type.getName();
// 19-Mar-2015: Without context, all we can check are bounds.
if (context == null) {
// And to prevent infinite loops, now need this:
return _unknownType();
} else {
// Ok: here's where context might come in handy!
/* 19-Mar-2015, tatu: As per [databind#609], may need to allow
* unresolved type variables to handle some cases where bounds
* are enough. Let's hope it does not hide real fail cases.
*/
JavaType actualType = context.findType(name);
if (actualType != null) {
return actualType;
}
}
/* 29-Jan-2010, tatu: We used to throw exception here, if type was
* bound: but the problem is that this can occur for generic "base"
* method, overridden by sub-class. If so, we will want to ignore
* current type (for method) since it will be masked.
*/
Type[] bounds = type.getBounds();
// With type variables we must use bound information.
// Theoretically this gets tricky, as there may be multiple
// bounds ("... extends A & B"); and optimally we might
// want to choose the best match. Also, bounds are optional;
// but here we are lucky in that implicit "Object" is
// added as bounds if so.
// Either way let's just use the first bound, for now, and
// worry about better match later on if there is need.
/* 29-Jan-2010, tatu: One more problem are recursive types
* (T extends Comparable<T>). Need to add "placeholder"
* for resolution to catch those.
*/
context._addPlaceholder(name);
return _constructType(bounds[0], context);
}
protected JavaType _fromVariable(TypeVariable<?> type, TypeBindings context)
{
final String name = type.getName();
// 19-Mar-2015: Without context, all we can check are bounds.
if (context == null) {
// And to prevent infinite loops, now need this:
context = new TypeBindings(this, (Class<?>) null);
} else {
// Ok: here's where context might come in handy!
/* 19-Mar-2015, tatu: As per [databind#609], may need to allow
* unresolved type variables to handle some cases where bounds
* are enough. Let's hope it does not hide real fail cases.
*/
JavaType actualType = context.findType(name, false);
if (actualType != null) {
return actualType;
}
}
/* 29-Jan-2010, tatu: We used to throw exception here, if type was
* bound: but the problem is that this can occur for generic "base"
* method, overridden by sub-class. If so, we will want to ignore
* current type (for method) since it will be masked.
*/
Type[] bounds = type.getBounds();
// With type variables we must use bound information.
// Theoretically this gets tricky, as there may be multiple
// bounds ("... extends A & B"); and optimally we might
// want to choose the best match. Also, bounds are optional;
// but here we are lucky in that implicit "Object" is
// added as bounds if so.
// Either way let's just use the first bound, for now, and
// worry about better match later on if there is need.
/* 29-Jan-2010, tatu: One more problem are recursive types
* (T extends Comparable<T>). Need to add "placeholder"
* for resolution to catch those.
*/
context._addPlaceholder(name);
return _constructType(bounds[0], context);
} | src/main/java/com/fasterxml/jackson/databind/type/TypeFactory.java |
JacksonDatabind-112 | public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
// May need to resolve types for delegate-based creators:
JsonDeserializer<Object> delegate = null;
if (_valueInstantiator != null) {
// [databind#2324]: check both array-delegating and delegating
AnnotatedWithParams delegateCreator = _valueInstantiator.getDelegateCreator();
if (delegateCreator != null) {
JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
delegate = findDeserializer(ctxt, delegateType, property);
}
}
JsonDeserializer<?> valueDeser = _valueDeserializer;
final JavaType valueType = _containerType.getContentType();
if (valueDeser == null) {
// [databind#125]: May have a content converter
valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
if (valueDeser == null) {
// And we may also need to get deserializer for String
valueDeser = ctxt.findContextualValueDeserializer(valueType, property);
}
} else { // if directly assigned, probably not yet contextual, so:
valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);
}
// 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
// comes down to "List vs Collection" I suppose... for now, pass Collection
Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);
if (isDefaultDeserializer(valueDeser)) {
valueDeser = null;
}
return withResolved(delegate, valueDeser, nuller, unwrapSingle);
}
public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
// May need to resolve types for delegate-based creators:
JsonDeserializer<Object> delegate = null;
if (_valueInstantiator != null) {
// [databind#2324]: check both array-delegating and delegating
AnnotatedWithParams delegateCreator = _valueInstantiator.getArrayDelegateCreator();
if (delegateCreator != null) {
JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());
delegate = findDeserializer(ctxt, delegateType, property);
} else if ((delegateCreator = _valueInstantiator.getDelegateCreator()) != null) {
JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
delegate = findDeserializer(ctxt, delegateType, property);
}
}
JsonDeserializer<?> valueDeser = _valueDeserializer;
final JavaType valueType = _containerType.getContentType();
if (valueDeser == null) {
// [databind#125]: May have a content converter
valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
if (valueDeser == null) {
// And we may also need to get deserializer for String
valueDeser = ctxt.findContextualValueDeserializer(valueType, property);
}
} else { // if directly assigned, probably not yet contextual, so:
valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, valueType);
}
// 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
// comes down to "List vs Collection" I suppose... for now, pass Collection
Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
NullValueProvider nuller = findContentNullProvider(ctxt, property, valueDeser);
if (isDefaultDeserializer(valueDeser)) {
valueDeser = null;
}
return withResolved(delegate, valueDeser, nuller, unwrapSingle);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/StringCollectionDeserializer.java |
JacksonDatabind-12 | public boolean isCachable() {
/* As per [databind#735], existence of value or key deserializer (only passed
* if annotated to use non-standard one) should also prevent caching.
*/
return (_valueTypeDeserializer == null)
&& (_ignorableProperties == null);
}
public boolean isCachable() {
/* As per [databind#735], existence of value or key deserializer (only passed
* if annotated to use non-standard one) should also prevent caching.
*/
return (_valueDeserializer == null)
&& (_keyDeserializer == null)
&& (_valueTypeDeserializer == null)
&& (_ignorableProperties == null);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/MapDeserializer.java |
JacksonDatabind-16 | protected final boolean _add(Annotation ann) {
if (_annotations == null) {
_annotations = new HashMap<Class<? extends Annotation>,Annotation>();
}
Annotation previous = _annotations.put(ann.annotationType(), ann);
return (previous != null) && previous.equals(ann);
}
protected final boolean _add(Annotation ann) {
if (_annotations == null) {
_annotations = new HashMap<Class<? extends Annotation>,Annotation>();
}
Annotation previous = _annotations.put(ann.annotationType(), ann);
return (previous == null) || !previous.equals(ann);
} | src/main/java/com/fasterxml/jackson/databind/introspect/AnnotationMap.java |
JacksonDatabind-17 | public boolean useForType(JavaType t)
{
switch (_appliesFor) {
case NON_CONCRETE_AND_ARRAYS:
while (t.isArrayType()) {
t = t.getContentType();
}
// fall through
case OBJECT_AND_NON_CONCRETE:
// return t.isJavaLangObject() ||
return (t.getRawClass() == Object.class)
|| (!t.isConcrete()
// [databind#88] Should not apply to JSON tree models:
|| TreeNode.class.isAssignableFrom(t.getRawClass()));
case NON_FINAL:
while (t.isArrayType()) {
t = t.getContentType();
}
// [Issue#88] Should not apply to JSON tree models:
return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
default:
//case JAVA_LANG_OBJECT:
// return t.isJavaLangObject();
return (t.getRawClass() == Object.class);
}
}
public boolean useForType(JavaType t)
{
switch (_appliesFor) {
case NON_CONCRETE_AND_ARRAYS:
while (t.isArrayType()) {
t = t.getContentType();
}
// fall through
case OBJECT_AND_NON_CONCRETE:
// return t.isJavaLangObject() ||
return (t.getRawClass() == Object.class)
|| (!t.isConcrete()
// [databind#88] Should not apply to JSON tree models:
&& !TreeNode.class.isAssignableFrom(t.getRawClass()));
case NON_FINAL:
while (t.isArrayType()) {
t = t.getContentType();
}
// [Issue#88] Should not apply to JSON tree models:
return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
default:
//case JAVA_LANG_OBJECT:
// return t.isJavaLangObject();
return (t.getRawClass() == Object.class);
}
} | src/main/java/com/fasterxml/jackson/databind/ObjectMapper.java |
JacksonDatabind-19 | private JavaType _mapType(Class<?> rawClass)
{
// 28-May-2015, tatu: Properties are special, as per [databind#810]
JavaType[] typeParams = findTypeParameters(rawClass, Map.class);
// ok to have no types ("raw")
if (typeParams == null) {
return MapType.construct(rawClass, _unknownType(), _unknownType());
}
// but exactly 2 types if any found
if (typeParams.length != 2) {
throw new IllegalArgumentException("Strange Map type "+rawClass.getName()+": can not determine type parameters");
}
return MapType.construct(rawClass, typeParams[0], typeParams[1]);
}
private JavaType _mapType(Class<?> rawClass)
{
// 28-May-2015, tatu: Properties are special, as per [databind#810]
if (rawClass == Properties.class) {
return MapType.construct(rawClass, CORE_TYPE_STRING, CORE_TYPE_STRING);
}
JavaType[] typeParams = findTypeParameters(rawClass, Map.class);
// ok to have no types ("raw")
if (typeParams == null) {
return MapType.construct(rawClass, _unknownType(), _unknownType());
}
// but exactly 2 types if any found
if (typeParams.length != 2) {
throw new IllegalArgumentException("Strange Map type "+rawClass.getName()+": can not determine type parameters");
}
return MapType.construct(rawClass, typeParams[0], typeParams[1]);
} | src/main/java/com/fasterxml/jackson/databind/type/TypeFactory.java |
JacksonDatabind-24 | public BaseSettings withDateFormat(DateFormat df) {
if (_dateFormat == df) {
return this;
}
TimeZone tz = (df == null) ? _timeZone : df.getTimeZone();
return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,
_typeResolverBuilder, df, _handlerInstantiator, _locale,
tz, _defaultBase64);
}
public BaseSettings withDateFormat(DateFormat df) {
if (_dateFormat == df) {
return this;
}
return new BaseSettings(_classIntrospector, _annotationIntrospector, _visibilityChecker, _propertyNamingStrategy, _typeFactory,
_typeResolverBuilder, df, _handlerInstantiator, _locale,
_timeZone, _defaultBase64);
} | src/main/java/com/fasterxml/jackson/databind/cfg/BaseSettings.java |
JacksonDatabind-27 | protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)
throws IOException
{
final ExternalTypeHandler ext = _externalTypeIdHandler.start();
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
// first: let's check to see if this might be part of value with external type id:
// 11-Sep-2015, tatu: Important; do NOT pass buffer as last arg, but null,
// since it is not the bean
if (ext.handlePropertyValue(p, ctxt, propName, buffer)) {
;
} else {
// Last creator property to set?
if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
continue; // never gets here
}
// if so, need to copy all remaining tokens into buffer
while (t == JsonToken.FIELD_NAME) {
p.nextToken(); // to skip name
tokens.copyCurrentStructure(p);
t = p.nextToken();
}
if (bean.getClass() != _beanType.getRawClass()) {
// !!! 08-Jul-2011, tatu: Could theoretically support; but for now
// it's too complicated, so bail out
throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values");
}
return ext.complete(p, ctxt, bean);
}
}
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
continue;
}
// external type id (or property that depends on it)?
if (ext.handlePropertyValue(p, ctxt, propName, null)) {
continue;
}
/* As per [JACKSON-313], things marked as ignorable should not be
* passed to any setter
*/
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
// "any property"?
if (_anySetter != null) {
buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
}
}
// We hit END_OBJECT; resolve the pieces:
try {
return ext.complete(p, ctxt, buffer, creator);
} catch (Exception e) {
wrapInstantiationProblem(e, ctxt);
return null; // never gets here
}
}
protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser p, DeserializationContext ctxt)
throws IOException
{
final ExternalTypeHandler ext = _externalTypeIdHandler.start();
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
// first: let's check to see if this might be part of value with external type id:
// 11-Sep-2015, tatu: Important; do NOT pass buffer as last arg, but null,
// since it is not the bean
if (ext.handlePropertyValue(p, ctxt, propName, null)) {
;
} else {
// Last creator property to set?
if (buffer.assignParameter(creatorProp, _deserializeWithErrorWrapping(p, ctxt, creatorProp))) {
t = p.nextToken(); // to move to following FIELD_NAME/END_OBJECT
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
continue; // never gets here
}
// if so, need to copy all remaining tokens into buffer
while (t == JsonToken.FIELD_NAME) {
p.nextToken(); // to skip name
tokens.copyCurrentStructure(p);
t = p.nextToken();
}
if (bean.getClass() != _beanType.getRawClass()) {
// !!! 08-Jul-2011, tatu: Could theoretically support; but for now
// it's too complicated, so bail out
throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values");
}
return ext.complete(p, ctxt, bean);
}
}
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
continue;
}
// external type id (or property that depends on it)?
if (ext.handlePropertyValue(p, ctxt, propName, null)) {
continue;
}
/* As per [JACKSON-313], things marked as ignorable should not be
* passed to any setter
*/
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
// "any property"?
if (_anySetter != null) {
buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
}
}
// We hit END_OBJECT; resolve the pieces:
try {
return ext.complete(p, ctxt, buffer, creator);
} catch (Exception e) {
wrapInstantiationProblem(e, ctxt);
return null; // never gets here
}
} | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializer.java |
JacksonDatabind-28 | public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
if (p.getCurrentToken() == JsonToken.START_OBJECT) {
p.nextToken();
return deserializeObject(p, ctxt, ctxt.getNodeFactory());
}
// 23-Sep-2015, tatu: Ugh. We may also be given END_OBJECT (similar to FIELD_NAME),
// if caller has advanced to the first token of Object, but for empty Object
if (p.getCurrentToken() == JsonToken.FIELD_NAME) {
return deserializeObject(p, ctxt, ctxt.getNodeFactory());
}
throw ctxt.mappingException(ObjectNode.class);
}
public ObjectNode deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
if (p.isExpectedStartObjectToken() || p.hasToken(JsonToken.FIELD_NAME)) {
return deserializeObject(p, ctxt, ctxt.getNodeFactory());
}
// 23-Sep-2015, tatu: Ugh. We may also be given END_OBJECT (similar to FIELD_NAME),
// if caller has advanced to the first token of Object, but for empty Object
if (p.hasToken(JsonToken.END_OBJECT)) {
return ctxt.getNodeFactory().objectNode();
}
throw ctxt.mappingException(ObjectNode.class);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/JsonNodeDeserializer.java |
JacksonDatabind-33 | public PropertyName findNameForSerialization(Annotated a)
{
String name = null;
JsonGetter jg = _findAnnotation(a, JsonGetter.class);
if (jg != null) {
name = jg.value();
} else {
JsonProperty pann = _findAnnotation(a, JsonProperty.class);
if (pann != null) {
name = pann.value();
/* 22-Apr-2014, tatu: Should figure out a better way to do this, but
* it's actually bit tricky to do it more efficiently (meta-annotations
* add more lookups; AnnotationMap costs etc)
*/
} else if (_hasAnnotation(a, JsonSerialize.class)
|| _hasAnnotation(a, JsonView.class)
|| _hasAnnotation(a, JsonRawValue.class)) {
name = "";
} else {
return null;
}
}
return PropertyName.construct(name);
}
public PropertyName findNameForSerialization(Annotated a)
{
String name = null;
JsonGetter jg = _findAnnotation(a, JsonGetter.class);
if (jg != null) {
name = jg.value();
} else {
JsonProperty pann = _findAnnotation(a, JsonProperty.class);
if (pann != null) {
name = pann.value();
/* 22-Apr-2014, tatu: Should figure out a better way to do this, but
* it's actually bit tricky to do it more efficiently (meta-annotations
* add more lookups; AnnotationMap costs etc)
*/
} else if (_hasAnnotation(a, JsonSerialize.class)
|| _hasAnnotation(a, JsonView.class)
|| _hasAnnotation(a, JsonRawValue.class)
|| _hasAnnotation(a, JsonUnwrapped.class)
|| _hasAnnotation(a, JsonBackReference.class)
|| _hasAnnotation(a, JsonManagedReference.class)) {
name = "";
} else {
return null;
}
}
return PropertyName.construct(name);
} | src/main/java/com/fasterxml/jackson/databind/introspect/JacksonAnnotationIntrospector.java |
JacksonDatabind-34 | public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
if (_isInt) {
visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);
} else {
Class<?> h = handledType();
if (h == BigDecimal.class) {
visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);
} else {
// otherwise bit unclear what to call... but let's try:
/*JsonNumberFormatVisitor v2 =*/ visitor.expectNumberFormat(typeHint);
}
}
}
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) throws JsonMappingException
{
if (_isInt) {
visitIntFormat(visitor, typeHint, JsonParser.NumberType.BIG_INTEGER);
} else {
Class<?> h = handledType();
if (h == BigDecimal.class) {
visitFloatFormat(visitor, typeHint, JsonParser.NumberType.BIG_DECIMAL);
} else {
// otherwise bit unclear what to call... but let's try:
/*JsonNumberFormatVisitor v2 =*/ visitor.expectNumberFormat(typeHint);
}
}
} | src/main/java/com/fasterxml/jackson/databind/ser/std/NumberSerializer.java |
JacksonDatabind-35 | private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 02-Aug-2013, tatu: May need to use native type ids
if (p.canReadTypeId()) {
Object typeId = p.getTypeId();
if (typeId != null) {
return _deserializeWithNativeTypeId(p, ctxt, typeId);
}
}
// first, sanity checks
if (p.getCurrentToken() != JsonToken.START_OBJECT) {
throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,
"need JSON Object to contain As.WRAPPER_OBJECT type information for class "+baseTypeName());
}
// should always get field name, but just in case...
if (p.nextToken() != JsonToken.FIELD_NAME) {
throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,
"need JSON String that contains type id (for subtype of "+baseTypeName()+")");
}
final String typeId = p.getText();
JsonDeserializer<Object> deser = _findDeserializer(ctxt, typeId);
p.nextToken();
// Minor complication: we may need to merge type id in?
if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {
// but what if there's nowhere to add it in? Error? Or skip? For now, skip.
TokenBuffer tb = new TokenBuffer(null, false);
tb.writeStartObject(); // recreate START_OBJECT
tb.writeFieldName(_typePropertyName);
tb.writeString(typeId);
p = JsonParserSequence.createFlattened(tb.asParser(p), p);
p.nextToken();
}
Object value = deser.deserialize(p, ctxt);
// And then need the closing END_OBJECT
if (p.nextToken() != JsonToken.END_OBJECT) {
throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,
"expected closing END_OBJECT after type information and deserialized value");
}
return value;
}
private final Object _deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 02-Aug-2013, tatu: May need to use native type ids
if (p.canReadTypeId()) {
Object typeId = p.getTypeId();
if (typeId != null) {
return _deserializeWithNativeTypeId(p, ctxt, typeId);
}
}
// first, sanity checks
JsonToken t = p.getCurrentToken();
if (t == JsonToken.START_OBJECT) {
// should always get field name, but just in case...
if (p.nextToken() != JsonToken.FIELD_NAME) {
throw ctxt.wrongTokenException(p, JsonToken.FIELD_NAME,
"need JSON String that contains type id (for subtype of "+baseTypeName()+")");
}
} else if (t != JsonToken.FIELD_NAME) {
throw ctxt.wrongTokenException(p, JsonToken.START_OBJECT,
"need JSON Object to contain As.WRAPPER_OBJECT type information for class "+baseTypeName());
}
final String typeId = p.getText();
JsonDeserializer<Object> deser = _findDeserializer(ctxt, typeId);
p.nextToken();
// Minor complication: we may need to merge type id in?
if (_typeIdVisible && p.getCurrentToken() == JsonToken.START_OBJECT) {
// but what if there's nowhere to add it in? Error? Or skip? For now, skip.
TokenBuffer tb = new TokenBuffer(null, false);
tb.writeStartObject(); // recreate START_OBJECT
tb.writeFieldName(_typePropertyName);
tb.writeString(typeId);
p = JsonParserSequence.createFlattened(tb.asParser(p), p);
p.nextToken();
}
Object value = deser.deserialize(p, ctxt);
// And then need the closing END_OBJECT
if (p.nextToken() != JsonToken.END_OBJECT) {
throw ctxt.wrongTokenException(p, JsonToken.END_OBJECT,
"expected closing END_OBJECT after type information and deserialized value");
}
return value;
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/AsWrapperTypeDeserializer.java |
JacksonDatabind-37 | protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values, so no.
/*
if (!_class.isAssignableFrom(subclass)) {
throw new IllegalArgumentException("Class "+subclass.getName()+" not sub-type of "
+_class.getName());
}
*/
// 15-Jan-2015, tatu: Not correct; should really re-resolve...
return new SimpleType(subclass, _bindings, _superClass, _superInterfaces,
_valueHandler, _typeHandler, _asStatic);
}
protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values, so no.
/*
if (!_class.isAssignableFrom(subclass)) {
throw new IllegalArgumentException("Class "+subclass.getName()+" not sub-type of "
+_class.getName());
}
*/
// 15-Jan-2015, tatu: Not correct; should really re-resolve...
return new SimpleType(subclass, _bindings, this, _superInterfaces,
_valueHandler, _typeHandler, _asStatic);
} | src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java |
JacksonDatabind-39 | public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 29-Jan-2016, tatu: Simple skipping for all other tokens, but FIELD_NAME bit
// special unfortunately
p.skipChildren();
return null;
}
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 29-Jan-2016, tatu: Simple skipping for all other tokens, but FIELD_NAME bit
// special unfortunately
if (p.hasToken(JsonToken.FIELD_NAME)) {
while (true) {
JsonToken t = p.nextToken();
if ((t == null) || (t == JsonToken.END_OBJECT)) {
break;
}
p.skipChildren();
}
} else {
p.skipChildren();
}
return null;
} | src/main/java/com/fasterxml/jackson/databind/deser/std/NullifyingDeserializer.java |
JacksonDatabind-42 | protected Object _deserializeFromEmptyString() throws IOException {
// As per [databind#398], URI requires special handling
if (_kind == STD_URI) {
return URI.create("");
}
// As per [databind#1123], Locale too
return super._deserializeFromEmptyString();
}
protected Object _deserializeFromEmptyString() throws IOException {
// As per [databind#398], URI requires special handling
if (_kind == STD_URI) {
return URI.create("");
}
// As per [databind#1123], Locale too
if (_kind == STD_LOCALE) {
return Locale.ROOT;
}
return super._deserializeFromEmptyString();
} | src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java |
JacksonDatabind-44 | protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values (`Void`, `NoClass`), so can not quite do yet.
// TODO: fix in 2.8
/*
throw new IllegalArgumentException("Class "+subclass.getName()+" not sub-type of "
+_class.getName());
*/
return new SimpleType(subclass, _bindings, this, _superInterfaces,
_valueHandler, _typeHandler, _asStatic);
// Otherwise, stitch together the hierarchy. First, super-class
// if not found, try a super-interface
// should not get here but...
}
protected JavaType _narrow(Class<?> subclass)
{
if (_class == subclass) {
return this;
}
// Should we check that there is a sub-class relationship?
// 15-Jan-2016, tatu: Almost yes, but there are some complications with
// placeholder values (`Void`, `NoClass`), so can not quite do yet.
// TODO: fix in 2.8
if (!_class.isAssignableFrom(subclass)) {
/*
throw new IllegalArgumentException("Class "+subclass.getName()+" not sub-type of "
+_class.getName());
*/
return new SimpleType(subclass, _bindings, this, _superInterfaces,
_valueHandler, _typeHandler, _asStatic);
}
// Otherwise, stitch together the hierarchy. First, super-class
Class<?> next = subclass.getSuperclass();
if (next == _class) { // straight up parent class? Great.
return new SimpleType(subclass, _bindings, this,
_superInterfaces, _valueHandler, _typeHandler, _asStatic);
}
if ((next != null) && _class.isAssignableFrom(next)) {
JavaType superb = _narrow(next);
return new SimpleType(subclass, _bindings, superb,
null, _valueHandler, _typeHandler, _asStatic);
}
// if not found, try a super-interface
Class<?>[] nextI = subclass.getInterfaces();
for (Class<?> iface : nextI) {
if (iface == _class) { // directly implemented
return new SimpleType(subclass, _bindings, null,
new JavaType[] { this }, _valueHandler, _typeHandler, _asStatic);
}
if (_class.isAssignableFrom(iface)) { // indirect, so recurse
JavaType superb = _narrow(iface);
return new SimpleType(subclass, _bindings, null,
new JavaType[] { superb }, _valueHandler, _typeHandler, _asStatic);
}
}
// should not get here but...
throw new IllegalArgumentException("Internal error: Can not resolve sub-type for Class "+subclass.getName()+" to "
+_class.getName());
} | src/main/java/com/fasterxml/jackson/databind/type/SimpleType.java |
JacksonDatabind-45 | public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property != null) {
JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());
if (format != null) {
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
if (format.getShape() == JsonFormat.Shape.STRING) {
TimeZone tz = format.getTimeZone();
final String pattern = format.hasPattern()
? format.getPattern()
: StdDateFormat.DATE_FORMAT_STR_ISO8601;
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(pattern, loc);
if (tz == null) {
tz = serializers.getTimeZone();
}
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
}
}
return this;
}
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property != null) {
JsonFormat.Value format = serializers.getAnnotationIntrospector().findFormat((Annotated)property.getMember());
if (format != null) {
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()
|| format.hasLocale() || format.hasTimeZone()) {
TimeZone tz = format.getTimeZone();
final String pattern = format.hasPattern()
? format.getPattern()
: StdDateFormat.DATE_FORMAT_STR_ISO8601;
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(pattern, loc);
if (tz == null) {
tz = serializers.getTimeZone();
}
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
}
}
return this;
} | src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java |
JacksonDatabind-46 | public StringBuilder getGenericSignature(StringBuilder sb)
{
_classSignature(_class, sb, false);
sb.append('<');
sb = _referencedType.getGenericSignature(sb);
sb.append(';');
return sb;
}
public StringBuilder getGenericSignature(StringBuilder sb)
{
_classSignature(_class, sb, false);
sb.append('<');
sb = _referencedType.getGenericSignature(sb);
sb.append(">;");
return sb;
} | src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java |
JacksonDatabind-47 | public JavaType refineSerializationType(final MapperConfig<?> config,
final Annotated a, final JavaType baseType) throws JsonMappingException
{
JavaType type = baseType;
final TypeFactory tf = config.getTypeFactory();
// 10-Oct-2015, tatu: For 2.7, we'll need to delegate back to
// now-deprecated secondary methods; this because while
// direct sub-class not yet retrofitted may only override
// those methods. With 2.8 or later we may consider removal
// of these methods
// Ok: start by refining the main type itself; common to all types
Class<?> serClass = findSerializationType(a);
if (serClass != null) {
if (type.hasRawClass(serClass)) {
// 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of
// static typing this way
type = type.withStaticTyping();
} else {
try {
// 11-Oct-2015, tatu: For deser, we call `TypeFactory.constructSpecializedType()`,
// may be needed here too in future?
type = tf.constructGeneralizedType(type, serClass);
} catch (IllegalArgumentException iae) {
throw new JsonMappingException(null,
String.format("Failed to widen type %s with annotation (value %s), from '%s': %s",
type, serClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
}
// Then further processing for container types
// First, key type (for Maps, Map-like types):
if (type.isMapLikeType()) {
JavaType keyType = type.getKeyType();
Class<?> keyClass = findSerializationKeyType(a, keyType);
if (keyClass != null) {
if (keyType.hasRawClass(keyClass)) {
keyType = keyType.withStaticTyping();
} else {
Class<?> currRaw = keyType.getRawClass();
try {
// 19-May-2016, tatu: As per [databind#1231], [databind#1178] may need to actually
// specialize (narrow) type sometimes, even if more commonly opposite
// is needed.
if (keyClass.isAssignableFrom(currRaw)) { // common case
keyType = tf.constructGeneralizedType(keyType, keyClass);
} else if (currRaw.isAssignableFrom(keyClass)) { // specialization, ok as well
keyType = tf.constructSpecializedType(keyType, keyClass);
} else {
throw new JsonMappingException(null,
String.format("Can not refine serialization key type %s into %s; types not related",
keyType, keyClass.getName()));
}
} catch (IllegalArgumentException iae) {
throw new JsonMappingException(null,
String.format("Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s",
type, keyClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
type = ((MapLikeType) type).withKeyType(keyType);
}
}
JavaType contentType = type.getContentType();
if (contentType != null) { // collection[like], map[like], array, reference
// And then value types for all containers:
Class<?> contentClass = findSerializationContentType(a, contentType);
if (contentClass != null) {
if (contentType.hasRawClass(contentClass)) {
contentType = contentType.withStaticTyping();
} else {
// 03-Apr-2016, tatu: As per [databind#1178], may need to actually
// specialize (narrow) type sometimes, even if more commonly opposite
// is needed.
Class<?> currRaw = contentType.getRawClass();
try {
if (contentClass.isAssignableFrom(currRaw)) { // common case
contentType = tf.constructGeneralizedType(contentType, contentClass);
} else if (currRaw.isAssignableFrom(contentClass)) { // specialization, ok as well
contentType = tf.constructSpecializedType(contentType, contentClass);
} else {
throw new JsonMappingException(null,
String.format("Can not refine serialization content type %s into %s; types not related",
contentType, contentClass.getName()));
}
} catch (IllegalArgumentException iae) { // shouldn't really happen
throw new JsonMappingException(null,
String.format("Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s",
type, contentClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
type = type.withContentType(contentType);
}
}
return type;
}
public JavaType refineSerializationType(final MapperConfig<?> config,
final Annotated a, final JavaType baseType) throws JsonMappingException
{
JavaType type = baseType;
final TypeFactory tf = config.getTypeFactory();
// 10-Oct-2015, tatu: For 2.7, we'll need to delegate back to
// now-deprecated secondary methods; this because while
// direct sub-class not yet retrofitted may only override
// those methods. With 2.8 or later we may consider removal
// of these methods
// Ok: start by refining the main type itself; common to all types
Class<?> serClass = findSerializationType(a);
if (serClass != null) {
if (type.hasRawClass(serClass)) {
// 30-Nov-2015, tatu: As per [databind#1023], need to allow forcing of
// static typing this way
type = type.withStaticTyping();
} else {
Class<?> currRaw = type.getRawClass();
try {
// 11-Oct-2015, tatu: For deser, we call `TypeFactory.constructSpecializedType()`,
// may be needed here too in future?
if (serClass.isAssignableFrom(currRaw)) { // common case
type = tf.constructGeneralizedType(type, serClass);
} else if (currRaw.isAssignableFrom(serClass)) { // specialization, ok as well
type = tf.constructSpecializedType(type, serClass);
} else {
throw new JsonMappingException(null,
String.format("Can not refine serialization type %s into %s; types not related",
type, serClass.getName()));
}
} catch (IllegalArgumentException iae) {
throw new JsonMappingException(null,
String.format("Failed to widen type %s with annotation (value %s), from '%s': %s",
type, serClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
}
// Then further processing for container types
// First, key type (for Maps, Map-like types):
if (type.isMapLikeType()) {
JavaType keyType = type.getKeyType();
Class<?> keyClass = findSerializationKeyType(a, keyType);
if (keyClass != null) {
if (keyType.hasRawClass(keyClass)) {
keyType = keyType.withStaticTyping();
} else {
Class<?> currRaw = keyType.getRawClass();
try {
// 19-May-2016, tatu: As per [databind#1231], [databind#1178] may need to actually
// specialize (narrow) type sometimes, even if more commonly opposite
// is needed.
if (keyClass.isAssignableFrom(currRaw)) { // common case
keyType = tf.constructGeneralizedType(keyType, keyClass);
} else if (currRaw.isAssignableFrom(keyClass)) { // specialization, ok as well
keyType = tf.constructSpecializedType(keyType, keyClass);
} else {
throw new JsonMappingException(null,
String.format("Can not refine serialization key type %s into %s; types not related",
keyType, keyClass.getName()));
}
} catch (IllegalArgumentException iae) {
throw new JsonMappingException(null,
String.format("Failed to widen key type of %s with concrete-type annotation (value %s), from '%s': %s",
type, keyClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
type = ((MapLikeType) type).withKeyType(keyType);
}
}
JavaType contentType = type.getContentType();
if (contentType != null) { // collection[like], map[like], array, reference
// And then value types for all containers:
Class<?> contentClass = findSerializationContentType(a, contentType);
if (contentClass != null) {
if (contentType.hasRawClass(contentClass)) {
contentType = contentType.withStaticTyping();
} else {
// 03-Apr-2016, tatu: As per [databind#1178], may need to actually
// specialize (narrow) type sometimes, even if more commonly opposite
// is needed.
Class<?> currRaw = contentType.getRawClass();
try {
if (contentClass.isAssignableFrom(currRaw)) { // common case
contentType = tf.constructGeneralizedType(contentType, contentClass);
} else if (currRaw.isAssignableFrom(contentClass)) { // specialization, ok as well
contentType = tf.constructSpecializedType(contentType, contentClass);
} else {
throw new JsonMappingException(null,
String.format("Can not refine serialization content type %s into %s; types not related",
contentType, contentClass.getName()));
}
} catch (IllegalArgumentException iae) { // shouldn't really happen
throw new JsonMappingException(null,
String.format("Internal error: failed to refine value type of %s with concrete-type annotation (value %s), from '%s': %s",
type, contentClass.getName(), a.getName(), iae.getMessage()),
iae);
}
}
type = type.withContentType(contentType);
}
}
return type;
} | src/main/java/com/fasterxml/jackson/databind/AnnotationIntrospector.java |
JacksonDatabind-49 | public Object generateId(Object forPojo) {
// 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of
// id being generated for "alwaysAsId", but not being written as POJO; regardless,
// need to use existing id if there is one:
id = generator.generateId(forPojo);
return id;
}
public Object generateId(Object forPojo) {
// 04-Jun-2016, tatu: As per [databind#1255], need to consider possibility of
// id being generated for "alwaysAsId", but not being written as POJO; regardless,
// need to use existing id if there is one:
if (id == null) {
id = generator.generateId(forPojo);
}
return id;
} | src/main/java/com/fasterxml/jackson/databind/ser/impl/WritableObjectId.java |
JacksonDatabind-5 | protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods,
Class<?> mixInCls, AnnotatedMethodMap mixIns)
{
List<Class<?>> parents = new ArrayList<Class<?>>();
parents.add(mixInCls);
ClassUtil.findSuperTypes(mixInCls, targetClass, parents);
for (Class<?> mixin : parents) {
for (Method m : mixin.getDeclaredMethods()) {
if (!_isIncludableMemberMethod(m)) {
continue;
}
AnnotatedMethod am = methods.find(m);
/* Do we already have a method to augment (from sub-class
* that will mask this mixIn)? If so, add if visible
* without masking (no such annotation)
*/
if (am != null) {
_addMixUnders(m, am);
/* Otherwise will have precedence, but must wait
* until we find the real method (mixIn methods are
* just placeholder, can't be called)
*/
} else {
// Well, or, as per [Issue#515], multi-level merge within mixins...
mixIns.add(_constructMethod(m));
}
}
}
}
protected void _addMethodMixIns(Class<?> targetClass, AnnotatedMethodMap methods,
Class<?> mixInCls, AnnotatedMethodMap mixIns)
{
List<Class<?>> parents = new ArrayList<Class<?>>();
parents.add(mixInCls);
ClassUtil.findSuperTypes(mixInCls, targetClass, parents);
for (Class<?> mixin : parents) {
for (Method m : mixin.getDeclaredMethods()) {
if (!_isIncludableMemberMethod(m)) {
continue;
}
AnnotatedMethod am = methods.find(m);
/* Do we already have a method to augment (from sub-class
* that will mask this mixIn)? If so, add if visible
* without masking (no such annotation)
*/
if (am != null) {
_addMixUnders(m, am);
/* Otherwise will have precedence, but must wait
* until we find the real method (mixIn methods are
* just placeholder, can't be called)
*/
} else {
// Well, or, as per [Issue#515], multi-level merge within mixins...
am = mixIns.find(m);
if (am != null) {
_addMixUnders(m, am);
} else {
mixIns.add(_constructMethod(m));
}
}
}
}
} | src/main/java/com/fasterxml/jackson/databind/introspect/AnnotatedClass.java |
JacksonDatabind-51 | protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [Databind#305], need to provide contextual info. But for
* backwards compatibility, let's start by only supporting this
* for base class, not via interface. Later on we can add this
* to the interface, assuming deprecation at base class helps.
*/
JavaType type = _idResolver.typeFromId(ctxt, typeId);
if (type == null) {
// As per [JACKSON-614], use the default impl if no type id available:
deser = _findDefaultImplDeserializer(ctxt);
if (deser == null) {
// 10-May-2016, tatu: We may get some help...
JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);
if (actual == null) { // what should this be taken to mean?
// TODO: try to figure out something better
return null;
}
// ... would this actually work?
deser = ctxt.findContextualValueDeserializer(actual, _property);
}
} else {
/* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
* we actually now need to explicitly narrow from base type (which may have parameterization)
* using raw type.
*
* One complication, though; can not change 'type class' (simple type to container); otherwise
* we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
* type in process (getting SimpleType of Map.class which will not work as expected)
*/
if ((_baseType != null)
&& _baseType.getClass() == type.getClass()) {
/* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
* but it appears to check that JavaType impl class is the same which is
* important for some reason?
* Disabling the check will break 2 Enum-related tests.
*/
// 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
// generic type with custom type resolvers. If so, should try to retain them.
// Whether this is sufficient to avoid problems remains to be seen, but for
// now it should improve things.
type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
}
deser = ctxt.findContextualValueDeserializer(type, _property);
}
_deserializers.put(typeId, deser);
}
return deser;
}
protected final JsonDeserializer<Object> _findDeserializer(DeserializationContext ctxt,
String typeId) throws IOException
{
JsonDeserializer<Object> deser = _deserializers.get(typeId);
if (deser == null) {
/* As per [Databind#305], need to provide contextual info. But for
* backwards compatibility, let's start by only supporting this
* for base class, not via interface. Later on we can add this
* to the interface, assuming deprecation at base class helps.
*/
JavaType type = _idResolver.typeFromId(ctxt, typeId);
if (type == null) {
// As per [JACKSON-614], use the default impl if no type id available:
deser = _findDefaultImplDeserializer(ctxt);
if (deser == null) {
// 10-May-2016, tatu: We may get some help...
JavaType actual = _handleUnknownTypeId(ctxt, typeId, _idResolver, _baseType);
if (actual == null) { // what should this be taken to mean?
// TODO: try to figure out something better
return null;
}
// ... would this actually work?
deser = ctxt.findContextualValueDeserializer(actual, _property);
}
} else {
/* 16-Dec-2010, tatu: Since nominal type we get here has no (generic) type parameters,
* we actually now need to explicitly narrow from base type (which may have parameterization)
* using raw type.
*
* One complication, though; can not change 'type class' (simple type to container); otherwise
* we may try to narrow a SimpleType (Object.class) into MapType (Map.class), losing actual
* type in process (getting SimpleType of Map.class which will not work as expected)
*/
if ((_baseType != null)
&& _baseType.getClass() == type.getClass()) {
/* 09-Aug-2015, tatu: Not sure if the second part of the check makes sense;
* but it appears to check that JavaType impl class is the same which is
* important for some reason?
* Disabling the check will break 2 Enum-related tests.
*/
// 19-Jun-2016, tatu: As per [databind#1270] we may actually get full
// generic type with custom type resolvers. If so, should try to retain them.
// Whether this is sufficient to avoid problems remains to be seen, but for
// now it should improve things.
if (!type.hasGenericTypes()) {
type = ctxt.getTypeFactory().constructSpecializedType(_baseType, type.getRawClass());
}
}
deser = ctxt.findContextualValueDeserializer(type, _property);
}
_deserializers.put(typeId, deser);
}
return deser;
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/TypeDeserializerBase.java |
JacksonDatabind-54 | protected BeanPropertyWriter buildWriter(SerializerProvider prov,
BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser,
TypeSerializer typeSer, TypeSerializer contentTypeSer,
AnnotatedMember am, boolean defaultUseStaticTyping)
throws JsonMappingException
{
// do we have annotation that forces type to use (to declared type or its super type)?
JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
// Container types can have separate type serializers for content (value / element) type
if (contentTypeSer != null) {
/* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
* type information for contents. Should work well (for JAXB case); can be
* revisited if this causes problems.
*/
if (serializationType == null) {
// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
serializationType = declaredType;
}
JavaType ct = serializationType.getContentType();
// Not exactly sure why, but this used to occur; better check explicitly:
if (ct == null) {
throw new IllegalStateException("Problem trying to create BeanPropertyWriter for property '"
+propDef.getName()+"' (of type "+_beanDesc.getType()+"); serialization type "+serializationType+" has no content");
}
serializationType = serializationType.withContentTypeHandler(contentTypeSer);
ct = serializationType.getContentType();
}
Object valueToSuppress = null;
boolean suppressNulls = false;
JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());
JsonInclude.Include inclusion = inclV.getValueInclusion();
if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
inclusion = JsonInclude.Include.ALWAYS;
}
// 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
JavaType actualType = (serializationType == null) ? declaredType : serializationType;
switch (inclusion) {
case NON_DEFAULT:
// 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
// so that if enclosing class has this, we may need to values of property,
// whereas for global defaults OR per-property overrides, we have more
// static definition. Sigh.
// First: case of class specifying it; try to find POJO property defaults
if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {
valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);
} else {
valueToSuppress = getDefaultValue(actualType);
}
if (valueToSuppress == null) {
suppressNulls = true;
} else {
if (valueToSuppress.getClass().isArray()) {
valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
}
}
break;
case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
// always suppress nulls
suppressNulls = true;
// and for referential types, also "empty", which in their case means "absent"
if (declaredType.isReferenceType()) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
case NON_EMPTY:
// always suppress nulls
suppressNulls = true;
// but possibly also 'empty' values:
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
break;
case NON_NULL:
suppressNulls = true;
// fall through
case ALWAYS: // default
default:
// we may still want to suppress empty collections, as per [JACKSON-254]:
if (declaredType.isContainerType()
&& !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
}
BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
am, _beanDesc.getClassAnnotations(), declaredType,
ser, typeSer, serializationType, suppressNulls, valueToSuppress);
// How about custom null serializer?
Object serDef = _annotationIntrospector.findNullSerializer(am);
if (serDef != null) {
bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
}
// And then, handling of unwrapping
NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
if (unwrapper != null) {
bpw = bpw.unwrappingWriter(unwrapper);
}
return bpw;
}
protected BeanPropertyWriter buildWriter(SerializerProvider prov,
BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser,
TypeSerializer typeSer, TypeSerializer contentTypeSer,
AnnotatedMember am, boolean defaultUseStaticTyping)
throws JsonMappingException
{
// do we have annotation that forces type to use (to declared type or its super type)?
JavaType serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
// Container types can have separate type serializers for content (value / element) type
if (contentTypeSer != null) {
/* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
* type information for contents. Should work well (for JAXB case); can be
* revisited if this causes problems.
*/
if (serializationType == null) {
// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
serializationType = declaredType;
}
JavaType ct = serializationType.getContentType();
// Not exactly sure why, but this used to occur; better check explicitly:
if (ct == null) {
throw new IllegalStateException("Problem trying to create BeanPropertyWriter for property '"
+propDef.getName()+"' (of type "+_beanDesc.getType()+"); serialization type "+serializationType+" has no content");
}
serializationType = serializationType.withContentTypeHandler(contentTypeSer);
ct = serializationType.getContentType();
}
Object valueToSuppress = null;
boolean suppressNulls = false;
JsonInclude.Value inclV = _defaultInclusion.withOverrides(propDef.findInclusion());
JsonInclude.Include inclusion = inclV.getValueInclusion();
if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
inclusion = JsonInclude.Include.ALWAYS;
}
// 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
JavaType actualType = (serializationType == null) ? declaredType : serializationType;
switch (inclusion) {
case NON_DEFAULT:
// 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
// so that if enclosing class has this, we may need to values of property,
// whereas for global defaults OR per-property overrides, we have more
// static definition. Sigh.
// First: case of class specifying it; try to find POJO property defaults
if (_defaultInclusion.getValueInclusion() == JsonInclude.Include.NON_DEFAULT) {
valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);
} else {
valueToSuppress = getDefaultValue(actualType);
}
if (valueToSuppress == null) {
suppressNulls = true;
} else {
if (valueToSuppress.getClass().isArray()) {
valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
}
}
break;
case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
// always suppress nulls
suppressNulls = true;
// and for referential types, also "empty", which in their case means "absent"
if (actualType.isReferenceType()) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
case NON_EMPTY:
// always suppress nulls
suppressNulls = true;
// but possibly also 'empty' values:
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
break;
case NON_NULL:
suppressNulls = true;
// fall through
case ALWAYS: // default
default:
// we may still want to suppress empty collections, as per [JACKSON-254]:
if (actualType.isContainerType()
&& !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
}
BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
am, _beanDesc.getClassAnnotations(), declaredType,
ser, typeSer, serializationType, suppressNulls, valueToSuppress);
// How about custom null serializer?
Object serDef = _annotationIntrospector.findNullSerializer(am);
if (serDef != null) {
bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
}
// And then, handling of unwrapping
NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
if (unwrapper != null) {
bpw = bpw.unwrappingWriter(unwrapper);
}
return bpw;
} | src/main/java/com/fasterxml/jackson/databind/ser/PropertyBuilder.java |
JacksonDatabind-57 | public <T> MappingIterator<T> readValues(byte[] src, int offset, int length)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src),
true));
}
public <T> MappingIterator<T> readValues(byte[] src, int offset, int length)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src, offset, length),
true));
} | src/main/java/com/fasterxml/jackson/databind/ObjectReader.java |
JacksonDatabind-58 | protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,
BeanDescription beanDesc, BeanPropertyDefinition propDef,
JavaType propType0)
throws JsonMappingException
{
// need to ensure method is callable (for non-public)
AnnotatedMember mutator = propDef.getNonConstructorMutator();
if (ctxt.canOverrideAccessModifiers()) {
// [databind#877]: explicitly prevent forced access to `cause` of `Throwable`;
// never needed and attempts may cause problems on some platforms.
// !!! NOTE: should be handled better for 2.8 and later
mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
// note: this works since we know there's exactly one argument for methods
BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),
propType0, propDef.getWrapperName(),
beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());
JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);
// did type change?
if (type != propType0) {
property = property.withType(type);
}
// First: does the Method specify the deserializer to use? If so, let's use it.
JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator);
type = modifyTypeByAnnotation(ctxt, mutator, type);
TypeDeserializer typeDeser = type.getTypeHandler();
SettableBeanProperty prop;
if (mutator instanceof AnnotatedMethod) {
prop = new MethodProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);
} else {
prop = new FieldProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedField) mutator);
}
if (propDeser != null) {
prop = prop.withValueDeserializer(propDeser);
}
// need to retain name of managed forward references:
AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();
if (ref != null && ref.isManagedReference()) {
prop.setManagedReferenceName(ref.getName());
}
ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();
if(objectIdInfo != null){
prop.setObjectIdInfo(objectIdInfo);
}
return prop;
}
protected SettableBeanProperty constructSettableProperty(DeserializationContext ctxt,
BeanDescription beanDesc, BeanPropertyDefinition propDef,
JavaType propType0)
throws JsonMappingException
{
// need to ensure method is callable (for non-public)
AnnotatedMember mutator = propDef.getNonConstructorMutator();
if (ctxt.canOverrideAccessModifiers()) {
// [databind#877]: explicitly prevent forced access to `cause` of `Throwable`;
// never needed and attempts may cause problems on some platforms.
// !!! NOTE: should be handled better for 2.8 and later
if ((mutator instanceof AnnotatedField)
&& "cause".equals(mutator.getName())) {
;
} else {
mutator.fixAccess(ctxt.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
}
// note: this works since we know there's exactly one argument for methods
BeanProperty.Std property = new BeanProperty.Std(propDef.getFullName(),
propType0, propDef.getWrapperName(),
beanDesc.getClassAnnotations(), mutator, propDef.getMetadata());
JavaType type = resolveType(ctxt, beanDesc, propType0, mutator);
// did type change?
if (type != propType0) {
property = property.withType(type);
}
// First: does the Method specify the deserializer to use? If so, let's use it.
JsonDeserializer<Object> propDeser = findDeserializerFromAnnotation(ctxt, mutator);
type = modifyTypeByAnnotation(ctxt, mutator, type);
TypeDeserializer typeDeser = type.getTypeHandler();
SettableBeanProperty prop;
if (mutator instanceof AnnotatedMethod) {
prop = new MethodProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedMethod) mutator);
} else {
prop = new FieldProperty(propDef, type, typeDeser,
beanDesc.getClassAnnotations(), (AnnotatedField) mutator);
}
if (propDeser != null) {
prop = prop.withValueDeserializer(propDeser);
}
// need to retain name of managed forward references:
AnnotationIntrospector.ReferenceProperty ref = propDef.findReferenceType();
if (ref != null && ref.isManagedReference()) {
prop.setManagedReferenceName(ref.getName());
}
ObjectIdInfo objectIdInfo = propDef.findObjectIdInfo();
if(objectIdInfo != null){
prop.setObjectIdInfo(objectIdInfo);
}
return prop;
} | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java |
JacksonDatabind-6 | protected Date parseAsISO8601(String dateStr, ParsePosition pos)
{
/* 21-May-2009, tatu: DateFormat has very strict handling of
* timezone modifiers for ISO-8601. So we need to do some scrubbing.
*/
/* First: do we have "zulu" format ('Z' == "GMT")? If yes, that's
* quite simple because we already set date format timezone to be
* GMT, and hence can just strip out 'Z' altogether
*/
int len = dateStr.length();
char c = dateStr.charAt(len-1);
DateFormat df;
// [JACKSON-200]: need to support "plain" date...
if (len <= 10 && Character.isDigit(c)) {
df = _formatPlain;
if (df == null) {
df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);
}
} else if (c == 'Z') {
df = _formatISO8601_z;
if (df == null) {
df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);
}
// [JACKSON-334]: may be missing milliseconds... if so, add
if (dateStr.charAt(len-4) == ':') {
StringBuilder sb = new StringBuilder(dateStr);
sb.insert(len-1, ".000");
dateStr = sb.toString();
}
} else {
// Let's see if we have timezone indicator or not...
if (hasTimeZone(dateStr)) {
c = dateStr.charAt(len-3);
if (c == ':') { // remove optional colon
// remove colon
StringBuilder sb = new StringBuilder(dateStr);
sb.delete(len-3, len-2);
dateStr = sb.toString();
} else if (c == '+' || c == '-') { // missing minutes
// let's just append '00'
dateStr += "00";
}
// Milliseconds partial or missing; and even seconds are optional
len = dateStr.length();
// remove 'T', '+'/'-' and 4-digit timezone-offset
c = dateStr.charAt(len-9);
if (Character.isDigit(c)) {
StringBuilder sb = new StringBuilder(dateStr);
sb.insert(len-5, ".000");
dateStr = sb.toString();
}
df = _formatISO8601;
if (_formatISO8601 == null) {
df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);
}
} else {
// If not, plain date. Easiest to just patch 'Z' in the end?
StringBuilder sb = new StringBuilder(dateStr);
// And possible also millisecond part if missing
int timeLen = len - dateStr.lastIndexOf('T') - 1;
if (timeLen <= 8) {
sb.append(".000");
}
sb.append('Z');
dateStr = sb.toString();
df = _formatISO8601_z;
if (df == null) {
df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,
_timezone, _locale);
}
}
}
return df.parse(dateStr, pos);
}
protected Date parseAsISO8601(String dateStr, ParsePosition pos)
{
/* 21-May-2009, tatu: DateFormat has very strict handling of
* timezone modifiers for ISO-8601. So we need to do some scrubbing.
*/
/* First: do we have "zulu" format ('Z' == "GMT")? If yes, that's
* quite simple because we already set date format timezone to be
* GMT, and hence can just strip out 'Z' altogether
*/
int len = dateStr.length();
char c = dateStr.charAt(len-1);
DateFormat df;
// [JACKSON-200]: need to support "plain" date...
if (len <= 10 && Character.isDigit(c)) {
df = _formatPlain;
if (df == null) {
df = _formatPlain = _cloneFormat(DATE_FORMAT_PLAIN, DATE_FORMAT_STR_PLAIN, _timezone, _locale);
}
} else if (c == 'Z') {
df = _formatISO8601_z;
if (df == null) {
df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z, _timezone, _locale);
}
// [JACKSON-334]: may be missing milliseconds... if so, add
if (dateStr.charAt(len-4) == ':') {
StringBuilder sb = new StringBuilder(dateStr);
sb.insert(len-1, ".000");
dateStr = sb.toString();
}
} else {
// Let's see if we have timezone indicator or not...
if (hasTimeZone(dateStr)) {
c = dateStr.charAt(len-3);
if (c == ':') { // remove optional colon
// remove colon
StringBuilder sb = new StringBuilder(dateStr);
sb.delete(len-3, len-2);
dateStr = sb.toString();
} else if (c == '+' || c == '-') { // missing minutes
// let's just append '00'
dateStr += "00";
}
// Milliseconds partial or missing; and even seconds are optional
len = dateStr.length();
// remove 'T', '+'/'-' and 4-digit timezone-offset
int timeLen = len - dateStr.lastIndexOf('T') - 6;
if (timeLen < 12) { // 8 for hh:mm:ss, 4 for .sss
int offset = len - 5; // insertion offset, before tz-offset
StringBuilder sb = new StringBuilder(dateStr);
switch (timeLen) {
case 11:
sb.insert(offset, '0'); break;
case 10:
sb.insert(offset, "00"); break;
case 9: // is this legal? (just second fraction marker)
sb.insert(offset, "000"); break;
case 8:
sb.insert(offset, ".000"); break;
case 7: // not legal to have single-digit second
break;
case 6: // probably not legal, but let's allow
sb.insert(offset, "00.000");
case 5: // is legal to omit seconds
sb.insert(offset, ":00.000");
}
dateStr = sb.toString();
}
df = _formatISO8601;
if (_formatISO8601 == null) {
df = _formatISO8601 = _cloneFormat(DATE_FORMAT_ISO8601, DATE_FORMAT_STR_ISO8601, _timezone, _locale);
}
} else {
// If not, plain date. Easiest to just patch 'Z' in the end?
StringBuilder sb = new StringBuilder(dateStr);
// And possible also millisecond part if missing
int timeLen = len - dateStr.lastIndexOf('T') - 1;
if (timeLen < 12) { // missing, or partial
switch (timeLen) {
case 11: sb.append('0');
case 10: sb.append('0');
case 9: sb.append('0');
break;
default:
sb.append(".000");
}
}
sb.append('Z');
dateStr = sb.toString();
df = _formatISO8601_z;
if (df == null) {
df = _formatISO8601_z = _cloneFormat(DATE_FORMAT_ISO8601_Z, DATE_FORMAT_STR_ISO8601_Z,
_timezone, _locale);
}
}
}
return df.parse(dateStr, pos);
} | src/main/java/com/fasterxml/jackson/databind/util/StdDateFormat.java |
JacksonDatabind-62 | public CollectionDeserializer createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
// May need to resolve types for delegate-based creators:
JsonDeserializer<Object> delegateDeser = null;
if (_valueInstantiator != null) {
if (_valueInstantiator.canCreateUsingDelegate()) {
JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
if (delegateType == null) {
throw new IllegalArgumentException("Invalid delegate-creator definition for "+_collectionType
+": value instantiator ("+_valueInstantiator.getClass().getName()
+") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'");
}
delegateDeser = findDeserializer(ctxt, delegateType, property);
}
}
// [databind#1043]: allow per-property allow-wrapping of single overrides:
// 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
// comes down to "List vs Collection" I suppose... for now, pass Collection
Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// also, often value deserializer is resolved here:
JsonDeserializer<?> valueDeser = _valueDeserializer;
// May have a content converter
valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
final JavaType vt = _collectionType.getContentType();
if (valueDeser == null) {
valueDeser = ctxt.findContextualValueDeserializer(vt, property);
} else { // if directly assigned, probably not yet contextual, so:
valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);
}
// and finally, type deserializer needs context as well
TypeDeserializer valueTypeDeser = _valueTypeDeserializer;
if (valueTypeDeser != null) {
valueTypeDeser = valueTypeDeser.forProperty(property);
}
return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);
}
public CollectionDeserializer createContextual(DeserializationContext ctxt,
BeanProperty property) throws JsonMappingException
{
// May need to resolve types for delegate-based creators:
JsonDeserializer<Object> delegateDeser = null;
if (_valueInstantiator != null) {
if (_valueInstantiator.canCreateUsingDelegate()) {
JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
if (delegateType == null) {
throw new IllegalArgumentException("Invalid delegate-creator definition for "+_collectionType
+": value instantiator ("+_valueInstantiator.getClass().getName()
+") returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'");
}
delegateDeser = findDeserializer(ctxt, delegateType, property);
} else if (_valueInstantiator.canCreateUsingArrayDelegate()) {
JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());
if (delegateType == null) {
throw new IllegalArgumentException("Invalid array-delegate-creator definition for "+_collectionType
+": value instantiator ("+_valueInstantiator.getClass().getName()
+") returned true for 'canCreateUsingArrayDelegate()', but null for 'getArrayDelegateType()'");
}
delegateDeser = findDeserializer(ctxt, delegateType, property);
}
}
// [databind#1043]: allow per-property allow-wrapping of single overrides:
// 11-Dec-2015, tatu: Should we pass basic `Collection.class`, or more refined? Mostly
// comes down to "List vs Collection" I suppose... for now, pass Collection
Boolean unwrapSingle = findFormatFeature(ctxt, property, Collection.class,
JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
// also, often value deserializer is resolved here:
JsonDeserializer<?> valueDeser = _valueDeserializer;
// May have a content converter
valueDeser = findConvertingContentDeserializer(ctxt, property, valueDeser);
final JavaType vt = _collectionType.getContentType();
if (valueDeser == null) {
valueDeser = ctxt.findContextualValueDeserializer(vt, property);
} else { // if directly assigned, probably not yet contextual, so:
valueDeser = ctxt.handleSecondaryContextualization(valueDeser, property, vt);
}
// and finally, type deserializer needs context as well
TypeDeserializer valueTypeDeser = _valueTypeDeserializer;
if (valueTypeDeser != null) {
valueTypeDeser = valueTypeDeser.forProperty(property);
}
return withResolved(delegateDeser, valueDeser, valueTypeDeser, unwrapSingle);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/CollectionDeserializer.java |
JacksonDatabind-64 | protected BeanPropertyWriter buildWriter(SerializerProvider prov,
BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser,
TypeSerializer typeSer, TypeSerializer contentTypeSer,
AnnotatedMember am, boolean defaultUseStaticTyping)
throws JsonMappingException
{
// do we have annotation that forces type to use (to declared type or its super type)?
JavaType serializationType;
try {
serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
} catch (JsonMappingException e) {
return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());
}
// Container types can have separate type serializers for content (value / element) type
if (contentTypeSer != null) {
/* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
* type information for contents. Should work well (for JAXB case); can be
* revisited if this causes problems.
*/
if (serializationType == null) {
// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
serializationType = declaredType;
}
JavaType ct = serializationType.getContentType();
// Not exactly sure why, but this used to occur; better check explicitly:
if (ct == null) {
prov.reportBadPropertyDefinition(_beanDesc, propDef,
"serialization type "+serializationType+" has no content");
}
serializationType = serializationType.withContentTypeHandler(contentTypeSer);
ct = serializationType.getContentType();
}
Object valueToSuppress = null;
boolean suppressNulls = false;
// 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
JavaType actualType = (serializationType == null) ? declaredType : serializationType;
// 17-Aug-2016, tatu: Default inclusion covers global default (for all types), as well
// as type-default for enclosing POJO. What we need, then, is per-type default (if any)
// for declared property type... and finally property annotation overrides
JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),
_defaultInclusion);
// property annotation override
inclV = inclV.withOverrides(propDef.findInclusion());
JsonInclude.Include inclusion = inclV.getValueInclusion();
if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
inclusion = JsonInclude.Include.ALWAYS;
}
switch (inclusion) {
case NON_DEFAULT:
// 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
// so that if enclosing class has this, we may need to access values of property,
// whereas for global defaults OR per-property overrides, we have more
// static definition. Sigh.
// First: case of class/type specifying it; try to find POJO property defaults
// 16-Oct-2016, tatu: Note: if we can not for some reason create "default instance",
// revert logic to the case of general/per-property handling, so both
// type-default AND null are to be excluded.
// (as per [databind#1417]
if (_useRealPropertyDefaults) {
// 07-Sep-2016, tatu: may also need to front-load access forcing now
if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {
am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
valueToSuppress = getPropertyDefaultValue(propDef.getName(), am, actualType);
} else {
valueToSuppress = getDefaultValue(actualType);
suppressNulls = true;
}
if (valueToSuppress == null) {
suppressNulls = true;
} else {
if (valueToSuppress.getClass().isArray()) {
valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
}
}
break;
case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
// always suppress nulls
suppressNulls = true;
// and for referential types, also "empty", which in their case means "absent"
if (actualType.isReferenceType()) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
case NON_EMPTY:
// always suppress nulls
suppressNulls = true;
// but possibly also 'empty' values:
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
break;
case NON_NULL:
suppressNulls = true;
// fall through
case ALWAYS: // default
default:
// we may still want to suppress empty collections, as per [JACKSON-254]:
if (actualType.isContainerType()
&& !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
}
BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
am, _beanDesc.getClassAnnotations(), declaredType,
ser, typeSer, serializationType, suppressNulls, valueToSuppress);
// How about custom null serializer?
Object serDef = _annotationIntrospector.findNullSerializer(am);
if (serDef != null) {
bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
}
// And then, handling of unwrapping
NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
if (unwrapper != null) {
bpw = bpw.unwrappingWriter(unwrapper);
}
return bpw;
}
protected BeanPropertyWriter buildWriter(SerializerProvider prov,
BeanPropertyDefinition propDef, JavaType declaredType, JsonSerializer<?> ser,
TypeSerializer typeSer, TypeSerializer contentTypeSer,
AnnotatedMember am, boolean defaultUseStaticTyping)
throws JsonMappingException
{
// do we have annotation that forces type to use (to declared type or its super type)?
JavaType serializationType;
try {
serializationType = findSerializationType(am, defaultUseStaticTyping, declaredType);
} catch (JsonMappingException e) {
return prov.reportBadPropertyDefinition(_beanDesc, propDef, e.getMessage());
}
// Container types can have separate type serializers for content (value / element) type
if (contentTypeSer != null) {
/* 04-Feb-2010, tatu: Let's force static typing for collection, if there is
* type information for contents. Should work well (for JAXB case); can be
* revisited if this causes problems.
*/
if (serializationType == null) {
// serializationType = TypeFactory.type(am.getGenericType(), _beanDesc.getType());
serializationType = declaredType;
}
JavaType ct = serializationType.getContentType();
// Not exactly sure why, but this used to occur; better check explicitly:
if (ct == null) {
prov.reportBadPropertyDefinition(_beanDesc, propDef,
"serialization type "+serializationType+" has no content");
}
serializationType = serializationType.withContentTypeHandler(contentTypeSer);
ct = serializationType.getContentType();
}
Object valueToSuppress = null;
boolean suppressNulls = false;
// 12-Jul-2016, tatu: [databind#1256] Need to make sure we consider type refinement
JavaType actualType = (serializationType == null) ? declaredType : serializationType;
// 17-Aug-2016, tatu: Default inclusion covers global default (for all types), as well
// as type-default for enclosing POJO. What we need, then, is per-type default (if any)
// for declared property type... and finally property annotation overrides
JsonInclude.Value inclV = _config.getDefaultPropertyInclusion(actualType.getRawClass(),
_defaultInclusion);
// property annotation override
inclV = inclV.withOverrides(propDef.findInclusion());
JsonInclude.Include inclusion = inclV.getValueInclusion();
if (inclusion == JsonInclude.Include.USE_DEFAULTS) { // should not occur but...
inclusion = JsonInclude.Include.ALWAYS;
}
switch (inclusion) {
case NON_DEFAULT:
// 11-Nov-2015, tatu: This is tricky because semantics differ between cases,
// so that if enclosing class has this, we may need to access values of property,
// whereas for global defaults OR per-property overrides, we have more
// static definition. Sigh.
// First: case of class/type specifying it; try to find POJO property defaults
Object defaultBean;
// 16-Oct-2016, tatu: Note: if we can not for some reason create "default instance",
// revert logic to the case of general/per-property handling, so both
// type-default AND null are to be excluded.
// (as per [databind#1417]
if (_useRealPropertyDefaults && (defaultBean = getDefaultBean()) != null) {
// 07-Sep-2016, tatu: may also need to front-load access forcing now
if (prov.isEnabled(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)) {
am.fixAccess(_config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
}
try {
valueToSuppress = am.getValue(defaultBean);
} catch (Exception e) {
_throwWrapped(e, propDef.getName(), defaultBean);
}
} else {
valueToSuppress = getDefaultValue(actualType);
suppressNulls = true;
}
if (valueToSuppress == null) {
suppressNulls = true;
} else {
if (valueToSuppress.getClass().isArray()) {
valueToSuppress = ArrayBuilders.getArrayComparator(valueToSuppress);
}
}
break;
case NON_ABSENT: // new with 2.6, to support Guava/JDK8 Optionals
// always suppress nulls
suppressNulls = true;
// and for referential types, also "empty", which in their case means "absent"
if (actualType.isReferenceType()) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
case NON_EMPTY:
// always suppress nulls
suppressNulls = true;
// but possibly also 'empty' values:
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
break;
case NON_NULL:
suppressNulls = true;
// fall through
case ALWAYS: // default
default:
// we may still want to suppress empty collections, as per [JACKSON-254]:
if (actualType.isContainerType()
&& !_config.isEnabled(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)) {
valueToSuppress = BeanPropertyWriter.MARKER_FOR_EMPTY;
}
break;
}
BeanPropertyWriter bpw = new BeanPropertyWriter(propDef,
am, _beanDesc.getClassAnnotations(), declaredType,
ser, typeSer, serializationType, suppressNulls, valueToSuppress);
// How about custom null serializer?
Object serDef = _annotationIntrospector.findNullSerializer(am);
if (serDef != null) {
bpw.assignNullSerializer(prov.serializerInstance(am, serDef));
}
// And then, handling of unwrapping
NameTransformer unwrapper = _annotationIntrospector.findUnwrappingNameTransformer(am);
if (unwrapper != null) {
bpw = bpw.unwrappingWriter(unwrapper);
}
return bpw;
} | src/main/java/com/fasterxml/jackson/databind/ser/PropertyBuilder.java |
JacksonDatabind-67 | public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
KeyDeserializer deser = null;
if (_factoryConfig.hasKeyDeserializers()) {
BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());
for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {
deser = d.findKeyDeserializer(type, config, beanDesc);
if (deser != null) {
break;
}
}
}
// the only non-standard thing is this:
if (deser == null) {
if (type.isEnumType()) {
return _createEnumKeyDeserializer(ctxt, type);
}
deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);
}
// and then post-processing
if (deser != null) {
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyKeyDeserializer(config, type, deser);
}
}
}
return deser;
}
public KeyDeserializer createKeyDeserializer(DeserializationContext ctxt,
JavaType type)
throws JsonMappingException
{
final DeserializationConfig config = ctxt.getConfig();
KeyDeserializer deser = null;
if (_factoryConfig.hasKeyDeserializers()) {
BeanDescription beanDesc = config.introspectClassAnnotations(type.getRawClass());
for (KeyDeserializers d : _factoryConfig.keyDeserializers()) {
deser = d.findKeyDeserializer(type, config, beanDesc);
if (deser != null) {
break;
}
}
}
// the only non-standard thing is this:
if (deser == null) {
if (type.isEnumType()) {
deser = _createEnumKeyDeserializer(ctxt, type);
} else {
deser = StdKeyDeserializers.findStringBasedKeyDeserializer(config, type);
}
}
// and then post-processing
if (deser != null) {
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
deser = mod.modifyKeyDeserializer(config, type, deser);
}
}
}
return deser;
} | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java |
JacksonDatabind-7 | public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
copyCurrentStructure(jp);
/* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from
* FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need
* to assume one did exist.
*/
return this;
}
public TokenBuffer deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
if (jp.getCurrentTokenId() != JsonToken.FIELD_NAME.id()) {
copyCurrentStructure(jp);
return this;
}
/* 28-Oct-2014, tatu: As per #592, need to support a special case of starting from
* FIELD_NAME, which is taken to mean that we are missing START_OBJECT, but need
* to assume one did exist.
*/
JsonToken t;
writeStartObject();
do {
copyCurrentStructure(jp);
} while ((t = jp.nextToken()) == JsonToken.FIELD_NAME);
if (t != JsonToken.END_OBJECT) {
throw ctxt.mappingException("Expected END_OBJECT after copying contents of a JsonParser into TokenBuffer, got "+t);
}
writeEndObject();
return this;
} | src/main/java/com/fasterxml/jackson/databind/util/TokenBuffer.java |
JacksonDatabind-70 | public void remove(SettableBeanProperty propToRm)
{
ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size);
String key = getPropertyName(propToRm);
boolean found = false;
for (int i = 1, end = _hashArea.length; i < end; i += 2) {
SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];
if (prop == null) {
continue;
}
if (!found) {
// 09-Jan-2017, tatu: Important: must check name slot and NOT property name,
// as only former is lower-case in case-insensitive case
found = key.equals(prop.getName());
if (found) {
// need to leave a hole here
_propsInOrder[_findFromOrdered(prop)] = null;
continue;
}
}
props.add(prop);
}
if (!found) {
throw new NoSuchElementException("No entry '"+propToRm.getName()+"' found, can't remove");
}
init(props);
}
public void remove(SettableBeanProperty propToRm)
{
ArrayList<SettableBeanProperty> props = new ArrayList<SettableBeanProperty>(_size);
String key = getPropertyName(propToRm);
boolean found = false;
for (int i = 1, end = _hashArea.length; i < end; i += 2) {
SettableBeanProperty prop = (SettableBeanProperty) _hashArea[i];
if (prop == null) {
continue;
}
if (!found) {
// 09-Jan-2017, tatu: Important: must check name slot and NOT property name,
// as only former is lower-case in case-insensitive case
found = key.equals(_hashArea[i-1]);
if (found) {
// need to leave a hole here
_propsInOrder[_findFromOrdered(prop)] = null;
continue;
}
}
props.add(prop);
}
if (!found) {
throw new NoSuchElementException("No entry '"+propToRm.getName()+"' found, can't remove");
}
init(props);
} | src/main/java/com/fasterxml/jackson/databind/deser/impl/BeanPropertyMap.java |
JacksonDatabind-71 | public static StdKeyDeserializer forType(Class<?> raw)
{
int kind;
// first common types:
if (raw == String.class || raw == Object.class) {
return StringKD.forType(raw);
} else if (raw == UUID.class) {
kind = TYPE_UUID;
} else if (raw == Integer.class) {
kind = TYPE_INT;
} else if (raw == Long.class) {
kind = TYPE_LONG;
} else if (raw == Date.class) {
kind = TYPE_DATE;
} else if (raw == Calendar.class) {
kind = TYPE_CALENDAR;
// then less common ones...
} else if (raw == Boolean.class) {
kind = TYPE_BOOLEAN;
} else if (raw == Byte.class) {
kind = TYPE_BYTE;
} else if (raw == Character.class) {
kind = TYPE_CHAR;
} else if (raw == Short.class) {
kind = TYPE_SHORT;
} else if (raw == Float.class) {
kind = TYPE_FLOAT;
} else if (raw == Double.class) {
kind = TYPE_DOUBLE;
} else if (raw == URI.class) {
kind = TYPE_URI;
} else if (raw == URL.class) {
kind = TYPE_URL;
} else if (raw == Class.class) {
kind = TYPE_CLASS;
} else if (raw == Locale.class) {
FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Locale.class);
return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);
} else if (raw == Currency.class) {
FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Currency.class);
return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);
} else {
return null;
}
return new StdKeyDeserializer(kind, raw);
}
public static StdKeyDeserializer forType(Class<?> raw)
{
int kind;
// first common types:
if (raw == String.class || raw == Object.class || raw == CharSequence.class) {
return StringKD.forType(raw);
} else if (raw == UUID.class) {
kind = TYPE_UUID;
} else if (raw == Integer.class) {
kind = TYPE_INT;
} else if (raw == Long.class) {
kind = TYPE_LONG;
} else if (raw == Date.class) {
kind = TYPE_DATE;
} else if (raw == Calendar.class) {
kind = TYPE_CALENDAR;
// then less common ones...
} else if (raw == Boolean.class) {
kind = TYPE_BOOLEAN;
} else if (raw == Byte.class) {
kind = TYPE_BYTE;
} else if (raw == Character.class) {
kind = TYPE_CHAR;
} else if (raw == Short.class) {
kind = TYPE_SHORT;
} else if (raw == Float.class) {
kind = TYPE_FLOAT;
} else if (raw == Double.class) {
kind = TYPE_DOUBLE;
} else if (raw == URI.class) {
kind = TYPE_URI;
} else if (raw == URL.class) {
kind = TYPE_URL;
} else if (raw == Class.class) {
kind = TYPE_CLASS;
} else if (raw == Locale.class) {
FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Locale.class);
return new StdKeyDeserializer(TYPE_LOCALE, raw, deser);
} else if (raw == Currency.class) {
FromStringDeserializer<?> deser = FromStringDeserializer.findDeserializer(Currency.class);
return new StdKeyDeserializer(TYPE_CURRENCY, raw, deser);
} else {
return null;
}
return new StdKeyDeserializer(kind, raw);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/StdKeyDeserializer.java |
JacksonDatabind-74 | protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,
TokenBuffer tb) throws IOException
{
// As per [JACKSON-614], may have default implementation to use
JsonDeserializer<Object> deser = _findDefaultImplDeserializer(ctxt);
if (deser != null) {
if (tb != null) {
tb.writeEndObject();
p = tb.asParser(p);
// must move to point to the first token:
p.nextToken();
}
return deser.deserialize(p, ctxt);
}
// or, perhaps we just bumped into a "natural" value (boolean/int/double/String)?
Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);
if (result != null) {
return result;
}
// or, something for which "as-property" won't work, changed into "wrapper-array" type:
if (p.getCurrentToken() == JsonToken.START_ARRAY) {
return super.deserializeTypedFromAny(p, ctxt);
}
ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,
"missing property '"+_typePropertyName+"' that is to contain type id (for class "+baseTypeName()+")");
return null;
}
protected Object _deserializeTypedUsingDefaultImpl(JsonParser p, DeserializationContext ctxt,
TokenBuffer tb) throws IOException
{
// As per [JACKSON-614], may have default implementation to use
JsonDeserializer<Object> deser = _findDefaultImplDeserializer(ctxt);
if (deser != null) {
if (tb != null) {
tb.writeEndObject();
p = tb.asParser(p);
// must move to point to the first token:
p.nextToken();
}
return deser.deserialize(p, ctxt);
}
// or, perhaps we just bumped into a "natural" value (boolean/int/double/String)?
Object result = TypeDeserializer.deserializeIfNatural(p, ctxt, _baseType);
if (result != null) {
return result;
}
// or, something for which "as-property" won't work, changed into "wrapper-array" type:
if (p.getCurrentToken() == JsonToken.START_ARRAY) {
return super.deserializeTypedFromAny(p, ctxt);
} else if (p.getCurrentToken() == JsonToken.VALUE_STRING) {
if (ctxt.isEnabled(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)) {
String str = p.getText().trim();
if (str.isEmpty()) {
return null;
}
}
}
ctxt.reportWrongTokenException(p, JsonToken.FIELD_NAME,
"missing property '"+_typePropertyName+"' that is to contain type id (for class "+baseTypeName()+")");
return null;
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/AsPropertyTypeDeserializer.java |
JacksonDatabind-76 | protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,
DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p, ctxt);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
if (buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt))) {
t = p.nextToken();
Object bean;
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
continue;
}
while (t == JsonToken.FIELD_NAME) {
p.nextToken();
tokens.copyCurrentStructure(p);
t = p.nextToken();
}
tokens.writeEndObject();
if (bean.getClass() != _beanType.getRawClass()) {
ctxt.reportMappingException("Can not create polymorphic instances with unwrapped values");
return null;
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
continue;
}
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
tokens.writeFieldName(propName);
tokens.copyCurrentStructure(p);
// "any property"?
if (_anySetter != null) {
buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
}
}
// We hit END_OBJECT, so:
Object bean;
// !!! 15-Feb-2012, tatu: Need to modify creator to use Builder!
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
return wrapInstantiationProblem(e, ctxt);
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
}
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser p,
DeserializationContext ctxt)
throws IOException, JsonProcessingException
{
final PropertyBasedCreator creator = _propertyBasedCreator;
PropertyValueBuffer buffer = creator.startBuilding(p, ctxt, _objectIdReader);
TokenBuffer tokens = new TokenBuffer(p, ctxt);
tokens.writeStartObject();
JsonToken t = p.getCurrentToken();
for (; t == JsonToken.FIELD_NAME; t = p.nextToken()) {
String propName = p.getCurrentName();
p.nextToken(); // to point to value
// creator property?
SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
if (creatorProp != null) {
buffer.assignParameter(creatorProp, creatorProp.deserialize(p, ctxt));
continue;
}
// Object Id property?
if (buffer.readIdProperty(propName)) {
continue;
}
// regular property? needs buffering
SettableBeanProperty prop = _beanProperties.find(propName);
if (prop != null) {
buffer.bufferProperty(prop, prop.deserialize(p, ctxt));
continue;
}
if (_ignorableProps != null && _ignorableProps.contains(propName)) {
handleIgnoredProperty(p, ctxt, handledType(), propName);
continue;
}
tokens.writeFieldName(propName);
tokens.copyCurrentStructure(p);
// "any property"?
if (_anySetter != null) {
buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(p, ctxt));
}
}
// We hit END_OBJECT, so:
Object bean;
// !!! 15-Feb-2012, tatu: Need to modify creator to use Builder!
try {
bean = creator.build(ctxt, buffer);
} catch (Exception e) {
return wrapInstantiationProblem(e, ctxt);
}
return _unwrappedPropertyHandler.processUnwrapped(p, ctxt, bean, tokens);
} | src/main/java/com/fasterxml/jackson/databind/deser/BuilderBasedDeserializer.java |
JacksonDatabind-8 | protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)
{
final int mask = (1 << typeIndex);
_hasNonDefaultCreator = true;
AnnotatedWithParams oldOne = _creators[typeIndex];
// already had an explicitly marked one?
if (oldOne != null) {
if ((_explicitCreators & mask) != 0) { // already had explicitly annotated, leave as-is
// but skip, if new one not annotated
if (!explicit) {
return;
}
// both explicit: verify
// otherwise only verify if neither explicitly annotated.
}
// one more thing: ok to override in sub-class
if (oldOne.getClass() == newOne.getClass()) {
// [databind#667]: avoid one particular class of bogus problems
throw new IllegalArgumentException("Conflicting "+TYPE_DESCS[typeIndex]
+" creators: already had explicitly marked "+oldOne+", encountered "+newOne);
// otherwise, which one to choose?
// new type more generic, use old
// new type more specific, use it
}
}
if (explicit) {
_explicitCreators |= mask;
}
_creators[typeIndex] = _fixAccess(newOne);
}
protected void verifyNonDup(AnnotatedWithParams newOne, int typeIndex, boolean explicit)
{
final int mask = (1 << typeIndex);
_hasNonDefaultCreator = true;
AnnotatedWithParams oldOne = _creators[typeIndex];
// already had an explicitly marked one?
if (oldOne != null) {
boolean verify;
if ((_explicitCreators & mask) != 0) { // already had explicitly annotated, leave as-is
// but skip, if new one not annotated
if (!explicit) {
return;
}
// both explicit: verify
verify = true;
} else {
// otherwise only verify if neither explicitly annotated.
verify = !explicit;
}
// one more thing: ok to override in sub-class
if (verify && (oldOne.getClass() == newOne.getClass())) {
// [databind#667]: avoid one particular class of bogus problems
Class<?> oldType = oldOne.getRawParameterType(0);
Class<?> newType = newOne.getRawParameterType(0);
if (oldType == newType) {
throw new IllegalArgumentException("Conflicting "+TYPE_DESCS[typeIndex]
+" creators: already had explicitly marked "+oldOne+", encountered "+newOne);
}
// otherwise, which one to choose?
if (newType.isAssignableFrom(oldType)) {
// new type more generic, use old
return;
}
// new type more specific, use it
}
}
if (explicit) {
_explicitCreators |= mask;
}
_creators[typeIndex] = _fixAccess(newOne);
} | src/main/java/com/fasterxml/jackson/databind/deser/impl/CreatorCollector.java |
JacksonDatabind-82 | protected void addBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
final boolean isConcrete = !beanDesc.getType().isAbstract();
final SettableBeanProperty[] creatorProps = isConcrete
? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
: null;
final boolean hasCreatorProps = (creatorProps != null);
// 01-May-2016, tatu: Which base type to use here gets tricky, since
// it may often make most sense to use general type for overrides,
// but what we have here may be more specific impl type. But for now
// just use it as is.
JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
.getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
beanDesc.getClassInfo());
Set<String> ignored;
if (ignorals != null) {
boolean ignoreAny = ignorals.getIgnoreUnknown();
builder.setIgnoreUnknownProperties(ignoreAny);
// Or explicit/implicit definitions?
ignored = ignorals.getIgnored();
for (String propName : ignored) {
builder.addIgnorable(propName);
}
} else {
ignored = Collections.emptySet();
}
// Also, do we have a fallback "any" setter?
AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();
AnnotatedMember anySetterField = null;
if (anySetterMethod != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));
}
else {
anySetterField = beanDesc.findAnySetterField();
if(anySetterField != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));
}
}
// NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter
// Implicit ones via @JsonIgnore and equivalent?
if (anySetterMethod == null && anySetterField == null) {
Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
if (ignored2 != null) {
for (String propName : ignored2) {
// allow ignoral of similarly named JSON property, but do not force;
// latter means NOT adding this to 'ignored':
builder.addIgnorable(propName);
}
}
}
final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
&& ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);
// Ok: let's then filter out property definitions
List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
beanDesc, builder, beanDesc.findProperties(), ignored);
// After which we can let custom code change the set
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
}
}
// At which point we still have all kinds of properties; not all with mutators:
for (BeanPropertyDefinition propDef : propDefs) {
SettableBeanProperty prop = null;
/* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,
* we need to do linkage (as per [databind#318]), and so need to start with
* other types, and only then create constructor parameter, if any.
*/
if (propDef.hasSetter()) {
JavaType propertyType = propDef.getSetter().getParameterType(0);
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (propDef.hasField()) {
JavaType propertyType = propDef.getField().getType();
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (useGettersAsSetters && propDef.hasGetter()) {
/* May also need to consider getters
* for Map/Collection properties; but with lowest precedence
*/
AnnotatedMethod getter = propDef.getGetter();
// should only consider Collections and Maps, for now?
Class<?> rawPropertyType = getter.getRawType();
if (Collection.class.isAssignableFrom(rawPropertyType)
|| Map.class.isAssignableFrom(rawPropertyType)) {
prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
}
}
// 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types
// (since they are never used anyway)
if (hasCreatorProps && propDef.hasConstructorParameter()) {
/* If property is passed via constructor parameter, we must
* handle things in special way. Not sure what is the most optimal way...
* for now, let's just call a (new) method in builder, which does nothing.
*/
// but let's call a method just to allow custom builders to be aware...
final String name = propDef.getName();
CreatorProperty cprop = null;
if (creatorProps != null) {
for (SettableBeanProperty cp : creatorProps) {
if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
cprop = (CreatorProperty) cp;
break;
}
}
}
if (cprop == null) {
List<String> n = new ArrayList<>();
for (SettableBeanProperty cp : creatorProps) {
n.add(cp.getName());
}
ctxt.reportBadPropertyDefinition(beanDesc, propDef,
"Could not find creator property with name '%s' (known Creator properties: %s)",
name, n);
continue;
}
if (prop != null) {
cprop.setFallbackSetter(prop);
}
prop = cprop;
builder.addCreatorProperty(cprop);
continue;
}
if (prop != null) {
Class<?>[] views = propDef.findViews();
if (views == null) {
// one more twist: if default inclusion disabled, need to force empty set of views
if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
views = NO_VIEWS;
}
}
// one more thing before adding to builder: copy any metadata
prop.setViews(views);
builder.addProperty(prop);
}
}
}
protected void addBeanProps(DeserializationContext ctxt,
BeanDescription beanDesc, BeanDeserializerBuilder builder)
throws JsonMappingException
{
final boolean isConcrete = !beanDesc.getType().isAbstract();
final SettableBeanProperty[] creatorProps = isConcrete
? builder.getValueInstantiator().getFromObjectArguments(ctxt.getConfig())
: null;
final boolean hasCreatorProps = (creatorProps != null);
// 01-May-2016, tatu: Which base type to use here gets tricky, since
// it may often make most sense to use general type for overrides,
// but what we have here may be more specific impl type. But for now
// just use it as is.
JsonIgnoreProperties.Value ignorals = ctxt.getConfig()
.getDefaultPropertyIgnorals(beanDesc.getBeanClass(),
beanDesc.getClassInfo());
Set<String> ignored;
if (ignorals != null) {
boolean ignoreAny = ignorals.getIgnoreUnknown();
builder.setIgnoreUnknownProperties(ignoreAny);
// Or explicit/implicit definitions?
ignored = ignorals.findIgnoredForDeserialization();
for (String propName : ignored) {
builder.addIgnorable(propName);
}
} else {
ignored = Collections.emptySet();
}
// Also, do we have a fallback "any" setter?
AnnotatedMethod anySetterMethod = beanDesc.findAnySetter();
AnnotatedMember anySetterField = null;
if (anySetterMethod != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterMethod));
}
else {
anySetterField = beanDesc.findAnySetterField();
if(anySetterField != null) {
builder.setAnySetter(constructAnySetter(ctxt, beanDesc, anySetterField));
}
}
// NOTE: we do NOT add @JsonIgnore'd properties into blocked ones if there's any-setter
// Implicit ones via @JsonIgnore and equivalent?
if (anySetterMethod == null && anySetterField == null) {
Collection<String> ignored2 = beanDesc.getIgnoredPropertyNames();
if (ignored2 != null) {
for (String propName : ignored2) {
// allow ignoral of similarly named JSON property, but do not force;
// latter means NOT adding this to 'ignored':
builder.addIgnorable(propName);
}
}
}
final boolean useGettersAsSetters = ctxt.isEnabled(MapperFeature.USE_GETTERS_AS_SETTERS)
&& ctxt.isEnabled(MapperFeature.AUTO_DETECT_GETTERS);
// Ok: let's then filter out property definitions
List<BeanPropertyDefinition> propDefs = filterBeanProps(ctxt,
beanDesc, builder, beanDesc.findProperties(), ignored);
// After which we can let custom code change the set
if (_factoryConfig.hasDeserializerModifiers()) {
for (BeanDeserializerModifier mod : _factoryConfig.deserializerModifiers()) {
propDefs = mod.updateProperties(ctxt.getConfig(), beanDesc, propDefs);
}
}
// At which point we still have all kinds of properties; not all with mutators:
for (BeanPropertyDefinition propDef : propDefs) {
SettableBeanProperty prop = null;
/* 18-Oct-2013, tatu: Although constructor parameters have highest precedence,
* we need to do linkage (as per [databind#318]), and so need to start with
* other types, and only then create constructor parameter, if any.
*/
if (propDef.hasSetter()) {
JavaType propertyType = propDef.getSetter().getParameterType(0);
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (propDef.hasField()) {
JavaType propertyType = propDef.getField().getType();
prop = constructSettableProperty(ctxt, beanDesc, propDef, propertyType);
} else if (useGettersAsSetters && propDef.hasGetter()) {
/* May also need to consider getters
* for Map/Collection properties; but with lowest precedence
*/
AnnotatedMethod getter = propDef.getGetter();
// should only consider Collections and Maps, for now?
Class<?> rawPropertyType = getter.getRawType();
if (Collection.class.isAssignableFrom(rawPropertyType)
|| Map.class.isAssignableFrom(rawPropertyType)) {
prop = constructSetterlessProperty(ctxt, beanDesc, propDef);
}
}
// 25-Sep-2014, tatu: No point in finding constructor parameters for abstract types
// (since they are never used anyway)
if (hasCreatorProps && propDef.hasConstructorParameter()) {
/* If property is passed via constructor parameter, we must
* handle things in special way. Not sure what is the most optimal way...
* for now, let's just call a (new) method in builder, which does nothing.
*/
// but let's call a method just to allow custom builders to be aware...
final String name = propDef.getName();
CreatorProperty cprop = null;
if (creatorProps != null) {
for (SettableBeanProperty cp : creatorProps) {
if (name.equals(cp.getName()) && (cp instanceof CreatorProperty)) {
cprop = (CreatorProperty) cp;
break;
}
}
}
if (cprop == null) {
List<String> n = new ArrayList<>();
for (SettableBeanProperty cp : creatorProps) {
n.add(cp.getName());
}
ctxt.reportBadPropertyDefinition(beanDesc, propDef,
"Could not find creator property with name '%s' (known Creator properties: %s)",
name, n);
continue;
}
if (prop != null) {
cprop.setFallbackSetter(prop);
}
prop = cprop;
builder.addCreatorProperty(cprop);
continue;
}
if (prop != null) {
Class<?>[] views = propDef.findViews();
if (views == null) {
// one more twist: if default inclusion disabled, need to force empty set of views
if (!ctxt.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
views = NO_VIEWS;
}
}
// one more thing before adding to builder: copy any metadata
prop.setViews(views);
builder.addProperty(prop);
}
}
} | src/main/java/com/fasterxml/jackson/databind/deser/BeanDeserializerFactory.java |
JacksonDatabind-83 | public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
String text = p.getValueAsString();
if (text != null) { // has String representation
if (text.length() == 0 || (text = text.trim()).length() == 0) {
// 04-Feb-2013, tatu: Usually should become null; but not always
return _deserializeFromEmptyString();
}
Exception cause = null;
try {
// 19-May-2017, tatu: Used to require non-null result (assuming `null`
// indicated error; but that seems wrong. Should be able to return
// `null` as value.
if (_deserialize(text, ctxt) != null) {
return _deserialize(text, ctxt);
}
} catch (IllegalArgumentException iae) {
cause = iae;
} catch (MalformedURLException me) {
cause = me;
}
String msg = "not a valid textual representation";
if (cause != null) {
String m2 = cause.getMessage();
if (m2 != null) {
msg = msg + ", problem: "+m2;
}
}
// 05-May-2016, tatu: Unlike most usage, this seems legit, so...
JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);
if (cause != null) {
e.initCause(cause);
}
throw e;
// nothing to do here, yet? We'll fail anyway
}
JsonToken t = p.getCurrentToken();
// [databind#381]
if (t == JsonToken.START_ARRAY) {
return _deserializeFromArray(p, ctxt);
}
if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
// Trivial cases; null to null, instance of type itself returned as is
Object ob = p.getEmbeddedObject();
if (ob == null) {
return null;
}
if (_valueClass.isAssignableFrom(ob.getClass())) {
return (T) ob;
}
return _deserializeEmbedded(ob, ctxt);
}
return (T) ctxt.handleUnexpectedToken(_valueClass, p);
}
public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
// 22-Sep-2012, tatu: For 2.1, use this new method, may force coercion:
String text = p.getValueAsString();
if (text != null) { // has String representation
if (text.length() == 0 || (text = text.trim()).length() == 0) {
// 04-Feb-2013, tatu: Usually should become null; but not always
return _deserializeFromEmptyString();
}
Exception cause = null;
try {
// 19-May-2017, tatu: Used to require non-null result (assuming `null`
// indicated error; but that seems wrong. Should be able to return
// `null` as value.
return _deserialize(text, ctxt);
} catch (IllegalArgumentException iae) {
cause = iae;
} catch (MalformedURLException me) {
cause = me;
}
String msg = "not a valid textual representation";
if (cause != null) {
String m2 = cause.getMessage();
if (m2 != null) {
msg = msg + ", problem: "+m2;
}
}
// 05-May-2016, tatu: Unlike most usage, this seems legit, so...
JsonMappingException e = ctxt.weirdStringException(text, _valueClass, msg);
if (cause != null) {
e.initCause(cause);
}
throw e;
// nothing to do here, yet? We'll fail anyway
}
JsonToken t = p.getCurrentToken();
// [databind#381]
if (t == JsonToken.START_ARRAY) {
return _deserializeFromArray(p, ctxt);
}
if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
// Trivial cases; null to null, instance of type itself returned as is
Object ob = p.getEmbeddedObject();
if (ob == null) {
return null;
}
if (_valueClass.isAssignableFrom(ob.getClass())) {
return (T) ob;
}
return _deserializeEmbedded(ob, ctxt);
}
return (T) ctxt.handleUnexpectedToken(_valueClass, p);
} | src/main/java/com/fasterxml/jackson/databind/deser/std/FromStringDeserializer.java |
JacksonDatabind-85 | public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property == null) {
return this;
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format == null) {
return this;
}
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
// 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
// First: custom pattern will override things
if ((shape == JsonFormat.Shape.STRING) || format.hasPattern()
|| format.hasLocale() || format.hasTimeZone()) {
TimeZone tz = format.getTimeZone();
final String pattern = format.hasPattern()
? format.getPattern()
: StdDateFormat.DATE_FORMAT_STR_ISO8601;
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(pattern, loc);
if (tz == null) {
tz = serializers.getTimeZone();
}
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
// Otherwise, need one of these changes:
// Jackson's own `StdDateFormat` is quite easy to deal with...
// 08-Jun-2017, tatu: Unfortunately there's no generally usable
// mechanism for changing `DateFormat` instances (or even clone()ing)
// So: require it be `SimpleDateFormat`; can't config other types
// serializers.reportBadDefinition(handledType(), String.format(
// Ugh. No way to change `Locale`, create copy; must re-crete completely:
return this;
}
public JsonSerializer<?> createContextual(SerializerProvider serializers,
BeanProperty property) throws JsonMappingException
{
if (property == null) {
return this;
}
JsonFormat.Value format = findFormatOverrides(serializers, property, handledType());
if (format == null) {
return this;
}
// Simple case first: serialize as numeric timestamp?
JsonFormat.Shape shape = format.getShape();
if (shape.isNumeric()) {
return withFormat(Boolean.TRUE, null);
}
// 08-Jun-2017, tatu: With [databind#1648], this gets bit tricky..
// First: custom pattern will override things
if (format.hasPattern()) {
final Locale loc = format.hasLocale()
? format.getLocale()
: serializers.getLocale();
SimpleDateFormat df = new SimpleDateFormat(format.getPattern(), loc);
TimeZone tz = format.hasTimeZone() ? format.getTimeZone()
: serializers.getTimeZone();
df.setTimeZone(tz);
return withFormat(Boolean.FALSE, df);
}
// Otherwise, need one of these changes:
final boolean hasLocale = format.hasLocale();
final boolean hasTZ = format.hasTimeZone();
final boolean asString = (shape == JsonFormat.Shape.STRING);
if (!hasLocale && !hasTZ && !asString) {
return this;
}
DateFormat df0 = serializers.getConfig().getDateFormat();
// Jackson's own `StdDateFormat` is quite easy to deal with...
if (df0 instanceof StdDateFormat) {
StdDateFormat std = (StdDateFormat) df0;
if (format.hasLocale()) {
std = std.withLocale(format.getLocale());
}
if (format.hasTimeZone()) {
std = std.withTimeZone(format.getTimeZone());
}
return withFormat(Boolean.FALSE, std);
}
// 08-Jun-2017, tatu: Unfortunately there's no generally usable
// mechanism for changing `DateFormat` instances (or even clone()ing)
// So: require it be `SimpleDateFormat`; can't config other types
if (!(df0 instanceof SimpleDateFormat)) {
// serializers.reportBadDefinition(handledType(), String.format(
serializers.reportMappingProblem(
"Configured `DateFormat` (%s) not a `SimpleDateFormat`; can not configure `Locale` or `TimeZone`",
df0.getClass().getName());
}
SimpleDateFormat df = (SimpleDateFormat) df0;
if (hasLocale) {
// Ugh. No way to change `Locale`, create copy; must re-crete completely:
df = new SimpleDateFormat(df.toPattern(), format.getLocale());
} else {
df = (SimpleDateFormat) df.clone();
}
TimeZone newTz = format.getTimeZone();
boolean changeTZ = (newTz != null) && !newTz.equals(df.getTimeZone());
if (changeTZ) {
df.setTimeZone(newTz);
}
return withFormat(Boolean.FALSE, df);
} | src/main/java/com/fasterxml/jackson/databind/ser/std/DateTimeSerializerBase.java |
JacksonDatabind-88 | protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException
{
/* 30-Jan-2010, tatu: Most ids are basic class names; so let's first
* check if any generics info is added; and only then ask factory
* to do translation when necessary
*/
TypeFactory tf = ctxt.getTypeFactory();
if (id.indexOf('<') > 0) {
// note: may want to try combining with specialization (esp for EnumMap)?
// 17-Aug-2017, tatu: As per [databind#1735] need to ensure assignment
// compatibility -- needed later anyway, and not doing so may open
// security issues.
JavaType t = tf.constructFromCanonical(id);
// Probably cleaner to have a method in `TypeFactory` but can't add in patch
return t;
}
Class<?> cls;
try {
cls = tf.findClass(id);
} catch (ClassNotFoundException e) {
// 24-May-2016, tatu: Ok, this is pretty ugly, but we should always get
// DeserializationContext, just playing it safe
if (ctxt instanceof DeserializationContext) {
DeserializationContext dctxt = (DeserializationContext) ctxt;
// First: we may have problem handlers that can deal with it?
return dctxt.handleUnknownTypeId(_baseType, id, this, "no such class found");
}
// ... meaning that we really should never get here.
return null;
} catch (Exception e) {
throw new IllegalArgumentException("Invalid type id '"+id+"' (for id type 'Id.class'): "+e.getMessage(), e);
}
return tf.constructSpecializedType(_baseType, cls);
}
protected JavaType _typeFromId(String id, DatabindContext ctxt) throws IOException
{
/* 30-Jan-2010, tatu: Most ids are basic class names; so let's first
* check if any generics info is added; and only then ask factory
* to do translation when necessary
*/
TypeFactory tf = ctxt.getTypeFactory();
if (id.indexOf('<') > 0) {
// note: may want to try combining with specialization (esp for EnumMap)?
// 17-Aug-2017, tatu: As per [databind#1735] need to ensure assignment
// compatibility -- needed later anyway, and not doing so may open
// security issues.
JavaType t = tf.constructFromCanonical(id);
if (!t.isTypeOrSubTypeOf(_baseType.getRawClass())) {
// Probably cleaner to have a method in `TypeFactory` but can't add in patch
throw new IllegalArgumentException(String.format(
"Class %s not subtype of %s", t.getRawClass().getName(), _baseType));
}
return t;
}
Class<?> cls;
try {
cls = tf.findClass(id);
} catch (ClassNotFoundException e) {
// 24-May-2016, tatu: Ok, this is pretty ugly, but we should always get
// DeserializationContext, just playing it safe
if (ctxt instanceof DeserializationContext) {
DeserializationContext dctxt = (DeserializationContext) ctxt;
// First: we may have problem handlers that can deal with it?
return dctxt.handleUnknownTypeId(_baseType, id, this, "no such class found");
}
// ... meaning that we really should never get here.
return null;
} catch (Exception e) {
throw new IllegalArgumentException("Invalid type id '"+id+"' (for id type 'Id.class'): "+e.getMessage(), e);
}
return tf.constructSpecializedType(_baseType, cls);
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/ClassNameIdResolver.java |
JacksonDatabind-9 | public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
String str;
if (value instanceof Date) {
provider.defaultSerializeDateKey((Date) value, jgen);
return;
} else {
str = value.toString();
}
jgen.writeFieldName(str);
}
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
String str;
Class<?> cls = value.getClass();
if (cls == String.class) {
str = (String) value;
} else if (Date.class.isAssignableFrom(cls)) {
provider.defaultSerializeDateKey((Date) value, jgen);
return;
} else if (cls == Class.class) {
str = ((Class<?>) value).getName();
} else {
str = value.toString();
}
jgen.writeFieldName(str);
} | src/main/java/com/fasterxml/jackson/databind/ser/std/StdKeySerializer.java |
JacksonDatabind-91 | private boolean _hasCustomHandlers(JavaType t) {
if (t.isContainerType()) {
// First: value types may have both value and type handlers
JavaType ct = t.getContentType();
if (ct != null) {
return (ct.getValueHandler() != null) || (ct.getTypeHandler() != null);
// Second: map(-like) types may have value handler for key (but not type; keys are untyped)
}
}
return false;
}
private boolean _hasCustomHandlers(JavaType t) {
if (t.isContainerType()) {
// First: value types may have both value and type handlers
JavaType ct = t.getContentType();
if (ct != null) {
if ((ct.getValueHandler() != null) || (ct.getTypeHandler() != null)) {
return true;
}
}
// Second: map(-like) types may have value handler for key (but not type; keys are untyped)
if (t.isMapLikeType()) {
JavaType kt = t.getKeyType();
if (kt.getValueHandler() != null) {
return true;
}
}
}
return false;
} | src/main/java/com/fasterxml/jackson/databind/deser/DeserializerCache.java |
JacksonDatabind-93 | public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (full.startsWith(PREFIX_STRING)) {
for (Class<?> cls = raw; cls != Object.class; cls = cls.getSuperclass()) {
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (!raw.isInterface() && full.startsWith(PREFIX_STRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()) {
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
} | src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java |
JacksonDatabind-96 | protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
// Looks like there's bit of magic regarding 1-parameter creators; others simpler:
if (1 != candidate.paramCount()) {
// Ok: for delegates, we want one and exactly one parameter without
// injection AND without name
int oneNotInjected = candidate.findOnlyParamWithoutInjection();
if (oneNotInjected >= 0) {
// getting close; but most not have name
if (candidate.paramName(oneNotInjected) == null) {
_addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
return;
}
}
_addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
return;
}
AnnotatedParameter param = candidate.parameter(0);
JacksonInject.Value injectId = candidate.injection(0);
PropertyName paramName = candidate.explicitParamName(0);
BeanPropertyDefinition paramDef = candidate.propertyDef(0);
// If there's injection or explicit name, should be properties-based
boolean useProps = (paramName != null) || (injectId != null);
if (!useProps && (paramDef != null)) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
// 25-May-2018, tatu: as per [databind#2051], looks like we have to get
// not implicit name, but name with possible strategy-based-rename
// paramName = candidate.findImplicitParamName(0);
paramName = candidate.findImplicitParamName(0);
useProps = (paramName != null) && paramDef.couldSerialize();
}
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[] {
constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
};
creators.addPropertyCreator(candidate.creator(), true, properties);
return;
}
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
}
protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
// Looks like there's bit of magic regarding 1-parameter creators; others simpler:
if (1 != candidate.paramCount()) {
// Ok: for delegates, we want one and exactly one parameter without
// injection AND without name
int oneNotInjected = candidate.findOnlyParamWithoutInjection();
if (oneNotInjected >= 0) {
// getting close; but most not have name
if (candidate.paramName(oneNotInjected) == null) {
_addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
return;
}
}
_addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
return;
}
AnnotatedParameter param = candidate.parameter(0);
JacksonInject.Value injectId = candidate.injection(0);
PropertyName paramName = candidate.explicitParamName(0);
BeanPropertyDefinition paramDef = candidate.propertyDef(0);
// If there's injection or explicit name, should be properties-based
boolean useProps = (paramName != null) || (injectId != null);
if (!useProps && (paramDef != null)) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
// 25-May-2018, tatu: as per [databind#2051], looks like we have to get
// not implicit name, but name with possible strategy-based-rename
// paramName = candidate.findImplicitParamName(0);
paramName = candidate.paramName(0);
useProps = (paramName != null) && paramDef.couldSerialize();
}
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[] {
constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
};
creators.addPropertyCreator(candidate.creator(), true, properties);
return;
}
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
} | src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java |
JacksonDatabind-97 | public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException
{
if (_value == null) {
ctxt.defaultSerializeNull(gen);
} else if (_value instanceof JsonSerializable) {
((JsonSerializable) _value).serialize(gen, ctxt);
} else {
// 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
// this to preserve contextual information
gen.writeObject(_value);
}
}
public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException
{
if (_value == null) {
ctxt.defaultSerializeNull(gen);
} else if (_value instanceof JsonSerializable) {
((JsonSerializable) _value).serialize(gen, ctxt);
} else {
// 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
// this to preserve contextual information
ctxt.defaultSerializeValue(_value, gen);
}
} | src/main/java/com/fasterxml/jackson/databind/node/POJONode.java |
JacksonDatabind-98 | public Object complete(JsonParser p, DeserializationContext ctxt,
PropertyValueBuffer buffer, PropertyBasedCreator creator)
throws IOException
{
// first things first: deserialize all data buffered:
final int len = _properties.length;
Object[] values = new Object[len];
for (int i = 0; i < len; ++i) {
String typeId = _typeIds[i];
final ExtTypedProperty extProp = _properties[i];
if (typeId == null) {
// let's allow missing both type and property (may already have been set, too)
if (_tokens[i] == null) {
continue;
}
// but not just one
// 26-Oct-2012, tatu: As per [databind#94], must allow use of 'defaultImpl'
if (!extProp.hasDefaultType()) {
ctxt.reportInputMismatch(_beanType,
"Missing external type id property '%s'",
extProp.getTypePropertyName());
} else {
typeId = extProp.getDefaultTypeId();
}
} else if (_tokens[i] == null) {
SettableBeanProperty prop = extProp.getProperty();
ctxt.reportInputMismatch(_beanType,
"Missing property '%s' for external type id '%s'",
prop.getName(), _properties[i].getTypePropertyName());
}
values[i] = _deserialize(p, ctxt, i, typeId);
final SettableBeanProperty prop = extProp.getProperty();
// also: if it's creator prop, fill in
if (prop.getCreatorIndex() >= 0) {
buffer.assignParameter(prop, values[i]);
// [databind#999] And maybe there's creator property for type id too?
SettableBeanProperty typeProp = extProp.getTypeProperty();
// for now, should only be needed for creator properties, too
if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {
// 31-May-2018, tatu: [databind#1328] if id is NOT plain `String`, need to
// apply deserializer... fun fun.
buffer.assignParameter(typeProp, typeId);
}
}
}
Object bean = creator.build(ctxt, buffer);
// third: assign non-creator properties
for (int i = 0; i < len; ++i) {
SettableBeanProperty prop = _properties[i].getProperty();
if (prop.getCreatorIndex() < 0) {
prop.set(bean, values[i]);
}
}
return bean;
}
public Object complete(JsonParser p, DeserializationContext ctxt,
PropertyValueBuffer buffer, PropertyBasedCreator creator)
throws IOException
{
// first things first: deserialize all data buffered:
final int len = _properties.length;
Object[] values = new Object[len];
for (int i = 0; i < len; ++i) {
String typeId = _typeIds[i];
final ExtTypedProperty extProp = _properties[i];
if (typeId == null) {
// let's allow missing both type and property (may already have been set, too)
if (_tokens[i] == null) {
continue;
}
// but not just one
// 26-Oct-2012, tatu: As per [databind#94], must allow use of 'defaultImpl'
if (!extProp.hasDefaultType()) {
ctxt.reportInputMismatch(_beanType,
"Missing external type id property '%s'",
extProp.getTypePropertyName());
} else {
typeId = extProp.getDefaultTypeId();
}
} else if (_tokens[i] == null) {
SettableBeanProperty prop = extProp.getProperty();
ctxt.reportInputMismatch(_beanType,
"Missing property '%s' for external type id '%s'",
prop.getName(), _properties[i].getTypePropertyName());
}
values[i] = _deserialize(p, ctxt, i, typeId);
final SettableBeanProperty prop = extProp.getProperty();
// also: if it's creator prop, fill in
if (prop.getCreatorIndex() >= 0) {
buffer.assignParameter(prop, values[i]);
// [databind#999] And maybe there's creator property for type id too?
SettableBeanProperty typeProp = extProp.getTypeProperty();
// for now, should only be needed for creator properties, too
if ((typeProp != null) && (typeProp.getCreatorIndex() >= 0)) {
// 31-May-2018, tatu: [databind#1328] if id is NOT plain `String`, need to
// apply deserializer... fun fun.
final Object v;
if (typeProp.getType().hasRawClass(String.class)) {
v = typeId;
} else {
TokenBuffer tb = new TokenBuffer(p, ctxt);
tb.writeString(typeId);
v = typeProp.getValueDeserializer().deserialize(tb.asParserOnFirstToken(), ctxt);
tb.close();
}
buffer.assignParameter(typeProp, v);
}
}
}
Object bean = creator.build(ctxt, buffer);
// third: assign non-creator properties
for (int i = 0; i < len; ++i) {
SettableBeanProperty prop = _properties[i].getProperty();
if (prop.getCreatorIndex() < 0) {
prop.set(bean, values[i]);
}
}
return bean;
} | src/main/java/com/fasterxml/jackson/databind/deser/impl/ExternalTypeHandler.java |
JacksonDatabind-99 | protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
return sb.toString();
}
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
sb.append('>');
return sb.toString();
} | src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java |
JacksonXml-1 | public JsonToken nextToken() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
switch (t) {
case START_OBJECT:
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
break;
case START_ARRAY:
_parsingContext = _parsingContext.createChildArrayContext(-1, -1);
break;
case END_OBJECT:
case END_ARRAY:
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case FIELD_NAME:
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
break;
default: // VALUE_STRING, VALUE_NULL
// should be fine as is?
}
return t;
}
int token = _xmlTokens.next();
// Need to have a loop just because we may have to eat/convert
// a start-element that indicates an array element.
while (token == XmlTokenStream.XML_START_ELEMENT) {
// If we thought we might get leaf, no such luck
if (_mayBeLeaf) {
// leave _mayBeLeaf set, as we start a new context
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
if (_parsingContext.inArray()) {
// Yup: in array, so this element could be verified; but it won't be
// reported anyway, and we need to process following event.
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
// Ok: virtual wrapping can be done by simply repeating current START_ELEMENT.
// Couple of ways to do it; but start by making _xmlTokens replay the thing...
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
// Ok: in array context we need to skip reporting field names.
// But what's the best way to find next token?
return (_currToken = JsonToken.FIELD_NAME);
}
// Ok; beyond start element, what do we get?
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
// Simple, except that if this is a leaf, need to suppress end:
if (_mayBeLeaf) {
_mayBeLeaf = false;
// 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
// expose as empty Object, not null
return (_currToken = JsonToken.VALUE_NULL);
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
// If there was a chance of leaf node, no more...
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currText = _xmlTokens.getText();
return (_currToken = JsonToken.VALUE_STRING);
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
/* One more refinement (pronunced like "hack") is that if
* we had an empty String (or all white space), and we are
* deserializing an array, we better hide the empty text.
*/
// Also: must skip following END_ELEMENT
_xmlTokens.skipEndElement();
if (_parsingContext.inArray()) {
if (_isEmpty(_currText)) {
// 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
// expose as empty Object, not null (or, worse, as used to
// be done, by swallowing the token)
_currToken = JsonToken.END_ARRAY;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
return (_currToken = JsonToken.VALUE_STRING);
} else {
// [dataformat-xml#177]: empty text may also need to be skipped
if (_parsingContext.inObject()
&& (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {
_currToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
// If not a leaf (or otherwise ignorable), need to transform into property...
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_END:
return (_currToken = null);
}
// should never get here
_throwInternal();
return null;
}
public JsonToken nextToken() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
switch (t) {
case START_OBJECT:
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
break;
case START_ARRAY:
_parsingContext = _parsingContext.createChildArrayContext(-1, -1);
break;
case END_OBJECT:
case END_ARRAY:
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case FIELD_NAME:
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
break;
default: // VALUE_STRING, VALUE_NULL
// should be fine as is?
}
return t;
}
int token = _xmlTokens.next();
// Need to have a loop just because we may have to eat/convert
// a start-element that indicates an array element.
while (token == XmlTokenStream.XML_START_ELEMENT) {
// If we thought we might get leaf, no such luck
if (_mayBeLeaf) {
// leave _mayBeLeaf set, as we start a new context
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
if (_parsingContext.inArray()) {
// Yup: in array, so this element could be verified; but it won't be
// reported anyway, and we need to process following event.
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
// Ok: virtual wrapping can be done by simply repeating current START_ELEMENT.
// Couple of ways to do it; but start by making _xmlTokens replay the thing...
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
// Ok: in array context we need to skip reporting field names.
// But what's the best way to find next token?
return (_currToken = JsonToken.FIELD_NAME);
}
// Ok; beyond start element, what do we get?
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
// Simple, except that if this is a leaf, need to suppress end:
if (_mayBeLeaf) {
_mayBeLeaf = false;
if (_parsingContext.inArray()) {
// 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
// expose as empty Object, not null
_nextToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
return (_currToken = JsonToken.VALUE_NULL);
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
// If there was a chance of leaf node, no more...
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currText = _xmlTokens.getText();
return (_currToken = JsonToken.VALUE_STRING);
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
/* One more refinement (pronunced like "hack") is that if
* we had an empty String (or all white space), and we are
* deserializing an array, we better hide the empty text.
*/
// Also: must skip following END_ELEMENT
_xmlTokens.skipEndElement();
if (_parsingContext.inArray()) {
if (_isEmpty(_currText)) {
// 06-Jan-2015, tatu: as per [dataformat-xml#180], need to
// expose as empty Object, not null (or, worse, as used to
// be done, by swallowing the token)
_nextToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
return (_currToken = JsonToken.START_OBJECT);
}
}
return (_currToken = JsonToken.VALUE_STRING);
} else {
// [dataformat-xml#177]: empty text may also need to be skipped
if (_parsingContext.inObject()
&& (_currToken != JsonToken.FIELD_NAME) && _isEmpty(_currText)) {
_currToken = JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
return _currToken;
}
}
// If not a leaf (or otherwise ignorable), need to transform into property...
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
return (_currToken = JsonToken.FIELD_NAME);
case XmlTokenStream.XML_END:
return (_currToken = null);
}
// should never get here
_throwInternal();
return null;
} | src/main/java/com/fasterxml/jackson/dataformat/xml/deser/FromXmlParser.java |
JacksonXml-3 | public String nextTextValue() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
// expected case; yes, got a String
if (t == JsonToken.VALUE_STRING) {
return _currText;
}
_updateState(t);
return null;
}
int token = _xmlTokens.next();
// mostly copied from 'nextToken()'
while (token == XmlTokenStream.XML_START_ELEMENT) {
if (_mayBeLeaf) {
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
_currToken = JsonToken.START_OBJECT;
return null;
}
if (_parsingContext.inArray()) {
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
_currToken = JsonToken.FIELD_NAME;
return null;
}
// Ok; beyond start element, what do we get?
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
if (_mayBeLeaf) {
// NOTE: this is different from nextToken() -- produce "", NOT null
_mayBeLeaf = false;
_currToken = JsonToken.VALUE_STRING;
return (_currText = "");
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
// If there was a chance of leaf node, no more...
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
_currToken = JsonToken.START_OBJECT;
} else {
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
_currToken = JsonToken.FIELD_NAME;
}
break;
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currText = _xmlTokens.getText();
_currToken = JsonToken.VALUE_STRING;
break;
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
// Also: must skip following END_ELEMENT
_xmlTokens.skipEndElement();
// NOTE: this is different from nextToken() -- NO work-around
// for otherwise empty List/array
_currToken = JsonToken.VALUE_STRING;
return _currText;
}
// If not a leaf, need to transform into property...
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
_currToken = JsonToken.FIELD_NAME;
break;
case XmlTokenStream.XML_END:
_currToken = null;
}
return null;
}
public String nextTextValue() throws IOException
{
_binaryValue = null;
if (_nextToken != null) {
JsonToken t = _nextToken;
_currToken = t;
_nextToken = null;
// expected case; yes, got a String
if (t == JsonToken.VALUE_STRING) {
return _currText;
}
_updateState(t);
return null;
}
int token = _xmlTokens.next();
// mostly copied from 'nextToken()'
while (token == XmlTokenStream.XML_START_ELEMENT) {
if (_mayBeLeaf) {
_nextToken = JsonToken.FIELD_NAME;
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
_currToken = JsonToken.START_OBJECT;
return null;
}
if (_parsingContext.inArray()) {
token = _xmlTokens.next();
_mayBeLeaf = true;
continue;
}
String name = _xmlTokens.getLocalName();
_parsingContext.setCurrentName(name);
if (_namesToWrap != null && _namesToWrap.contains(name)) {
_xmlTokens.repeatStartElement();
}
_mayBeLeaf = true;
_currToken = JsonToken.FIELD_NAME;
return null;
}
// Ok; beyond start element, what do we get?
switch (token) {
case XmlTokenStream.XML_END_ELEMENT:
if (_mayBeLeaf) {
// NOTE: this is different from nextToken() -- produce "", NOT null
_mayBeLeaf = false;
_currToken = JsonToken.VALUE_STRING;
return (_currText = "");
}
_currToken = _parsingContext.inArray() ? JsonToken.END_ARRAY : JsonToken.END_OBJECT;
_parsingContext = _parsingContext.getParent();
_namesToWrap = _parsingContext.getNamesToWrap();
break;
case XmlTokenStream.XML_ATTRIBUTE_NAME:
// If there was a chance of leaf node, no more...
if (_mayBeLeaf) {
_mayBeLeaf = false;
_nextToken = JsonToken.FIELD_NAME;
_currText = _xmlTokens.getText();
_parsingContext = _parsingContext.createChildObjectContext(-1, -1);
_currToken = JsonToken.START_OBJECT;
} else {
_parsingContext.setCurrentName(_xmlTokens.getLocalName());
_currToken = JsonToken.FIELD_NAME;
}
break;
case XmlTokenStream.XML_ATTRIBUTE_VALUE:
_currToken = JsonToken.VALUE_STRING;
return (_currText = _xmlTokens.getText());
case XmlTokenStream.XML_TEXT:
_currText = _xmlTokens.getText();
if (_mayBeLeaf) {
_mayBeLeaf = false;
// Also: must skip following END_ELEMENT
_xmlTokens.skipEndElement();
// NOTE: this is different from nextToken() -- NO work-around
// for otherwise empty List/array
_currToken = JsonToken.VALUE_STRING;
return _currText;
}
// If not a leaf, need to transform into property...
_parsingContext.setCurrentName(_cfgNameForTextElement);
_nextToken = JsonToken.VALUE_STRING;
_currToken = JsonToken.FIELD_NAME;
break;
case XmlTokenStream.XML_END:
_currToken = null;
}
return null;
} | src/main/java/com/fasterxml/jackson/dataformat/xml/deser/FromXmlParser.java |
JacksonXml-4 | protected void _serializeXmlNull(JsonGenerator jgen) throws IOException
{
// 14-Nov-2016, tatu: As per [dataformat-xml#213], we may have explicitly
// configured root name...
if (jgen instanceof ToXmlGenerator) {
_initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);
}
super.serializeValue(jgen, null);
}
protected void _serializeXmlNull(JsonGenerator jgen) throws IOException
{
// 14-Nov-2016, tatu: As per [dataformat-xml#213], we may have explicitly
// configured root name...
QName rootName = _rootNameFromConfig();
if (rootName == null) {
rootName = ROOT_NAME_FOR_NULL;
}
if (jgen instanceof ToXmlGenerator) {
_initWithRootName((ToXmlGenerator) jgen, rootName);
}
super.serializeValue(jgen, null);
} | src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java |
JacksonXml-5 | protected XmlSerializerProvider(XmlSerializerProvider src) {
super(src);
// 21-May-2018, tatu: As per [dataformat-xml#282], should NOT really copy
// root name lookup as that may link back to diff version, configuration
_rootNameLookup = src._rootNameLookup;
}
protected XmlSerializerProvider(XmlSerializerProvider src) {
super(src);
// 21-May-2018, tatu: As per [dataformat-xml#282], should NOT really copy
// root name lookup as that may link back to diff version, configuration
_rootNameLookup = new XmlRootNameLookup();
} | src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java |
Jsoup-1 | private void normalise(Element element) {
List<Node> toMove = new ArrayList<Node>();
for (Node node: element.childNodes) {
if (node instanceof TextNode) {
TextNode tn = (TextNode) node;
if (!tn.isBlank())
toMove.add(tn);
}
}
for (Node node: toMove) {
element.removeChild(node);
body().appendChild(new TextNode(" ", ""));
body().appendChild(node);
}
}
private void normalise(Element element) {
List<Node> toMove = new ArrayList<Node>();
for (Node node: element.childNodes) {
if (node instanceof TextNode) {
TextNode tn = (TextNode) node;
if (!tn.isBlank())
toMove.add(tn);
}
}
for (Node node: toMove) {
element.removeChild(node);
body().prependChild(node);
body().prependChild(new TextNode(" ", ""));
}
} | src/main/java/org/jsoup/nodes/Document.java |
Jsoup-10 | public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
String relUrl = attr(attributeKey);
if (!hasAttr(attributeKey)) {
return ""; // nothing to make absolute with
} else {
URL base;
try {
try {
base = new URL(baseUri);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute may be abs on its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
// workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
URL abs = new URL(base, relUrl);
return abs.toExternalForm();
} catch (MalformedURLException e) {
return "";
}
}
}
public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
String relUrl = attr(attributeKey);
if (!hasAttr(attributeKey)) {
return ""; // nothing to make absolute with
} else {
URL base;
try {
try {
base = new URL(baseUri);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute may be abs on its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
// workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
if (relUrl.startsWith("?"))
relUrl = base.getPath() + relUrl;
URL abs = new URL(base, relUrl);
return abs.toExternalForm();
} catch (MalformedURLException e) {
return "";
}
}
} | src/main/java/org/jsoup/nodes/Node.java |
Jsoup-13 | public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
return attributes.hasKey(attributeKey);
}
public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
if (attributeKey.toLowerCase().startsWith("abs:")) {
String key = attributeKey.substring("abs:".length());
if (attributes.hasKey(key) && !absUrl(key).equals(""))
return true;
}
return attributes.hasKey(attributeKey);
} | src/main/java/org/jsoup/nodes/Node.java |
Jsoup-15 | boolean process(Token t, TreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
Element form = tb.insert(startTag);
tb.setFormElement(form);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
// we're not supposed to ask.
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
TreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
// todo: refactor these lookups
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
for (int si = 0; si < stack.size(); si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avvoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
}
boolean process(Token t, TreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
Element form = tb.insert(startTag);
tb.setFormElement(form);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
// we're not supposed to ask.
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
TreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
// todo: refactor these lookups
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
for (int si = 0; si < stack.size(); si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(Tag.valueOf(name), tb.getBaseUri());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodes().size()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avvoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
} | src/main/java/org/jsoup/parser/TreeBuilderState.java |
Jsoup-19 | private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
String value = el.absUrl(attr.getKey());
if (!preserveRelativeLinks)
attr.setValue(value);
for (Protocol protocol : protocols) {
String prot = protocol.toString() + ":";
if (value.toLowerCase().startsWith(prot)) {
return true;
}
}
return false;
}
private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
String value = el.absUrl(attr.getKey());
if (value.length() == 0)
value = attr.getValue(); // if it could not be made abs, run as-is to allow custom unknown protocols
if (!preserveRelativeLinks)
attr.setValue(value);
for (Protocol protocol : protocols) {
String prot = protocol.toString() + ":";
if (value.toLowerCase().startsWith(prot)) {
return true;
}
}
return false;
} | src/main/java/org/jsoup/safety/Whitelist.java |
Jsoup-2 | private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (tagName.length() == 0) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
Element child = new Element(tag, baseUri, attributes);
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
addChildToParent(child, isEmptyElement);
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
Node dataNode;
if (tag.equals(titleTag) || tag.equals(textareaTag)) // want to show as text, but not contain inside tags (so not a data tag?)
dataNode = TextNode.createFromEncoded(data, baseUri);
else
dataNode = new DataNode(data, baseUri); // data not encoded but raw (for " in script)
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (href.length() != 0) { // ignore <base target> etc
baseUri = href;
doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
}
private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (tagName.length() == 0) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
Element child = new Element(tag, baseUri, attributes);
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
addChildToParent(child, isEmptyElement);
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
popStackToClose(tag);
Node dataNode;
if (tag.equals(titleTag) || tag.equals(textareaTag)) // want to show as text, but not contain inside tags (so not a data tag?)
dataNode = TextNode.createFromEncoded(data, baseUri);
else
dataNode = new DataNode(data, baseUri); // data not encoded but raw (for " in script)
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (href.length() != 0) { // ignore <base target> etc
baseUri = href;
doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
} | src/main/java/org/jsoup/parser/Parser.java |
Jsoup-20 | static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset");
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (doc == null) {
// there are times where there is a spurious byte-order-mark at the start of the text. Shouldn't be present
// in utf-8. If after decoding, there is a BOM, strip it; otherwise will cause the parser to go straight
// into head mode
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset");
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (doc == null) {
// there are times where there is a spurious byte-order-mark at the start of the text. Shouldn't be present
// in utf-8. If after decoding, there is a BOM, strip it; otherwise will cause the parser to go straight
// into head mode
if (docData.charAt(0) == 65279)
docData = docData.substring(1);
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
} | src/main/java/org/jsoup/helper/DataUtil.java |
Jsoup-24 | void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
r.advance();
return;
}
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
anythingElse(t, r);
break;
}
} else {
anythingElse(t, r);
}
}
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
anythingElse(t, r);
break;
}
} else {
anythingElse(t, r);
}
} | src/main/java/org/jsoup/parser/TokeniserState.java |
Jsoup-26 | public Document clean(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
copySafeNodes(dirtyDocument.body(), clean.body());
return clean;
}
public Document clean(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
if (dirtyDocument.body() != null) // frameset documents won't have a body. the clean doc will have empty body.
copySafeNodes(dirtyDocument.body(), clean.body());
return clean;
} | src/main/java/org/jsoup/safety/Cleaner.java |
Jsoup-27 | static String getCharsetFromContentType(String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
charset = charset.toUpperCase(Locale.ENGLISH);
return charset;
}
return null;
}
static String getCharsetFromContentType(String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
if (Charset.isSupported(charset)) return charset;
charset = charset.toUpperCase(Locale.ENGLISH);
if (Charset.isSupported(charset)) return charset;
}
return null;
} | src/main/java/org/jsoup/helper/DataUtil.java |
Jsoup-32 | public Element clone() {
Element clone = (Element) super.clone();
clone.classNames();
return clone;
}
public Element clone() {
Element clone = (Element) super.clone();
clone.classNames = null; // derived on first hit, otherwise gets a pointer to source classnames
return clone;
} | src/main/java/org/jsoup/nodes/Element.java |
Jsoup-33 | Element insert(Token.StartTag startTag) {
// handle empty unknown tags
// when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag.
if (startTag.isSelfClosing()) {
Element el = insertEmpty(startTag);
stack.add(el);
tokeniser.emit(new Token.EndTag(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing
return el;
}
Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);
insert(el);
return el;
}
Element insert(Token.StartTag startTag) {
// handle empty unknown tags
// when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag.
if (startTag.isSelfClosing()) {
Element el = insertEmpty(startTag);
stack.add(el);
tokeniser.transition(TokeniserState.Data); // handles <script />, otherwise needs breakout steps from script data
tokeniser.emit(new Token.EndTag(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing
return el;
}
Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);
insert(el);
return el;
} | src/main/java/org/jsoup/parser/HtmlTreeBuilder.java |
Jsoup-34 | int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]);
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]);
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length && last <= length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
} | src/main/java/org/jsoup/parser/CharacterReader.java |
Jsoup-35 | boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
// we're not supposed to ask.
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
// todo: refactor these lookups
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents
// run-aways
for (int si = 0; si < stack.size() && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
}
boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, "base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "title")) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), "h1", "h2", "h3", "h4", "h5", "h6")) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, "pre", "listing")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, "dd", "dt")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), "dd", "dt")) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), "address", "div", "p"))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name,
"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u")) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, "area", "br", "embed", "img", "keygen", "wbr")) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, "param", "source", "track")) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
// we're not supposed to ask.
startTag.name("img");
return tb.process(startTag);
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), "name", "action", "prompt"))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in("optgroup", "option")) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in("rp", "rt")) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name,
"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr")) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name,
"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul")) {
// todo: refactor these lookups
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "dd", "dt")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, "h1", "h2", "h3", "h4", "h5", "h6")) {
if (!tb.inScope(new String[]{"h1", "h2", "h3", "h4", "h5", "h6"})) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose("h1", "h2", "h3", "h4", "h5", "h6");
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name,
"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u")) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents
// run-aways
for (int si = 0; si < stack.size() && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), "table", "tbody", "tfoot", "thead", "tr")) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
adopter.attributes().addAll(formatEl.attributes());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, "applet", "marquee", "object")) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
} | src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java |
Jsoup-37 | public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return accum.toString().trim();
}
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString();
} | src/main/java/org/jsoup/nodes/Element.java |
Jsoup-38 | boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, Constants.InBodyStartToHead)) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name, Constants.InBodyStartPClosers)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.Headings)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.InBodyStartPreListing)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.DdDt)) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), Constants.DdDt)) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name, Constants.Formatters)) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, Constants.InBodyStartApplets)) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, Constants.InBodyStartMedia)) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in(name, Constants.InBodyStartOptions)) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.InBodyStartRuby)) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name, Constants.InBodyStartDrop)) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name, Constants.InBodyEndClosers)) {
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, Constants.DdDt)) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, Constants.Headings)) {
if (!tb.inScope(Constants.Headings)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(Constants.Headings);
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents
// run-aways
final int stackSize = stack.size();
for (int si = 0; si < stackSize && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
adopter.attributes().addAll(formatEl.attributes());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, Constants.InBodyStartApplets)) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
}
boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character: {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
// todo confirm that check
tb.error(this);
return false;
} else if (isWhitespace(c)) {
tb.reconstructFormattingElements();
tb.insert(c);
} else {
tb.reconstructFormattingElements();
tb.insert(c);
tb.framesetOk(false);
}
break;
}
case Comment: {
tb.insert(t.asComment());
break;
}
case Doctype: {
tb.error(this);
return false;
}
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.name();
if (name.equals("html")) {
tb.error(this);
// merge attributes onto real html
Element html = tb.getStack().getFirst();
for (Attribute attribute : startTag.getAttributes()) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
} else if (StringUtil.in(name, Constants.InBodyStartToHead)) {
return tb.process(t, InHead);
} else if (name.equals("body")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
for (Attribute attribute : startTag.getAttributes()) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
} else if (name.equals("frameset")) {
tb.error(this);
LinkedList<Element> stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) {
// only in fragment case
return false; // ignore
} else if (!tb.framesetOk()) {
return false; // ignore frameset
} else {
Element second = stack.get(1);
if (second.parent() != null)
second.remove();
// pop up to html element
while (stack.size() > 1)
stack.removeLast();
tb.insert(startTag);
tb.transition(InFrameset);
}
} else if (StringUtil.in(name, Constants.InBodyStartPClosers)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.Headings)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
if (StringUtil.in(tb.currentElement().nodeName(), Constants.Headings)) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.InBodyStartPreListing)) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
// todo: ignore LF if next token
tb.framesetOk(false);
} else if (name.equals("form")) {
if (tb.getFormElement() != null) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertForm(startTag, true);
} else if (name.equals("li")) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (el.nodeName().equals("li")) {
tb.process(new Token.EndTag("li"));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.DdDt)) {
tb.framesetOk(false);
LinkedList<Element> stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
Element el = stack.get(i);
if (StringUtil.in(el.nodeName(), Constants.DdDt)) {
tb.process(new Token.EndTag(el.nodeName()));
break;
}
if (tb.isSpecial(el) && !StringUtil.in(el.nodeName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
} else if (name.equals("plaintext")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
} else if (name.equals("button")) {
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.process(new Token.EndTag("button"));
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
} else if (name.equals("a")) {
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.process(new Token.EndTag("a"));
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
Element a = tb.insert(startTag);
tb.pushActiveFormattingElements(a);
} else if (StringUtil.in(name, Constants.Formatters)) {
tb.reconstructFormattingElements();
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (name.equals("nobr")) {
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.process(new Token.EndTag("nobr"));
tb.reconstructFormattingElements();
}
Element el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (StringUtil.in(name, Constants.InBodyStartApplets)) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (name.equals("table")) {
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
} else if (StringUtil.in(name, Constants.InBodyStartEmptyFormatters)) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("input")) {
tb.reconstructFormattingElements();
Element el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
} else if (StringUtil.in(name, Constants.InBodyStartMedia)) {
tb.insertEmpty(startTag);
} else if (name.equals("hr")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (name.equals("image")) {
if (tb.getFromStack("svg") == null)
return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg
else
tb.insert(startTag);
} else if (name.equals("isindex")) {
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.tokeniser.acknowledgeSelfClosingFlag();
tb.process(new Token.StartTag("form"));
if (startTag.attributes.hasKey("action")) {
Element form = tb.getFormElement();
form.attr("action", startTag.attributes.get("action"));
}
tb.process(new Token.StartTag("hr"));
tb.process(new Token.StartTag("label"));
// hope you like english.
String prompt = startTag.attributes.hasKey("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character(prompt));
// input
Attributes inputAttribs = new Attributes();
for (Attribute attr : startTag.attributes) {
if (!StringUtil.in(attr.getKey(), Constants.InBodyStartInputAttribs))
inputAttribs.put(attr);
}
inputAttribs.put("name", "isindex");
tb.process(new Token.StartTag("input", inputAttribs));
tb.process(new Token.EndTag("label"));
tb.process(new Token.StartTag("hr"));
tb.process(new Token.EndTag("form"));
} else if (name.equals("textarea")) {
tb.insert(startTag);
// todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
} else if (name.equals("xmp")) {
if (tb.inButtonScope("p")) {
tb.process(new Token.EndTag("p"));
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("iframe")) {
tb.framesetOk(false);
handleRawtext(startTag, tb);
} else if (name.equals("noembed")) {
// also handle noscript if script enabled
handleRawtext(startTag, tb);
} else if (name.equals("select")) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
HtmlTreeBuilderState state = tb.state();
if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell))
tb.transition(InSelectInTable);
else
tb.transition(InSelect);
} else if (StringUtil.in(name, Constants.InBodyStartOptions)) {
if (tb.currentElement().nodeName().equals("option"))
tb.process(new Token.EndTag("option"));
tb.reconstructFormattingElements();
tb.insert(startTag);
} else if (StringUtil.in(name, Constants.InBodyStartRuby)) {
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
} else if (name.equals("math")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (name.equals("svg")) {
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
tb.tokeniser.acknowledgeSelfClosingFlag();
} else if (StringUtil.in(name, Constants.InBodyStartDrop)) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.name();
if (name.equals("body")) {
if (!tb.inScope("body")) {
tb.error(this);
return false;
} else {
// todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html
tb.transition(AfterBody);
}
} else if (name.equals("html")) {
boolean notIgnored = tb.process(new Token.EndTag("body"));
if (notIgnored)
return tb.process(endTag);
} else if (StringUtil.in(name, Constants.InBodyEndClosers)) {
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("form")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
}
} else if (name.equals("p")) {
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.process(new Token.StartTag(name)); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (name.equals("li")) {
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, Constants.DdDt)) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (StringUtil.in(name, Constants.Headings)) {
if (!tb.inScope(Constants.Headings)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(Constants.Headings);
}
} else if (name.equals("sarcasm")) {
// *sigh*
return anyOtherEndTag(t, tb);
} else if (StringUtil.in(name, Constants.InBodyEndAdoptionFormatters)) {
// Adoption Agency Algorithm.
OUTER:
for (int i = 0; i < 8; i++) {
Element formatEl = tb.getActiveFormattingElement(name);
if (formatEl == null)
return anyOtherEndTag(t, tb);
else if (!tb.onStack(formatEl)) {
tb.error(this);
tb.removeFromActiveFormattingElements(formatEl);
return true;
} else if (!tb.inScope(formatEl.nodeName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
LinkedList<Element> stack = tb.getStack();
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents
// run-aways
final int stackSize = stack.size();
for (int si = 0; si < stackSize && si < 64; si++) {
Element el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.nodeName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
// todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list.
// does that mean: int pos of format el in list?
Element node = furthestBlock;
Element lastNode = furthestBlock;
INNER:
for (int j = 0; j < 3; j++) {
if (tb.onStack(node))
node = tb.aboveOnStack(node);
if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check
tb.removeFromStack(node);
continue INNER;
} else if (node == formatEl)
break INNER;
Element replacement = new Element(Tag.valueOf(node.nodeName()), tb.getBaseUri());
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.
// not getting how this bookmark both straddles the element above, but is inbetween here...
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (StringUtil.in(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) {
if (lastNode.parent() != null)
lastNode.remove();
tb.insertInFosterParent(lastNode);
} else {
if (lastNode.parent() != null)
lastNode.remove();
commonAncestor.appendChild(lastNode);
}
Element adopter = new Element(formatEl.tag(), tb.getBaseUri());
adopter.attributes().addAll(formatEl.attributes());
Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]);
for (Node childNode : childNodes) {
adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod.
}
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
} else if (StringUtil.in(name, Constants.InBodyStartApplets)) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElement().nodeName().equals(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else if (name.equals("br")) {
tb.error(this);
tb.process(new Token.StartTag("br"));
return false;
} else {
return anyOtherEndTag(t, tb);
}
break;
case EOF:
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
} | src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java |
Jsoup-39 | static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
} else {
foundCharset = meta.attr("charset");
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
// UTF-8 BOM indicator. takes precedence over everything else. rarely used. re-decodes incase above decoded incorrectly
if (docData.length() > 0 && docData.charAt(0) == 65279) {
byteData.rewind();
docData = Charset.forName(defaultCharset).decode(byteData).toString();
docData = docData.substring(1);
charsetName = defaultCharset;
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
} else {
foundCharset = meta.attr("charset");
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
// UTF-8 BOM indicator. takes precedence over everything else. rarely used. re-decodes incase above decoded incorrectly
if (docData.length() > 0 && docData.charAt(0) == 65279) {
byteData.rewind();
docData = Charset.forName(defaultCharset).decode(byteData).toString();
docData = docData.substring(1);
charsetName = defaultCharset;
doc = null;
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
} | src/main/java/org/jsoup/helper/DataUtil.java |
Jsoup-40 | public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
Validate.notEmpty(name);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
}
public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
} | src/main/java/org/jsoup/nodes/DocumentType.java |
Jsoup-41 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return this == o;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return tag.equals(element.tag);
} | src/main/java/org/jsoup/nodes/Element.java |
Jsoup-42 | public List<Connection.KeyVal> formData() {
ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>();
// iterate the form control elements and accumulate their values
for (Element el: elements) {
if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable
String name = el.attr("name");
if (name.length() == 0) continue;
String type = el.attr("type");
if ("select".equals(el.tagName())) {
Elements options = el.select("option[selected]");
boolean set = false;
for (Element option: options) {
data.add(HttpConnection.KeyVal.create(name, option.val()));
set = true;
}
if (!set) {
Element option = el.select("option").first();
if (option != null)
data.add(HttpConnection.KeyVal.create(name, option.val()));
}
} else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// only add checkbox or radio if they have the checked attribute
if (el.hasAttr("checked")) {
final String val = el.val();
data.add(HttpConnection.KeyVal.create(name, val));
}
} else {
data.add(HttpConnection.KeyVal.create(name, el.val()));
}
}
return data;
}
public List<Connection.KeyVal> formData() {
ArrayList<Connection.KeyVal> data = new ArrayList<Connection.KeyVal>();
// iterate the form control elements and accumulate their values
for (Element el: elements) {
if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable
if (el.hasAttr("disabled")) continue; // skip disabled form inputs
String name = el.attr("name");
if (name.length() == 0) continue;
String type = el.attr("type");
if ("select".equals(el.tagName())) {
Elements options = el.select("option[selected]");
boolean set = false;
for (Element option: options) {
data.add(HttpConnection.KeyVal.create(name, option.val()));
set = true;
}
if (!set) {
Element option = el.select("option").first();
if (option != null)
data.add(HttpConnection.KeyVal.create(name, option.val()));
}
} else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// only add checkbox or radio if they have the checked attribute
if (el.hasAttr("checked")) {
final String val = el.val().length() > 0 ? el.val() : "on";
data.add(HttpConnection.KeyVal.create(name, val));
}
} else {
data.add(HttpConnection.KeyVal.create(name, el.val()));
}
}
return data;
} | src/main/java/org/jsoup/nodes/FormElement.java |
Jsoup-43 | private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element.equals(search))
return i;
}
return null;
}
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element == search)
return i;
}
return null;
} | src/main/java/org/jsoup/nodes/Element.java |
Jsoup-45 | void resetInsertionMode() {
boolean last = false;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (pos == 0) {
last = true;
node = contextElement;
}
String name = node.nodeName();
if ("select".equals(name)) {
transition(HtmlTreeBuilderState.InSelect);
break; // frag
} else if (("td".equals(name) || "td".equals(name) && !last)) {
transition(HtmlTreeBuilderState.InCell);
break;
} else if ("tr".equals(name)) {
transition(HtmlTreeBuilderState.InRow);
break;
} else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) {
transition(HtmlTreeBuilderState.InTableBody);
break;
} else if ("caption".equals(name)) {
transition(HtmlTreeBuilderState.InCaption);
break;
} else if ("colgroup".equals(name)) {
transition(HtmlTreeBuilderState.InColumnGroup);
break; // frag
} else if ("table".equals(name)) {
transition(HtmlTreeBuilderState.InTable);
break;
} else if ("head".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
} else if ("body".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break;
} else if ("frameset".equals(name)) {
transition(HtmlTreeBuilderState.InFrameset);
break; // frag
} else if ("html".equals(name)) {
transition(HtmlTreeBuilderState.BeforeHead);
break; // frag
} else if (last) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
}
}
}
void resetInsertionMode() {
boolean last = false;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (pos == 0) {
last = true;
node = contextElement;
}
String name = node.nodeName();
if ("select".equals(name)) {
transition(HtmlTreeBuilderState.InSelect);
break; // frag
} else if (("td".equals(name) || "th".equals(name) && !last)) {
transition(HtmlTreeBuilderState.InCell);
break;
} else if ("tr".equals(name)) {
transition(HtmlTreeBuilderState.InRow);
break;
} else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) {
transition(HtmlTreeBuilderState.InTableBody);
break;
} else if ("caption".equals(name)) {
transition(HtmlTreeBuilderState.InCaption);
break;
} else if ("colgroup".equals(name)) {
transition(HtmlTreeBuilderState.InColumnGroup);
break; // frag
} else if ("table".equals(name)) {
transition(HtmlTreeBuilderState.InTable);
break;
} else if ("head".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
} else if ("body".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break;
} else if ("frameset".equals(name)) {
transition(HtmlTreeBuilderState.InFrameset);
break; // frag
} else if ("html".equals(name)) {
transition(HtmlTreeBuilderState.BeforeHead);
break; // frag
} else if (last) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
}
}
} | src/main/java/org/jsoup/parser/HtmlTreeBuilder.java |
Jsoup-46 | static void escape(StringBuilder accum, String string, Document.OutputSettings out,
boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {
boolean lastWasWhite = false;
boolean reachedNonWhite = false;
final EscapeMode escapeMode = out.escapeMode();
final CharsetEncoder encoder = out.encoder();
final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());
final Map<Character, String> map = escapeMode.getMap();
final int length = string.length();
int codePoint;
for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {
codePoint = string.codePointAt(offset);
if (normaliseWhite) {
if (StringUtil.isWhitespace(codePoint)) {
if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)
continue;
accum.append(' ');
lastWasWhite = true;
continue;
} else {
lastWasWhite = false;
reachedNonWhite = true;
}
}
// surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]):
if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
final char c = (char) codePoint;
// html specific and required escapes:
switch (c) {
case '&':
accum.append("&");
break;
case 0xA0:
if (escapeMode != EscapeMode.xhtml)
accum.append(" ");
else
accum.append(c);
break;
case '<':
if (!inAttribute)
accum.append("<");
else
accum.append(c);
break;
case '>':
if (!inAttribute)
accum.append(">");
else
accum.append(c);
break;
case '"':
if (inAttribute)
accum.append(""");
else
accum.append(c);
break;
default:
if (canEncode(coreCharset, c, encoder))
accum.append(c);
else if (map.containsKey(c))
accum.append('&').append(map.get(c)).append(';');
else
accum.append("&#x").append(Integer.toHexString(codePoint)).append(';');
}
} else {
final String c = new String(Character.toChars(codePoint));
if (encoder.canEncode(c)) // uses fallback encoder for simplicity
accum.append(c);
else
accum.append("&#x").append(Integer.toHexString(codePoint)).append(';');
}
}
}
static void escape(StringBuilder accum, String string, Document.OutputSettings out,
boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) {
boolean lastWasWhite = false;
boolean reachedNonWhite = false;
final EscapeMode escapeMode = out.escapeMode();
final CharsetEncoder encoder = out.encoder();
final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name());
final Map<Character, String> map = escapeMode.getMap();
final int length = string.length();
int codePoint;
for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) {
codePoint = string.codePointAt(offset);
if (normaliseWhite) {
if (StringUtil.isWhitespace(codePoint)) {
if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite)
continue;
accum.append(' ');
lastWasWhite = true;
continue;
} else {
lastWasWhite = false;
reachedNonWhite = true;
}
}
// surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]):
if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
final char c = (char) codePoint;
// html specific and required escapes:
switch (c) {
case '&':
accum.append("&");
break;
case 0xA0:
if (escapeMode != EscapeMode.xhtml)
accum.append(" ");
else
accum.append(" ");
break;
case '<':
if (!inAttribute)
accum.append("<");
else
accum.append(c);
break;
case '>':
if (!inAttribute)
accum.append(">");
else
accum.append(c);
break;
case '"':
if (inAttribute)
accum.append(""");
else
accum.append(c);
break;
default:
if (canEncode(coreCharset, c, encoder))
accum.append(c);
else if (map.containsKey(c))
accum.append('&').append(map.get(c)).append(';');
else
accum.append("&#x").append(Integer.toHexString(codePoint)).append(';');
}
} else {
final String c = new String(Character.toChars(codePoint));
if (encoder.canEncode(c)) // uses fallback encoder for simplicity
accum.append(c);
else
accum.append("&#x").append(Integer.toHexString(codePoint)).append(';');
}
}
} | src/main/java/org/jsoup/nodes/Entities.java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.