index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueDouble.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the DOUBLE data type.
*/
public class ValueDouble extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 17;
/**
* The maximum display size of a double.
* Example: -3.3333333333333334E-100
*/
public static final int DISPLAY_SIZE = 24;
/**
* Double.doubleToLongBits(0.0)
*/
public static final long ZERO_BITS = Double.doubleToLongBits(0.0);
private static final ValueDouble ZERO = new ValueDouble(0.0);
private static final ValueDouble ONE = new ValueDouble(1.0);
private static final ValueDouble NAN = new ValueDouble(Double.NaN);
private final double value;
private ValueDouble(double value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value + v2.value);
}
@Override
public Value subtract(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value - v2.value);
}
@Override
public Value negate() {
return ValueDouble.get(-value);
}
@Override
public Value multiply(Value v) {
ValueDouble v2 = (ValueDouble) v;
return ValueDouble.get(value * v2.value);
}
@Override
public Value divide(Value v) {
ValueDouble v2 = (ValueDouble) v;
if (v2.value == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value / v2.value);
}
@Override
public ValueDouble modulus(Value v) {
ValueDouble other = (ValueDouble) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueDouble.get(value % other.value);
}
@Override
public String getSQL() {
if (value == Double.POSITIVE_INFINITY) {
return "POWER(0, -1)";
} else if (value == Double.NEGATIVE_INFINITY) {
return "(-POWER(0, -1))";
} else if (Double.isNaN(value)) {
return "SQRT(-1)";
}
return getString();
}
@Override
public int getType() {
return Value.DOUBLE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueDouble v = (ValueDouble) o;
return Double.compare(value, v.value);
}
@Override
public int getSignum() {
return value == 0 ? 0 : (value < 0 ? -1 : 1);
}
@Override
public double getDouble() {
return value;
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getScale() {
return 0;
}
@Override
public int hashCode() {
long hash = Double.doubleToLongBits(value);
return (int) (hash ^ (hash >> 32));
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setDouble(parameterIndex, value);
}
/**
* Get or create double value for the given double.
*
* @param d the double
* @return the value
*/
public static ValueDouble get(double d) {
if (d == 1.0) {
return ONE;
} else if (d == 0.0) {
// -0.0 == 0.0, and we want to return 0.0 for both
return ZERO;
} else if (Double.isNaN(d)) {
return NAN;
}
return (ValueDouble) Value.cache(new ValueDouble(d));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueDouble)) {
return false;
}
return compareSecure((ValueDouble) other, null) == 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueEnum.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.util.Locale;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
public class ValueEnum extends ValueEnumBase {
private enum Validation {
DUPLICATE,
EMPTY,
INVALID,
VALID
}
private final String[] enumerators;
private ValueEnum(final String[] enumerators, final int ordinal) {
super(enumerators[ordinal], ordinal);
this.enumerators = enumerators;
}
/**
* Check for any violations, such as empty
* values, duplicate values.
*
* @param enumerators the enumerators
*/
public static void check(final String[] enumerators) {
switch (validate(enumerators)) {
case VALID:
return;
case EMPTY:
throw DbException.get(ErrorCode.ENUM_EMPTY);
case DUPLICATE:
throw DbException.get(ErrorCode.ENUM_DUPLICATE,
toString(enumerators));
default:
throw DbException.get(ErrorCode.INVALID_VALUE_2,
toString(enumerators));
}
}
private static void check(final String[] enumerators, final Value value) {
check(enumerators);
if (validate(enumerators, value) != Validation.VALID) {
throw DbException.get(ErrorCode.ENUM_VALUE_NOT_PERMITTED,
toString(enumerators), value.toString());
}
}
@Override
protected int compareSecure(final Value v, final CompareMode mode) {
return Integer.compare(getInt(), v.getInt());
}
/**
* Create an ENUM value from the provided enumerators
* and value.
*
* @param enumerators the enumerators
* @param value a value
* @return the ENUM value
*/
public static ValueEnum get(final String[] enumerators, int value) {
check(enumerators, ValueInt.get(value));
return new ValueEnum(enumerators, value);
}
public static ValueEnum get(final String[] enumerators, String value) {
check(enumerators, ValueString.get(value));
final String cleanLabel = sanitize(value);
for (int i = 0; i < enumerators.length; i++) {
if (cleanLabel.equals(sanitize(enumerators[i]))) {
return new ValueEnum(enumerators, i);
}
}
throw DbException.get(ErrorCode.GENERAL_ERROR_1, "Unexpected error");
}
public String[] getEnumerators() {
return enumerators;
}
/**
* Evaluates whether a valid ENUM can be constructed
* from the provided enumerators and value.
*
* @param enumerators the enumerators
* @param value the value
* @return whether a valid ENUM can be constructed from the provided values
*/
public static boolean isValid(final String enumerators[], final Value value) {
return validate(enumerators, value).equals(Validation.VALID);
}
private static String sanitize(final String label) {
return label == null ? null : label.trim().toUpperCase(Locale.ENGLISH);
}
private static String[] sanitize(final String[] enumerators) {
if (enumerators == null || enumerators.length == 0) {
return null;
}
final String[] clean = new String[enumerators.length];
for (int i = 0; i < enumerators.length; i++) {
clean[i] = sanitize(enumerators[i]);
}
return clean;
}
private static String toString(final String[] enumerators) {
String result = "(";
for (int i = 0; i < enumerators.length; i++) {
result += "'" + enumerators[i] + "'";
if (i < enumerators.length - 1) {
result += ", ";
}
}
result += ")";
return result;
}
private static Validation validate(final String[] enumerators) {
final String[] cleaned = sanitize(enumerators);
if (cleaned == null || cleaned.length == 0) {
return Validation.EMPTY;
}
for (int i = 0; i < cleaned.length; i++) {
if (cleaned[i] == null || cleaned[i].equals("")) {
return Validation.EMPTY;
}
if (i < cleaned.length - 1) {
for (int j = i + 1; j < cleaned.length; j++) {
if (cleaned[i].equals(cleaned[j])) {
return Validation.DUPLICATE;
}
}
}
}
return Validation.VALID;
}
private static Validation validate(final String[] enumerators, final Value value) {
final Validation validation = validate(enumerators);
if (!validation.equals(Validation.VALID)) {
return validation;
}
if (DataType.isStringType(value.getType())) {
final String cleanLabel = sanitize(value.getString());
for (String enumerator : enumerators) {
if (cleanLabel.equals(sanitize(enumerator))) {
return Validation.VALID;
}
}
return Validation.INVALID;
} else {
final int ordinal = value.getInt();
if (ordinal < 0 || ordinal >= enumerators.length) {
return Validation.INVALID;
}
return Validation.VALID;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueEnumBase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Base implementation of the ENUM data type.
*
* Currently, this class is used primarily for
* client-server communication.
*/
public class ValueEnumBase extends Value {
private static final int PRECISION = 10;
private static final int DISPLAY_SIZE = 11;
private final String label;
private final int ordinal;
protected ValueEnumBase(final String label, final int ordinal) {
this.label = label;
this.ordinal = ordinal;
}
@Override
public Value add(final Value v) {
final Value iv = v.convertTo(Value.INT);
return convertTo(Value.INT).add(iv);
}
@Override
protected int compareSecure(final Value v, final CompareMode mode) {
return Integer.compare(getInt(), v.getInt());
}
@Override
public Value divide(final Value v) {
final Value iv = v.convertTo(Value.INT);
return convertTo(Value.INT).divide(iv);
}
@Override
public boolean equals(final Object other) {
return other instanceof ValueEnumBase &&
getInt() == ((ValueEnumBase) other).getInt();
}
/**
* Get or create an enum value with the given label and ordinal.
*
* @param label the label
* @param ordinal the ordinal
* @return the value
*/
public static ValueEnumBase get(final String label, final int ordinal) {
return new ValueEnumBase(label, ordinal);
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public int getInt() {
return ordinal;
}
@Override
public long getLong() {
return ordinal;
}
@Override
public Object getObject() {
return ordinal;
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getSignum() {
return Integer.signum(ordinal);
}
@Override
public String getSQL() {
return getString();
}
@Override
public String getString() {
return label;
}
@Override
public int getType() {
return Value.ENUM;
}
@Override
public int hashCode() {
int results = 31;
results += getString().hashCode();
results += getInt();
return results;
}
@Override
public Value modulus(final Value v) {
final Value iv = v.convertTo(Value.INT);
return convertTo(Value.INT).modulus(iv);
}
@Override
public Value multiply(final Value v) {
final Value iv = v.convertTo(Value.INT);
return convertTo(Value.INT).multiply(iv);
}
@Override
public void set(final PreparedStatement prep, final int parameterIndex)
throws SQLException {
prep.setInt(parameterIndex, ordinal);
}
@Override
public Value subtract(final Value v) {
final Value iv = v.convertTo(Value.INT);
return convertTo(Value.INT).subtract(iv);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueFloat.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the REAL data type.
*/
public class ValueFloat extends Value {
/**
* Float.floatToIntBits(0.0F).
*/
public static final int ZERO_BITS = Float.floatToIntBits(0.0F);
/**
* The precision in digits.
*/
static final int PRECISION = 7;
/**
* The maximum display size of a float.
* Example: -1.12345676E-20
*/
static final int DISPLAY_SIZE = 15;
private static final ValueFloat ZERO = new ValueFloat(0.0F);
private static final ValueFloat ONE = new ValueFloat(1.0F);
private final float value;
private ValueFloat(float value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value + v2.value);
}
@Override
public Value subtract(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value - v2.value);
}
@Override
public Value negate() {
return ValueFloat.get(-value);
}
@Override
public Value multiply(Value v) {
ValueFloat v2 = (ValueFloat) v;
return ValueFloat.get(value * v2.value);
}
@Override
public Value divide(Value v) {
ValueFloat v2 = (ValueFloat) v;
if (v2.value == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueFloat.get(value / v2.value);
}
@Override
public Value modulus(Value v) {
ValueFloat other = (ValueFloat) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueFloat.get(value % other.value);
}
@Override
public String getSQL() {
if (value == Float.POSITIVE_INFINITY) {
return "POWER(0, -1)";
} else if (value == Float.NEGATIVE_INFINITY) {
return "(-POWER(0, -1))";
} else if (Double.isNaN(value)) {
// NaN
return "SQRT(-1)";
}
return getString();
}
@Override
public int getType() {
return Value.FLOAT;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueFloat v = (ValueFloat) o;
return Float.compare(value, v.value);
}
@Override
public int getSignum() {
return value == 0 ? 0 : (value < 0 ? -1 : 1);
}
@Override
public float getFloat() {
return value;
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int getScale() {
return 0;
}
@Override
public int hashCode() {
long hash = Float.floatToIntBits(value);
return (int) (hash ^ (hash >> 32));
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setFloat(parameterIndex, value);
}
/**
* Get or create float value for the given float.
*
* @param d the float
* @return the value
*/
public static ValueFloat get(float d) {
if (d == 1.0F) {
return ONE;
} else if (d == 0.0F) {
// -0.0 == 0.0, and we want to return 0.0 for both
return ZERO;
}
return (ValueFloat) Value.cache(new ValueFloat(d));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof ValueFloat)) {
return false;
}
return compareSecure((ValueFloat) other, null) == 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueGeometry.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import org.h2.engine.Mode;
import org.h2.message.DbException;
import org.h2.util.StringUtils;
import org.locationtech.jts.geom.CoordinateSequence;
import org.locationtech.jts.geom.CoordinateSequenceFilter;
import org.locationtech.jts.geom.Envelope;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.PrecisionModel;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKBReader;
import org.locationtech.jts.io.WKBWriter;
import org.locationtech.jts.io.WKTReader;
import org.locationtech.jts.io.WKTWriter;
/**
* Implementation of the GEOMETRY data type.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class ValueGeometry extends Value {
/**
* As conversion from/to WKB cost a significant amount of CPU cycles, WKB
* are kept in ValueGeometry instance.
*
* We always calculate the WKB, because not all WKT values can be
* represented in WKB, but since we persist it in WKB format, it has to be
* valid in WKB
*/
private final byte[] bytes;
private final int hashCode;
/**
* The value. Converted from WKB only on request as conversion from/to WKB
* cost a significant amount of CPU cycles.
*/
private Geometry geometry;
/**
* Create a new geometry objects.
*
* @param bytes the bytes (always known)
* @param geometry the geometry object (may be null)
*/
private ValueGeometry(byte[] bytes, Geometry geometry) {
this.bytes = bytes;
this.geometry = geometry;
this.hashCode = Arrays.hashCode(bytes);
}
/**
* Get or create a geometry value for the given geometry.
*
* @param o the geometry object (of type
* org.locationtech.jts.geom.Geometry)
* @return the value
*/
public static ValueGeometry getFromGeometry(Object o) {
return get((Geometry) o);
}
private static ValueGeometry get(Geometry g) {
byte[] bytes = convertToWKB(g);
return (ValueGeometry) Value.cache(new ValueGeometry(bytes, g));
}
private static byte[] convertToWKB(Geometry g) {
boolean includeSRID = g.getSRID() != 0;
int dimensionCount = getDimensionCount(g);
WKBWriter writer = new WKBWriter(dimensionCount, includeSRID);
return writer.write(g);
}
private static int getDimensionCount(Geometry geometry) {
ZVisitor finder = new ZVisitor();
geometry.apply(finder);
return finder.isFoundZ() ? 3 : 2;
}
/**
* Get or create a geometry value for the given geometry.
*
* @param s the WKT representation of the geometry
* @return the value
*/
public static ValueGeometry get(String s) {
try {
Geometry g = new WKTReader().read(s);
return get(g);
} catch (ParseException ex) {
throw DbException.convert(ex);
}
}
/**
* Get or create a geometry value for the given geometry.
*
* @param s the WKT representation of the geometry
* @param srid the srid of the object
* @return the value
*/
public static ValueGeometry get(String s, int srid) {
try {
GeometryFactory geometryFactory = new GeometryFactory(new PrecisionModel(), srid);
Geometry g = new WKTReader(geometryFactory).read(s);
return get(g);
} catch (ParseException ex) {
throw DbException.convert(ex);
}
}
/**
* Get or create a geometry value for the given geometry.
*
* @param bytes the WKB representation of the geometry
* @return the value
*/
public static ValueGeometry get(byte[] bytes) {
return (ValueGeometry) Value.cache(new ValueGeometry(bytes, null));
}
/**
* Get a copy of geometry object. Geometry object is mutable. The returned
* object is therefore copied before returning.
*
* @return a copy of the geometry object
*/
public Geometry getGeometry() {
return getGeometryNoCopy().copy();
}
public Geometry getGeometryNoCopy() {
if (geometry == null) {
try {
geometry = new WKBReader().read(bytes);
} catch (ParseException ex) {
throw DbException.convert(ex);
}
}
return geometry;
}
/**
* Test if this geometry envelope intersects with the other geometry
* envelope.
*
* @param r the other geometry
* @return true if the two overlap
*/
public boolean intersectsBoundingBox(ValueGeometry r) {
// the Geometry object caches the envelope
return getGeometryNoCopy().getEnvelopeInternal().intersects(
r.getGeometryNoCopy().getEnvelopeInternal());
}
/**
* Get the union.
*
* @param r the other geometry
* @return the union of this geometry envelope and another geometry envelope
*/
public Value getEnvelopeUnion(ValueGeometry r) {
GeometryFactory gf = new GeometryFactory();
Envelope mergedEnvelope = new Envelope(getGeometryNoCopy().getEnvelopeInternal());
mergedEnvelope.expandToInclude(r.getGeometryNoCopy().getEnvelopeInternal());
return get(gf.toGeometry(mergedEnvelope));
}
@Override
public int getType() {
return Value.GEOMETRY;
}
@Override
public String getSQL() {
// WKT does not hold Z or SRID with JTS 1.13. As getSQL is used to
// export database, it should contains all object attributes. Moreover
// using bytes is faster than converting WKB to Geometry then to WKT.
return "X'" + StringUtils.convertBytesToHex(getBytesNoCopy()) + "'::Geometry";
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
Geometry g = ((ValueGeometry) v).getGeometryNoCopy();
return getGeometryNoCopy().compareTo(g);
}
@Override
public String getString() {
return getWKT();
}
@Override
public long getPrecision() {
return 0;
}
@Override
public int hashCode() {
return hashCode;
}
@Override
public Object getObject() {
return getGeometry();
}
@Override
public byte[] getBytes() {
return getWKB();
}
@Override
public byte[] getBytesNoCopy() {
return getWKB();
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setObject(parameterIndex, getGeometryNoCopy());
}
@Override
public int getDisplaySize() {
return getWKT().length();
}
@Override
public int getMemory() {
return getWKB().length * 20 + 24;
}
@Override
public boolean equals(Object other) {
// The JTS library only does half-way support for 3D coordinates, so
// their equals method only checks the first two coordinates.
return other instanceof ValueGeometry &&
Arrays.equals(getWKB(), ((ValueGeometry) other).getWKB());
}
/**
* Get the value in Well-Known-Text format.
*
* @return the well-known-text
*/
public String getWKT() {
return new WKTWriter(3).write(getGeometryNoCopy());
}
/**
* Get the value in Well-Known-Binary format.
*
* @return the well-known-binary
*/
public byte[] getWKB() {
return bytes;
}
@Override
public Value convertTo(int targetType, int precision, Mode mode, Object column, String[] enumerators) {
if (targetType == Value.JAVA_OBJECT) {
return this;
}
return super.convertTo(targetType, precision, mode, column, null);
}
/**
* A visitor that checks if there is a Z coordinate.
*/
static class ZVisitor implements CoordinateSequenceFilter {
private boolean foundZ;
public boolean isFoundZ() {
return foundZ;
}
/**
* Performs an operation on a coordinate in a CoordinateSequence.
*
* @param coordinateSequence the object to which the filter is applied
* @param i the index of the coordinate to apply the filter to
*/
@Override
public void filter(CoordinateSequence coordinateSequence, int i) {
if (!Double.isNaN(coordinateSequence.getOrdinate(i, 2))) {
foundZ = true;
}
}
@Override
public boolean isDone() {
return foundZ;
}
@Override
public boolean isGeometryChanged() {
return false;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueInt.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the INT data type.
*/
public class ValueInt extends Value {
/**
* The precision in digits.
*/
public static final int PRECISION = 10;
/**
* The maximum display size of an int.
* Example: -2147483648
*/
public static final int DISPLAY_SIZE = 11;
private static final int STATIC_SIZE = 128;
// must be a power of 2
private static final int DYNAMIC_SIZE = 256;
private static final ValueInt[] STATIC_CACHE = new ValueInt[STATIC_SIZE];
private static final ValueInt[] DYNAMIC_CACHE = new ValueInt[DYNAMIC_SIZE];
private final int value;
static {
for (int i = 0; i < STATIC_SIZE; i++) {
STATIC_CACHE[i] = new ValueInt(i);
}
}
private ValueInt(int value) {
this.value = value;
}
/**
* Get or create an int value for the given int.
*
* @param i the int
* @return the value
*/
public static ValueInt get(int i) {
if (i >= 0 && i < STATIC_SIZE) {
return STATIC_CACHE[i];
}
ValueInt v = DYNAMIC_CACHE[i & (DYNAMIC_SIZE - 1)];
if (v == null || v.value != i) {
v = new ValueInt(i);
DYNAMIC_CACHE[i & (DYNAMIC_SIZE - 1)] = v;
}
return v;
}
@Override
public Value add(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value + (long) other.value);
}
private static ValueInt checkRange(long x) {
if (x < Integer.MIN_VALUE || x > Integer.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1, Long.toString(x));
}
return ValueInt.get((int) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(long) value);
}
@Override
public Value subtract(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value - (long) other.value);
}
@Override
public Value multiply(Value v) {
ValueInt other = (ValueInt) v;
return checkRange((long) value * (long) other.value);
}
@Override
public Value divide(Value v) {
ValueInt other = (ValueInt) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueInt.get(value / other.value);
}
@Override
public Value modulus(Value v) {
ValueInt other = (ValueInt) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueInt.get(value % other.value);
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.INT;
}
@Override
public int getInt() {
return value;
}
@Override
public long getLong() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueInt v = (ValueInt) o;
return Integer.compare(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setInt(parameterIndex, value);
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueInt && value == ((ValueInt) other).value;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueJavaObject.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Types;
import org.h2.engine.SysProperties;
import org.h2.store.DataHandler;
import org.h2.util.Bits;
import org.h2.util.JdbcUtils;
import org.h2.util.Utils;
/**
* Implementation of the OBJECT data type.
*/
public class ValueJavaObject extends ValueBytes {
private static final ValueJavaObject EMPTY =
new ValueJavaObject(Utils.EMPTY_BYTES, null);
private final DataHandler dataHandler;
protected ValueJavaObject(byte[] v, DataHandler dataHandler) {
super(v);
this.dataHandler = dataHandler;
}
/**
* Get or create a java object value for the given byte array.
* Do not clone the data.
*
* @param javaObject the object
* @param b the byte array
* @param dataHandler provides the object serializer
* @return the value
*/
public static ValueJavaObject getNoCopy(Object javaObject, byte[] b,
DataHandler dataHandler) {
if (b != null && b.length == 0) {
return EMPTY;
}
ValueJavaObject obj;
if (SysProperties.serializeJavaObject) {
if (b == null) {
b = JdbcUtils.serialize(javaObject, dataHandler);
}
obj = new ValueJavaObject(b, dataHandler);
} else {
obj = new NotSerialized(javaObject, b, dataHandler);
}
if (b == null || b.length > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return (ValueJavaObject) Value.cache(obj);
}
@Override
public int getType() {
return Value.JAVA_OBJECT;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
Object obj = JdbcUtils.deserialize(getBytesNoCopy(), getDataHandler());
prep.setObject(parameterIndex, obj, Types.JAVA_OBJECT);
}
/**
* Value which serializes java object only for I/O operations.
* Used when property {@link SysProperties#serializeJavaObject} is disabled.
*
* @author Sergi Vladykin
*/
private static class NotSerialized extends ValueJavaObject {
private Object javaObject;
private int displaySize = -1;
NotSerialized(Object javaObject, byte[] v, DataHandler dataHandler) {
super(v, dataHandler);
this.javaObject = javaObject;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setObject(parameterIndex, getObject(), Types.JAVA_OBJECT);
}
@Override
public byte[] getBytesNoCopy() {
if (value == null) {
value = JdbcUtils.serialize(javaObject, null);
}
return value;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
Object o1 = getObject();
Object o2 = v.getObject();
boolean o1Comparable = o1 instanceof Comparable;
boolean o2Comparable = o2 instanceof Comparable;
if (o1Comparable && o2Comparable &&
Utils.haveCommonComparableSuperclass(o1.getClass(), o2.getClass())) {
@SuppressWarnings("unchecked")
Comparable<Object> c1 = (Comparable<Object>) o1;
return c1.compareTo(o2);
}
// group by types
if (o1.getClass() != o2.getClass()) {
if (o1Comparable != o2Comparable) {
return o1Comparable ? -1 : 1;
}
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
// compare hash codes
int h1 = hashCode();
int h2 = v.hashCode();
if (h1 == h2) {
if (o1.equals(o2)) {
return 0;
}
return Bits.compareNotNullSigned(getBytesNoCopy(), v.getBytesNoCopy());
}
return h1 > h2 ? 1 : -1;
}
@Override
public String getString() {
String str = getObject().toString();
if (displaySize == -1) {
displaySize = str.length();
}
return str;
}
@Override
public long getPrecision() {
return 0;
}
@Override
public int hashCode() {
if (hash == 0) {
hash = getObject().hashCode();
}
return hash;
}
@Override
public Object getObject() {
if (javaObject == null) {
javaObject = JdbcUtils.deserialize(value, getDataHandler());
}
return javaObject;
}
@Override
public int getDisplaySize() {
if (displaySize == -1) {
displaySize = getString().length();
}
return displaySize;
}
@Override
public int getMemory() {
if (value == null) {
return DataType.getDataType(getType()).memory;
}
int mem = super.getMemory();
if (javaObject != null) {
mem *= 2;
}
return mem;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof NotSerialized)) {
return false;
}
return getObject().equals(((NotSerialized) other).getObject());
}
@Override
public Value convertPrecision(long precision, boolean force) {
return this;
}
}
@Override
protected DataHandler getDataHandler() {
return dataHandler;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueLob.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.engine.Constants;
import org.h2.engine.Mode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.store.FileStoreInputStream;
import org.h2.store.FileStoreOutputStream;
import org.h2.store.RangeInputStream;
import org.h2.store.RangeReader;
import org.h2.store.fs.FileUtils;
import org.h2.util.Bits;
import org.h2.util.IOUtils;
import org.h2.util.MathUtils;
import org.h2.util.SmallLRUCache;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* Implementation of the BLOB and CLOB data types. Small objects are kept in
* memory and stored in the record.
*
* Large objects are stored in their own files. When large objects are set in a
* prepared statement, they are first stored as 'temporary' files. Later, when
* they are used in a record, and when the record is stored, the lob files are
* linked: the file is renamed using the file format (tableId).(objectId). There
* is one exception: large variables are stored in the file (-1).(objectId).
*
* When lobs are deleted, they are first renamed to a temp file, and if the
* delete operation is committed the file is deleted.
*
* Data compression is supported.
*/
public class ValueLob extends Value {
private static void rangeCheckUnknown(long zeroBasedOffset, long length) {
if (zeroBasedOffset < 0) {
throw DbException.getInvalidValueException("offset", zeroBasedOffset + 1);
}
if (length < 0) {
throw DbException.getInvalidValueException("length", length);
}
}
/**
* Create an input stream that is s subset of the given stream.
*
* @param inputStream the source input stream
* @param oneBasedOffset the offset (1 means no offset)
* @param length the length of the result, in bytes
* @param dataSize the length of the input, in bytes
* @return the smaller input stream
*/
static InputStream rangeInputStream(InputStream inputStream, long oneBasedOffset, long length, long dataSize) {
if (dataSize > 0) {
rangeCheck(oneBasedOffset - 1, length, dataSize);
} else {
rangeCheckUnknown(oneBasedOffset - 1, length);
}
try {
return new RangeInputStream(inputStream, oneBasedOffset - 1, length);
} catch (IOException e) {
throw DbException.getInvalidValueException("offset", oneBasedOffset);
}
}
/**
* Create a reader that is s subset of the given reader.
*
* @param reader the input reader
* @param oneBasedOffset the offset (1 means no offset)
* @param length the length of the result, in bytes
* @param dataSize the length of the input, in bytes
* @return the smaller input stream
*/
static Reader rangeReader(Reader reader, long oneBasedOffset, long length, long dataSize) {
if (dataSize > 0) {
rangeCheck(oneBasedOffset - 1, length, dataSize);
} else {
rangeCheckUnknown(oneBasedOffset - 1, length);
}
try {
return new RangeReader(reader, oneBasedOffset - 1, length);
} catch (IOException e) {
throw DbException.getInvalidValueException("offset", oneBasedOffset);
}
}
/**
* This counter is used to calculate the next directory to store lobs. It is
* better than using a random number because less directories are created.
*/
private static int dirCounter;
private final int type;
private long precision;
private DataHandler handler;
private int tableId;
private int objectId;
private String fileName;
private boolean linked;
private byte[] small;
private int hash;
private boolean compressed;
private FileStore tempFile;
private ValueLob(int type, DataHandler handler, String fileName,
int tableId, int objectId, boolean linked, long precision,
boolean compressed) {
this.type = type;
this.handler = handler;
this.fileName = fileName;
this.tableId = tableId;
this.objectId = objectId;
this.linked = linked;
this.precision = precision;
this.compressed = compressed;
}
private ValueLob(int type, byte[] small) {
this.type = type;
this.small = small;
if (small != null) {
if (type == Value.BLOB) {
this.precision = small.length;
} else {
this.precision = getString().length();
}
}
}
private static ValueLob copy(ValueLob lob) {
ValueLob copy = new ValueLob(lob.type, lob.handler, lob.fileName,
lob.tableId, lob.objectId, lob.linked, lob.precision, lob.compressed);
copy.small = lob.small;
copy.hash = lob.hash;
return copy;
}
/**
* Create a small lob using the given byte array.
*
* @param type the type (Value.BLOB or CLOB)
* @param small the byte array
* @return the lob value
*/
private static ValueLob createSmallLob(int type, byte[] small) {
return new ValueLob(type, small);
}
private static String getFileName(DataHandler handler, int tableId,
int objectId) {
if (SysProperties.CHECK && tableId == 0 && objectId == 0) {
DbException.throwInternalError("0 LOB");
}
String table = tableId < 0 ? ".temp" : ".t" + tableId;
return getFileNamePrefix(handler.getDatabasePath(), objectId) +
table + Constants.SUFFIX_LOB_FILE;
}
/**
* Create a LOB value with the given parameters.
*
* @param type the data type
* @param handler the file handler
* @param tableId the table object id
* @param objectId the object id
* @param precision the precision (length in elements)
* @param compression if compression is used
* @return the value object
*/
public static ValueLob openLinked(int type, DataHandler handler,
int tableId, int objectId, long precision, boolean compression) {
String fileName = getFileName(handler, tableId, objectId);
return new ValueLob(type, handler, fileName, tableId, objectId,
true/* linked */, precision, compression);
}
/**
* Create a LOB value with the given parameters.
*
* @param type the data type
* @param handler the file handler
* @param tableId the table object id
* @param objectId the object id
* @param precision the precision (length in elements)
* @param compression if compression is used
* @param fileName the file name
* @return the value object
*/
public static ValueLob openUnlinked(int type, DataHandler handler,
int tableId, int objectId, long precision, boolean compression,
String fileName) {
return new ValueLob(type, handler, fileName, tableId, objectId,
false/* linked */, precision, compression);
}
/**
* Create a CLOB value from a stream.
*
* @param in the reader
* @param length the number of characters to read, or -1 for no limit
* @param handler the data handler
* @return the lob value
*/
private static ValueLob createClob(Reader in, long length,
DataHandler handler) {
try {
if (handler == null) {
String s = IOUtils.readStringAndClose(in, (int) length);
return createSmallLob(Value.CLOB, s.getBytes(StandardCharsets.UTF_8));
}
boolean compress = handler.getLobCompressionAlgorithm(Value.CLOB) != null;
long remaining = Long.MAX_VALUE;
if (length >= 0 && length < remaining) {
remaining = length;
}
int len = getBufferSize(handler, compress, remaining);
char[] buff;
if (len >= Integer.MAX_VALUE) {
String data = IOUtils.readStringAndClose(in, -1);
buff = data.toCharArray();
len = buff.length;
} else {
buff = new char[len];
len = IOUtils.readFully(in, buff, len);
}
if (len <= handler.getMaxLengthInplaceLob()) {
byte[] small = new String(buff, 0, len).getBytes(StandardCharsets.UTF_8);
return ValueLob.createSmallLob(Value.CLOB, small);
}
ValueLob lob = new ValueLob(Value.CLOB, null);
lob.createFromReader(buff, len, in, remaining, handler);
return lob;
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
private static int getBufferSize(DataHandler handler, boolean compress,
long remaining) {
if (remaining < 0 || remaining > Integer.MAX_VALUE) {
remaining = Integer.MAX_VALUE;
}
int inplace = handler.getMaxLengthInplaceLob();
long m = compress ?
Constants.IO_BUFFER_SIZE_COMPRESS : Constants.IO_BUFFER_SIZE;
if (m < remaining && m <= inplace) {
// using "1L" to force long arithmetic
m = Math.min(remaining, inplace + 1L);
// the buffer size must be bigger than the inplace lob, otherwise we
// can't know if it must be stored in-place or not
m = MathUtils.roundUpLong(m, Constants.IO_BUFFER_SIZE);
}
m = Math.min(remaining, m);
m = MathUtils.convertLongToInt(m);
if (m < 0) {
m = Integer.MAX_VALUE;
}
return (int) m;
}
private void createFromReader(char[] buff, int len, Reader in,
long remaining, DataHandler h) throws IOException {
try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.CLOB) != null;
while (true) {
precision += len;
byte[] b = new String(buff, 0, len).getBytes(StandardCharsets.UTF_8);
out.write(b, 0, b.length);
remaining -= len;
if (remaining <= 0) {
break;
}
len = getBufferSize(h, compress, remaining);
len = IOUtils.readFully(in, buff, len);
if (len == 0) {
break;
}
}
}
}
private static String getFileNamePrefix(String path, int objectId) {
String name;
int f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY;
if (f > 0) {
name = SysProperties.FILE_SEPARATOR + objectId;
} else {
name = "";
}
objectId /= SysProperties.LOB_FILES_PER_DIRECTORY;
while (objectId > 0) {
f = objectId % SysProperties.LOB_FILES_PER_DIRECTORY;
name = SysProperties.FILE_SEPARATOR + f +
Constants.SUFFIX_LOBS_DIRECTORY + name;
objectId /= SysProperties.LOB_FILES_PER_DIRECTORY;
}
name = FileUtils.toRealPath(path +
Constants.SUFFIX_LOBS_DIRECTORY + name);
return name;
}
private static int getNewObjectId(DataHandler h) {
String path = h.getDatabasePath();
if ((path != null) && (path.length() == 0)) {
path = new File(Utils.getProperty("java.io.tmpdir", "."),
SysProperties.PREFIX_TEMP_FILE).getAbsolutePath();
}
int newId = 0;
int lobsPerDir = SysProperties.LOB_FILES_PER_DIRECTORY;
while (true) {
String dir = getFileNamePrefix(path, newId);
String[] list = getFileList(h, dir);
int fileCount = 0;
boolean[] used = new boolean[lobsPerDir];
for (String name : list) {
if (name.endsWith(Constants.SUFFIX_DB_FILE)) {
name = FileUtils.getName(name);
String n = name.substring(0, name.indexOf('.'));
int id;
try {
id = Integer.parseInt(n);
} catch (NumberFormatException e) {
id = -1;
}
if (id > 0) {
fileCount++;
used[id % lobsPerDir] = true;
}
}
}
int fileId = -1;
if (fileCount < lobsPerDir) {
for (int i = 1; i < lobsPerDir; i++) {
if (!used[i]) {
fileId = i;
break;
}
}
}
if (fileId > 0) {
newId += fileId;
invalidateFileList(h, dir);
break;
}
if (newId > Integer.MAX_VALUE / lobsPerDir) {
// this directory path is full: start from zero
newId = 0;
dirCounter = MathUtils.randomInt(lobsPerDir - 1) * lobsPerDir;
} else {
// calculate the directory.
// start with 1 (otherwise we don't know the number of
// directories).
// it doesn't really matter what directory is used, it might as
// well be random (but that would generate more directories):
// int dirId = RandomUtils.nextInt(lobsPerDir - 1) + 1;
int dirId = (dirCounter++ / (lobsPerDir - 1)) + 1;
newId = newId * lobsPerDir;
newId += dirId * lobsPerDir;
}
}
return newId;
}
private static void invalidateFileList(DataHandler h, String dir) {
SmallLRUCache<String, String[]> cache = h.getLobFileListCache();
if (cache != null) {
synchronized (cache) {
cache.remove(dir);
}
}
}
private static String[] getFileList(DataHandler h, String dir) {
SmallLRUCache<String, String[]> cache = h.getLobFileListCache();
String[] list;
if (cache == null) {
list = FileUtils.newDirectoryStream(dir).toArray(new String[0]);
} else {
synchronized (cache) {
list = cache.get(dir);
if (list == null) {
list = FileUtils.newDirectoryStream(dir).toArray(new String[0]);
cache.put(dir, list);
}
}
}
return list;
}
/**
* Create a BLOB value from a stream.
*
* @param in the input stream
* @param length the number of characters to read, or -1 for no limit
* @param handler the data handler
* @return the lob value
*/
private static ValueLob createBlob(InputStream in, long length,
DataHandler handler) {
try {
if (handler == null) {
byte[] data = IOUtils.readBytesAndClose(in, (int) length);
return createSmallLob(Value.BLOB, data);
}
long remaining = Long.MAX_VALUE;
boolean compress = handler.getLobCompressionAlgorithm(Value.BLOB) != null;
if (length >= 0 && length < remaining) {
remaining = length;
}
int len = getBufferSize(handler, compress, remaining);
byte[] buff;
if (len >= Integer.MAX_VALUE) {
buff = IOUtils.readBytesAndClose(in, -1);
len = buff.length;
} else {
buff = Utils.newBytes(len);
len = IOUtils.readFully(in, buff, len);
}
if (len <= handler.getMaxLengthInplaceLob()) {
byte[] small = Utils.copyBytes(buff, len);
return ValueLob.createSmallLob(Value.BLOB, small);
}
ValueLob lob = new ValueLob(Value.BLOB, null);
lob.createFromStream(buff, len, in, remaining, handler);
return lob;
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
private FileStoreOutputStream initLarge(DataHandler h) {
this.handler = h;
this.tableId = 0;
this.linked = false;
this.precision = 0;
this.small = null;
this.hash = 0;
String compressionAlgorithm = h.getLobCompressionAlgorithm(type);
this.compressed = compressionAlgorithm != null;
synchronized (h) {
String path = h.getDatabasePath();
if ((path != null) && (path.length() == 0)) {
path = new File(Utils.getProperty("java.io.tmpdir", "."),
SysProperties.PREFIX_TEMP_FILE).getAbsolutePath();
}
objectId = getNewObjectId(h);
fileName = getFileNamePrefix(path, objectId) + Constants.SUFFIX_TEMP_FILE;
tempFile = h.openFile(fileName, "rw", false);
tempFile.autoDelete();
}
return new FileStoreOutputStream(tempFile, h,
compressionAlgorithm);
}
private void createFromStream(byte[] buff, int len, InputStream in,
long remaining, DataHandler h) throws IOException {
try (FileStoreOutputStream out = initLarge(h)) {
boolean compress = h.getLobCompressionAlgorithm(Value.BLOB) != null;
while (true) {
precision += len;
out.write(buff, 0, len);
remaining -= len;
if (remaining <= 0) {
break;
}
len = getBufferSize(h, compress, remaining);
len = IOUtils.readFully(in, buff, len);
if (len <= 0) {
break;
}
}
}
}
/**
* Convert a lob to another data type. The data is fully read in memory
* except when converting to BLOB or CLOB.
*
* @param t the new type
* @param precision the precision of the column to convert this value to.
* The special constant <code>-1</code> is used to indicate that
* the precision plays no role when converting the value
* @param mode the database mode
* @param column the column (if any), used for to improve the error message if conversion fails
* @param enumerators the ENUM datatype enumerators (if any),
* for dealing with ENUM conversions
* @return the converted value
*/
@Override
public Value convertTo(int t, int precision, Mode mode, Object column, String[] enumerators) {
if (t == type) {
return this;
} else if (t == Value.CLOB) {
return ValueLob.createClob(getReader(), -1, handler);
} else if (t == Value.BLOB) {
return ValueLob.createBlob(getInputStream(), -1, handler);
}
return super.convertTo(t, precision, mode, column, null);
}
@Override
public boolean isLinkedToTable() {
return linked;
}
/**
* Get the current file name where the lob is saved.
*
* @return the file name or null
*/
public String getFileName() {
return fileName;
}
@Override
public void remove() {
if (fileName != null) {
if (tempFile != null) {
tempFile.stopAutoDelete();
tempFile = null;
}
deleteFile(handler, fileName);
}
}
@Override
public Value copy(DataHandler h, int tabId) {
if (fileName == null) {
this.tableId = tabId;
return this;
}
if (linked) {
ValueLob copy = ValueLob.copy(this);
copy.objectId = getNewObjectId(h);
copy.tableId = tabId;
String live = getFileName(h, copy.tableId, copy.objectId);
copyFileTo(h, fileName, live);
copy.fileName = live;
copy.linked = true;
return copy;
}
if (!linked) {
this.tableId = tabId;
String live = getFileName(h, tableId, objectId);
if (tempFile != null) {
tempFile.stopAutoDelete();
tempFile = null;
}
renameFile(h, fileName, live);
fileName = live;
linked = true;
}
return this;
}
/**
* Get the current table id of this lob.
*
* @return the table id
*/
@Override
public int getTableId() {
return tableId;
}
/**
* Get the current object id of this lob.
*
* @return the object id
*/
public int getObjectId() {
return objectId;
}
@Override
public int getType() {
return type;
}
@Override
public long getPrecision() {
return precision;
}
@Override
public String getString() {
int len = precision > Integer.MAX_VALUE || precision == 0 ?
Integer.MAX_VALUE : (int) precision;
try {
if (type == Value.CLOB) {
if (small != null) {
return new String(small, StandardCharsets.UTF_8);
}
return IOUtils.readStringAndClose(getReader(), len);
}
byte[] buff;
if (small != null) {
buff = small;
} else {
buff = IOUtils.readBytesAndClose(getInputStream(), len);
}
return StringUtils.convertBytesToHex(buff);
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
}
@Override
public byte[] getBytes() {
if (type == CLOB) {
// convert hex to string
return super.getBytes();
}
byte[] data = getBytesNoCopy();
return Utils.cloneByteArray(data);
}
@Override
public byte[] getBytesNoCopy() {
if (type == CLOB) {
// convert hex to string
return super.getBytesNoCopy();
}
if (small != null) {
return small;
}
try {
return IOUtils.readBytesAndClose(
getInputStream(), Integer.MAX_VALUE);
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
}
@Override
public int hashCode() {
if (hash == 0) {
if (precision > 4096) {
// TODO: should calculate the hash code when saving, and store
// it in the database file
return (int) (precision ^ (precision >>> 32));
}
if (type == CLOB) {
hash = getString().hashCode();
} else {
hash = Utils.getByteArrayHash(getBytes());
}
}
return hash;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
if (type == Value.CLOB) {
return Integer.signum(getString().compareTo(v.getString()));
}
byte[] v2 = v.getBytesNoCopy();
return Bits.compareNotNullSigned(getBytesNoCopy(), v2);
}
@Override
public Object getObject() {
if (type == Value.CLOB) {
return getReader();
}
return getInputStream();
}
@Override
public Reader getReader() {
return IOUtils.getBufferedReader(getInputStream());
}
@Override
public Reader getReader(long oneBasedOffset, long length) {
return rangeReader(getReader(), oneBasedOffset, length, type == Value.CLOB ? precision : -1);
}
@Override
public InputStream getInputStream() {
if (fileName == null) {
return new ByteArrayInputStream(small);
}
FileStore store = handler.openFile(fileName, "r", true);
boolean alwaysClose = SysProperties.lobCloseBetweenReads;
return new BufferedInputStream(
new FileStoreInputStream(store, handler, compressed, alwaysClose),
Constants.IO_BUFFER_SIZE);
}
@Override
public InputStream getInputStream(long oneBasedOffset, long length) {
if (fileName == null) {
return super.getInputStream(oneBasedOffset, length);
}
FileStore store = handler.openFile(fileName, "r", true);
boolean alwaysClose = SysProperties.lobCloseBetweenReads;
InputStream inputStream = new BufferedInputStream(
new FileStoreInputStream(store, handler, compressed, alwaysClose),
Constants.IO_BUFFER_SIZE);
return rangeInputStream(inputStream, oneBasedOffset, length, store.length());
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
long p = getPrecision();
if (p > Integer.MAX_VALUE || p <= 0) {
p = -1;
}
if (type == Value.BLOB) {
prep.setBinaryStream(parameterIndex, getInputStream(), (int) p);
} else {
prep.setCharacterStream(parameterIndex, getReader(), (int) p);
}
}
@Override
public String getSQL() {
String s;
if (type == Value.CLOB) {
s = getString();
return StringUtils.quoteStringSQL(s);
}
byte[] buff = getBytes();
s = StringUtils.convertBytesToHex(buff);
return "X'" + s + "'";
}
@Override
public String getTraceSQL() {
if (small != null && getPrecision() <= SysProperties.MAX_TRACE_DATA_LENGTH) {
return getSQL();
}
StringBuilder buff = new StringBuilder();
if (type == Value.CLOB) {
buff.append("SPACE(").append(getPrecision());
} else {
buff.append("CAST(REPEAT('00', ").append(getPrecision()).append(") AS BINARY");
}
buff.append(" /* ").append(fileName).append(" */)");
return buff.toString();
}
/**
* Get the data if this a small lob value.
*
* @return the data
*/
@Override
public byte[] getSmall() {
return small;
}
@Override
public int getDisplaySize() {
return MathUtils.convertLongToInt(getPrecision());
}
@Override
public boolean equals(Object other) {
return other instanceof ValueLob && compareSecure((Value) other, null) == 0;
}
/**
* Store the lob data to a file if the size of the buffer is larger than the
* maximum size for an in-place lob.
*
* @param h the data handler
*/
public void convertToFileIfRequired(DataHandler h) {
try {
if (small != null && small.length > h.getMaxLengthInplaceLob()) {
boolean compress = h.getLobCompressionAlgorithm(type) != null;
int len = getBufferSize(h, compress, Long.MAX_VALUE);
int tabId = tableId;
if (type == Value.BLOB) {
createFromStream(
Utils.newBytes(len), 0, getInputStream(), Long.MAX_VALUE, h);
} else {
createFromReader(
new char[len], 0, getReader(), Long.MAX_VALUE, h);
}
Value v2 = copy(h, tabId);
if (SysProperties.CHECK && v2 != this) {
DbException.throwInternalError(v2.toString());
}
}
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
/**
* Check if this lob value is compressed.
*
* @return true if it is
*/
public boolean isCompressed() {
return compressed;
}
private static synchronized void deleteFile(DataHandler handler,
String fileName) {
// synchronize on the database, to avoid concurrent temp file creation /
// deletion / backup
synchronized (handler.getLobSyncObject()) {
FileUtils.delete(fileName);
}
}
private static synchronized void renameFile(DataHandler handler,
String oldName, String newName) {
synchronized (handler.getLobSyncObject()) {
FileUtils.move(oldName, newName);
}
}
private static void copyFileTo(DataHandler h, String sourceFileName,
String targetFileName) {
synchronized (h.getLobSyncObject()) {
try {
IOUtils.copyFiles(sourceFileName, targetFileName);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
}
@Override
public int getMemory() {
if (small != null) {
return small.length + 104;
}
return 140;
}
/**
* Create an independent copy of this temporary value.
* The file will not be deleted automatically.
*
* @return the value
*/
@Override
public ValueLob copyToTemp() {
ValueLob lob;
if (type == CLOB) {
lob = ValueLob.createClob(getReader(), precision, handler);
} else {
lob = ValueLob.createBlob(getInputStream(), precision, handler);
}
return lob;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (this.precision <= precision) {
return this;
}
ValueLob lob;
if (type == CLOB) {
lob = ValueLob.createClob(getReader(), precision, handler);
} else {
lob = ValueLob.createBlob(getInputStream(), precision, handler);
}
return lob;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueLobDb.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.engine.Constants;
import org.h2.engine.Mode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.store.FileStoreInputStream;
import org.h2.store.FileStoreOutputStream;
import org.h2.store.LobStorageFrontend;
import org.h2.store.LobStorageInterface;
import org.h2.store.RangeReader;
import org.h2.store.fs.FileUtils;
import org.h2.util.Bits;
import org.h2.util.IOUtils;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* A implementation of the BLOB and CLOB data types.
*
* Small objects are kept in memory and stored in the record.
* Large objects are either stored in the database, or in temporary files.
*/
public class ValueLobDb extends Value implements Value.ValueClob,
Value.ValueBlob {
private final int type;
private final long lobId;
private final byte[] hmac;
private final byte[] small;
private final DataHandler handler;
/**
* For a BLOB, precision is length in bytes.
* For a CLOB, precision is length in chars.
*/
private final long precision;
private final String fileName;
private final FileStore tempFile;
private final int tableId;
private int hash;
//Arbonaut: 13.07.2016
// Fix for recovery tool.
private boolean isRecoveryReference;
private ValueLobDb(int type, DataHandler handler, int tableId, long lobId,
byte[] hmac, long precision) {
this.type = type;
this.handler = handler;
this.tableId = tableId;
this.lobId = lobId;
this.hmac = hmac;
this.precision = precision;
this.small = null;
this.fileName = null;
this.tempFile = null;
}
private ValueLobDb(int type, byte[] small, long precision) {
this.type = type;
this.small = small;
this.precision = precision;
this.lobId = 0;
this.hmac = null;
this.handler = null;
this.fileName = null;
this.tempFile = null;
this.tableId = 0;
}
/**
* Create a CLOB in a temporary file.
*/
private ValueLobDb(DataHandler handler, Reader in, long remaining)
throws IOException {
this.type = Value.CLOB;
this.handler = handler;
this.small = null;
this.lobId = 0;
this.hmac = null;
this.fileName = createTempLobFileName(handler);
this.tempFile = this.handler.openFile(fileName, "rw", false);
this.tempFile.autoDelete();
long tmpPrecision = 0;
try (FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null)) {
char[] buff = new char[Constants.IO_BUFFER_SIZE];
while (true) {
int len = getBufferSize(this.handler, false, remaining);
len = IOUtils.readFully(in, buff, len);
if (len == 0) {
break;
}
byte[] data = new String(buff, 0, len).getBytes(StandardCharsets.UTF_8);
out.write(data);
tmpPrecision += len;
}
}
this.precision = tmpPrecision;
this.tableId = 0;
}
/**
* Create a BLOB in a temporary file.
*/
private ValueLobDb(DataHandler handler, byte[] buff, int len, InputStream in,
long remaining) throws IOException {
this.type = Value.BLOB;
this.handler = handler;
this.small = null;
this.lobId = 0;
this.hmac = null;
this.fileName = createTempLobFileName(handler);
this.tempFile = this.handler.openFile(fileName, "rw", false);
this.tempFile.autoDelete();
long tmpPrecision = 0;
boolean compress = this.handler.getLobCompressionAlgorithm(Value.BLOB) != null;
try (FileStoreOutputStream out = new FileStoreOutputStream(tempFile, null, null)) {
while (true) {
tmpPrecision += len;
out.write(buff, 0, len);
remaining -= len;
if (remaining <= 0) {
break;
}
len = getBufferSize(this.handler, compress, remaining);
len = IOUtils.readFully(in, buff, len);
if (len <= 0) {
break;
}
}
}
this.precision = tmpPrecision;
this.tableId = 0;
}
private static String createTempLobFileName(DataHandler handler)
throws IOException {
String path = handler.getDatabasePath();
if (path.length() == 0) {
path = SysProperties.PREFIX_TEMP_FILE;
}
return FileUtils.createTempFile(path, Constants.SUFFIX_TEMP_FILE, true, true);
}
/**
* Create a LOB value.
*
* @param type the type
* @param handler the data handler
* @param tableId the table id
* @param id the lob id
* @param hmac the message authentication code
* @param precision the precision (number of bytes / characters)
* @return the value
*/
public static ValueLobDb create(int type, DataHandler handler,
int tableId, long id, byte[] hmac, long precision) {
return new ValueLobDb(type, handler, tableId, id, hmac, precision);
}
/**
* Convert a lob to another data type. The data is fully read in memory
* except when converting to BLOB or CLOB.
*
* @param t the new type
* @param precision the precision
* @param mode the mode
* @param column the column (if any), used for to improve the error message if conversion fails
* @param enumerators the ENUM datatype enumerators (if any),
* for dealing with ENUM conversions
* @return the converted value
*/
@Override
public Value convertTo(int t, int precision, Mode mode, Object column, String[] enumerators) {
if (t == type) {
return this;
} else if (t == Value.CLOB) {
if (handler != null) {
return handler.getLobStorage().
createClob(getReader(), -1);
} else if (small != null) {
return ValueLobDb.createSmallLob(t, small);
}
} else if (t == Value.BLOB) {
if (handler != null) {
return handler.getLobStorage().
createBlob(getInputStream(), -1);
} else if (small != null) {
return ValueLobDb.createSmallLob(t, small);
}
}
return super.convertTo(t, precision, mode, column, null);
}
@Override
public boolean isLinkedToTable() {
return small == null &&
tableId >= 0;
}
public boolean isStored() {
return small == null && fileName == null;
}
@Override
public void remove() {
if (fileName != null) {
if (tempFile != null) {
tempFile.stopAutoDelete();
}
// synchronize on the database, to avoid concurrent temp file
// creation / deletion / backup
synchronized (handler.getLobSyncObject()) {
FileUtils.delete(fileName);
}
}
if (handler != null) {
handler.getLobStorage().removeLob(this);
}
}
@Override
public Value copy(DataHandler database, int tableId) {
if (small == null) {
return handler.getLobStorage().copyLob(this, tableId, getPrecision());
} else if (small.length > database.getMaxLengthInplaceLob()) {
LobStorageInterface s = database.getLobStorage();
Value v;
if (type == Value.BLOB) {
v = s.createBlob(getInputStream(), getPrecision());
} else {
v = s.createClob(getReader(), getPrecision());
}
Value v2 = v.copy(database, tableId);
v.remove();
return v2;
}
return this;
}
/**
* Get the current table id of this lob.
*
* @return the table id
*/
@Override
public int getTableId() {
return tableId;
}
@Override
public int getType() {
return type;
}
@Override
public long getPrecision() {
return precision;
}
@Override
public String getString() {
int len = precision > Integer.MAX_VALUE || precision == 0 ?
Integer.MAX_VALUE : (int) precision;
try {
if (type == Value.CLOB) {
if (small != null) {
return new String(small, StandardCharsets.UTF_8);
}
return IOUtils.readStringAndClose(getReader(), len);
}
byte[] buff;
if (small != null) {
buff = small;
} else {
buff = IOUtils.readBytesAndClose(getInputStream(), len);
}
return StringUtils.convertBytesToHex(buff);
} catch (IOException e) {
throw DbException.convertIOException(e, toString());
}
}
@Override
public byte[] getBytes() {
if (type == CLOB) {
// convert hex to string
return super.getBytes();
}
byte[] data = getBytesNoCopy();
return Utils.cloneByteArray(data);
}
@Override
public byte[] getBytesNoCopy() {
if (type == CLOB) {
// convert hex to string
return super.getBytesNoCopy();
}
if (small != null) {
return small;
}
try {
return IOUtils.readBytesAndClose(getInputStream(), Integer.MAX_VALUE);
} catch (IOException e) {
throw DbException.convertIOException(e, toString());
}
}
@Override
public int hashCode() {
if (hash == 0) {
if (precision > 4096) {
// TODO: should calculate the hash code when saving, and store
// it in the database file
return (int) (precision ^ (precision >>> 32));
}
if (type == CLOB) {
hash = getString().hashCode();
} else {
hash = Utils.getByteArrayHash(getBytes());
}
}
return hash;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
if (v instanceof ValueLobDb) {
ValueLobDb v2 = (ValueLobDb) v;
if (v == this) {
return 0;
}
if (lobId == v2.lobId && small == null && v2.small == null) {
return 0;
}
}
if (type == Value.CLOB) {
return Integer.signum(getString().compareTo(v.getString()));
}
byte[] v2 = v.getBytesNoCopy();
return Bits.compareNotNullSigned(getBytesNoCopy(), v2);
}
@Override
public Object getObject() {
if (type == Value.CLOB) {
return getReader();
}
return getInputStream();
}
@Override
public Reader getReader() {
return IOUtils.getBufferedReader(getInputStream());
}
@Override
public Reader getReader(long oneBasedOffset, long length) {
return ValueLob.rangeReader(getReader(), oneBasedOffset, length, type == Value.CLOB ? precision : -1);
}
@Override
public InputStream getInputStream() {
if (small != null) {
return new ByteArrayInputStream(small);
} else if (fileName != null) {
FileStore store = handler.openFile(fileName, "r", true);
boolean alwaysClose = SysProperties.lobCloseBetweenReads;
return new BufferedInputStream(new FileStoreInputStream(store,
handler, false, alwaysClose), Constants.IO_BUFFER_SIZE);
}
long byteCount = (type == Value.BLOB) ? precision : -1;
try {
return handler.getLobStorage().getInputStream(this, hmac, byteCount);
} catch (IOException e) {
throw DbException.convertIOException(e, toString());
}
}
@Override
public InputStream getInputStream(long oneBasedOffset, long length) {
long byteCount;
InputStream inputStream;
if (small != null) {
return super.getInputStream(oneBasedOffset, length);
} else if (fileName != null) {
FileStore store = handler.openFile(fileName, "r", true);
boolean alwaysClose = SysProperties.lobCloseBetweenReads;
byteCount = store.length();
inputStream = new BufferedInputStream(new FileStoreInputStream(store,
handler, false, alwaysClose), Constants.IO_BUFFER_SIZE);
} else {
byteCount = (type == Value.BLOB) ? precision : -1;
try {
inputStream = handler.getLobStorage().getInputStream(this, hmac, byteCount);
} catch (IOException e) {
throw DbException.convertIOException(e, toString());
}
}
return ValueLob.rangeInputStream(inputStream, oneBasedOffset, length, byteCount);
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
long p = getPrecision();
if (p > Integer.MAX_VALUE || p <= 0) {
p = -1;
}
if (type == Value.BLOB) {
prep.setBinaryStream(parameterIndex, getInputStream(), (int) p);
} else {
prep.setCharacterStream(parameterIndex, getReader(), (int) p);
}
}
@Override
public String getSQL() {
String s;
if (type == Value.CLOB) {
s = getString();
return StringUtils.quoteStringSQL(s);
}
byte[] buff = getBytes();
s = StringUtils.convertBytesToHex(buff);
return "X'" + s + "'";
}
@Override
public String getTraceSQL() {
if (small != null && getPrecision() <= SysProperties.MAX_TRACE_DATA_LENGTH) {
return getSQL();
}
StringBuilder buff = new StringBuilder();
if (type == Value.CLOB) {
buff.append("SPACE(").append(getPrecision());
} else {
buff.append("CAST(REPEAT('00', ").append(getPrecision()).append(") AS BINARY");
}
buff.append(" /* table: ").append(tableId).append(" id: ")
.append(lobId).append(" */)");
return buff.toString();
}
/**
* Get the data if this a small lob value.
*
* @return the data
*/
@Override
public byte[] getSmall() {
return small;
}
@Override
public int getDisplaySize() {
return MathUtils.convertLongToInt(getPrecision());
}
@Override
public boolean equals(Object other) {
return other instanceof ValueLobDb && compareSecure((Value) other, null) == 0;
}
@Override
public int getMemory() {
if (small != null) {
return small.length + 104;
}
return 140;
}
/**
* Create an independent copy of this temporary value.
* The file will not be deleted automatically.
*
* @return the value
*/
@Override
public ValueLobDb copyToTemp() {
return this;
}
/**
* Create an independent copy of this value,
* that will be bound to a result.
*
* @return the value (this for small objects)
*/
@Override
public ValueLobDb copyToResult() {
if (handler == null) {
return this;
}
LobStorageInterface s = handler.getLobStorage();
if (s.isReadOnly()) {
return this;
}
return s.copyLob(this, LobStorageFrontend.TABLE_RESULT,
getPrecision());
}
public long getLobId() {
return lobId;
}
@Override
public String toString() {
return "lob: " + fileName + " table: " + tableId + " id: " + lobId;
}
/**
* Create a temporary CLOB value from a stream.
*
* @param in the reader
* @param length the number of characters to read, or -1 for no limit
* @param handler the data handler
* @return the lob value
*/
public static ValueLobDb createTempClob(Reader in, long length,
DataHandler handler) {
if (length >= 0) {
// Otherwise BufferedReader may try to read more data than needed and that
// blocks the network level
try {
in = new RangeReader(in, 0, length);
} catch (IOException e) {
throw DbException.convert(e);
}
}
BufferedReader reader;
if (in instanceof BufferedReader) {
reader = (BufferedReader) in;
} else {
reader = new BufferedReader(in, Constants.IO_BUFFER_SIZE);
}
try {
boolean compress = handler.getLobCompressionAlgorithm(Value.CLOB) != null;
long remaining = Long.MAX_VALUE;
if (length >= 0 && length < remaining) {
remaining = length;
}
int len = getBufferSize(handler, compress, remaining);
char[] buff;
if (len >= Integer.MAX_VALUE) {
String data = IOUtils.readStringAndClose(reader, -1);
buff = data.toCharArray();
len = buff.length;
} else {
buff = new char[len];
reader.mark(len);
len = IOUtils.readFully(reader, buff, len);
}
if (len <= handler.getMaxLengthInplaceLob()) {
byte[] small = new String(buff, 0, len).getBytes(StandardCharsets.UTF_8);
return ValueLobDb.createSmallLob(Value.CLOB, small, len);
}
reader.reset();
return new ValueLobDb(handler, reader, remaining);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
/**
* Create a temporary BLOB value from a stream.
*
* @param in the input stream
* @param length the number of characters to read, or -1 for no limit
* @param handler the data handler
* @return the lob value
*/
public static ValueLobDb createTempBlob(InputStream in, long length,
DataHandler handler) {
try {
long remaining = Long.MAX_VALUE;
boolean compress = handler.getLobCompressionAlgorithm(Value.BLOB) != null;
if (length >= 0 && length < remaining) {
remaining = length;
}
int len = getBufferSize(handler, compress, remaining);
byte[] buff;
if (len >= Integer.MAX_VALUE) {
buff = IOUtils.readBytesAndClose(in, -1);
len = buff.length;
} else {
buff = Utils.newBytes(len);
len = IOUtils.readFully(in, buff, len);
}
if (len <= handler.getMaxLengthInplaceLob()) {
byte[] small = Utils.copyBytes(buff, len);
return ValueLobDb.createSmallLob(Value.BLOB, small, small.length);
}
return new ValueLobDb(handler, buff, len, in, remaining);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
}
private static int getBufferSize(DataHandler handler, boolean compress,
long remaining) {
if (remaining < 0 || remaining > Integer.MAX_VALUE) {
remaining = Integer.MAX_VALUE;
}
int inplace = handler.getMaxLengthInplaceLob();
long m = compress ? Constants.IO_BUFFER_SIZE_COMPRESS
: Constants.IO_BUFFER_SIZE;
if (m < remaining && m <= inplace) {
// using "1L" to force long arithmetic because
// inplace could be Integer.MAX_VALUE
m = Math.min(remaining, inplace + 1L);
// the buffer size must be bigger than the inplace lob, otherwise we
// can't know if it must be stored in-place or not
m = MathUtils.roundUpLong(m, Constants.IO_BUFFER_SIZE);
}
m = Math.min(remaining, m);
m = MathUtils.convertLongToInt(m);
if (m < 0) {
m = Integer.MAX_VALUE;
}
return (int) m;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (this.precision <= precision) {
return this;
}
ValueLobDb lob;
if (type == CLOB) {
if (handler == null) {
try {
int p = MathUtils.convertLongToInt(precision);
String s = IOUtils.readStringAndClose(getReader(), p);
byte[] data = s.getBytes(StandardCharsets.UTF_8);
lob = ValueLobDb.createSmallLob(type, data, s.length());
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
} else {
lob = ValueLobDb.createTempClob(getReader(), precision, handler);
}
} else {
if (handler == null) {
try {
int p = MathUtils.convertLongToInt(precision);
byte[] data = IOUtils.readBytesAndClose(getInputStream(), p);
lob = ValueLobDb.createSmallLob(type, data, data.length);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
} else {
lob = ValueLobDb.createTempBlob(getInputStream(), precision, handler);
}
}
return lob;
}
/**
* Create a LOB object that fits in memory.
*
* @param type the type (Value.BLOB or CLOB)
* @param small the byte array
* @return the LOB
*/
public static Value createSmallLob(int type, byte[] small) {
int precision;
if (type == Value.CLOB) {
precision = new String(small, StandardCharsets.UTF_8).length();
} else {
precision = small.length;
}
return createSmallLob(type, small, precision);
}
/**
* Create a LOB object that fits in memory.
*
* @param type the type (Value.BLOB or CLOB)
* @param small the byte array
* @param precision the precision
* @return the LOB
*/
public static ValueLobDb createSmallLob(int type, byte[] small,
long precision) {
return new ValueLobDb(type, small, precision);
}
public void setRecoveryReference(boolean isRecoveryReference) {
this.isRecoveryReference = isRecoveryReference;
}
public boolean isRecoveryReference() {
return isRecoveryReference;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueLong.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the BIGINT data type.
*/
public class ValueLong extends Value {
/**
* The smallest {@code ValueLong} value.
*/
public static final ValueLong MIN = get(Long.MIN_VALUE);
/**
* The largest {@code ValueLong} value.
*/
public static final ValueLong MAX = get(Long.MAX_VALUE);
/**
* The largest Long value, as a BigInteger.
*/
public static final BigInteger MAX_BI = BigInteger.valueOf(Long.MAX_VALUE);
/**
* The smallest Long value, as a BigDecimal.
*/
public static final BigDecimal MIN_BD = BigDecimal.valueOf(Long.MIN_VALUE);
/**
* The precision in digits.
*/
public static final int PRECISION = 19;
/**
* The maximum display size of a long.
* Example: 9223372036854775808
*/
public static final int DISPLAY_SIZE = 20;
private static final BigInteger MIN_BI = BigInteger.valueOf(Long.MIN_VALUE);
private static final int STATIC_SIZE = 100;
private static final ValueLong[] STATIC_CACHE;
private final long value;
static {
STATIC_CACHE = new ValueLong[STATIC_SIZE];
for (int i = 0; i < STATIC_SIZE; i++) {
STATIC_CACHE[i] = new ValueLong(i);
}
}
private ValueLong(long value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueLong other = (ValueLong) v;
long result = value + other.value;
int sv = Long.signum(value);
int so = Long.signum(other.value);
int sr = Long.signum(result);
// if the operands have different signs overflow can not occur
// if the operands have the same sign,
// and the result has a different sign, then it is an overflow
// it can not be an overflow when one of the operands is 0
if (sv != so || sr == so || sv == 0 || so == 0) {
return ValueLong.get(result);
}
throw getOverflow();
}
@Override
public int getSignum() {
return Long.signum(value);
}
@Override
public Value negate() {
if (value == Long.MIN_VALUE) {
throw getOverflow();
}
return ValueLong.get(-value);
}
private DbException getOverflow() {
return DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1,
Long.toString(value));
}
@Override
public Value subtract(Value v) {
ValueLong other = (ValueLong) v;
int sv = Long.signum(value);
int so = Long.signum(other.value);
// if the operands have the same sign, then overflow can not occur
// if the second operand is 0, then overflow can not occur
if (sv == so || so == 0) {
return ValueLong.get(value - other.value);
}
// now, if the other value is Long.MIN_VALUE, it must be an overflow
// x - Long.MIN_VALUE overflows for x>=0
return add(other.negate());
}
private static boolean isInteger(long a) {
return a >= Integer.MIN_VALUE && a <= Integer.MAX_VALUE;
}
@Override
public Value multiply(Value v) {
ValueLong other = (ValueLong) v;
long result = value * other.value;
if (value == 0 || value == 1 || other.value == 0 || other.value == 1) {
return ValueLong.get(result);
}
if (isInteger(value) && isInteger(other.value)) {
return ValueLong.get(result);
}
// just checking one case is not enough: Long.MIN_VALUE * -1
// probably this is correct but I'm not sure
// if (result / value == other.value && result / other.value == value) {
// return ValueLong.get(result);
//}
BigInteger bv = BigInteger.valueOf(value);
BigInteger bo = BigInteger.valueOf(other.value);
BigInteger br = bv.multiply(bo);
if (br.compareTo(MIN_BI) < 0 || br.compareTo(MAX_BI) > 0) {
throw getOverflow();
}
return ValueLong.get(br.longValue());
}
@Override
public Value divide(Value v) {
ValueLong other = (ValueLong) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueLong.get(value / other.value);
}
@Override
public Value modulus(Value v) {
ValueLong other = (ValueLong) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueLong.get(this.value % other.value);
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.LONG;
}
@Override
public long getLong() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueLong v = (ValueLong) o;
return Long.compare(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return (int) (value ^ (value >> 32));
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setLong(parameterIndex, value);
}
/**
* Get or create a long value for the given long.
*
* @param i the long
* @return the value
*/
public static ValueLong get(long i) {
if (i >= 0 && i < STATIC_SIZE) {
return STATIC_CACHE[(int) i];
}
return (ValueLong) Value.cache(new ValueLong(i));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueLong && value == ((ValueLong) other).value;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueNull.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import org.h2.engine.Mode;
import org.h2.message.DbException;
/**
* Implementation of NULL. NULL is not a regular data type.
*/
public class ValueNull extends Value {
/**
* The main NULL instance.
*/
public static final ValueNull INSTANCE = new ValueNull();
/**
* This special instance is used as a marker for deleted entries in a map.
* It should not be used anywhere else.
*/
public static final ValueNull DELETED = new ValueNull();
/**
* The precision of NULL.
*/
private static final int PRECISION = 1;
/**
* The display size of the textual representation of NULL.
*/
private static final int DISPLAY_SIZE = 4;
private ValueNull() {
// don't allow construction
}
@Override
public String getSQL() {
return "NULL";
}
@Override
public int getType() {
return Value.NULL;
}
@Override
public String getString() {
return null;
}
@Override
public boolean getBoolean() {
return false;
}
@Override
public Date getDate() {
return null;
}
@Override
public Time getTime() {
return null;
}
@Override
public Timestamp getTimestamp() {
return null;
}
@Override
public byte[] getBytes() {
return null;
}
@Override
public byte getByte() {
return 0;
}
@Override
public short getShort() {
return 0;
}
@Override
public BigDecimal getBigDecimal() {
return null;
}
@Override
public double getDouble() {
return 0.0;
}
@Override
public float getFloat() {
return 0.0F;
}
@Override
public int getInt() {
return 0;
}
@Override
public long getLong() {
return 0;
}
@Override
public InputStream getInputStream() {
return null;
}
@Override
public Reader getReader() {
return null;
}
@Override
public Value convertTo(int type, int precision, Mode mode, Object column, String[] enumerators) {
return this;
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
throw DbException.throwInternalError("compare null");
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return 0;
}
@Override
public Object getObject() {
return null;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setNull(parameterIndex, DataType.convertTypeToSQLType(Value.NULL));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other == this;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueResultSet.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.h2.message.DbException;
import org.h2.tools.SimpleResultSet;
import org.h2.util.StatementBuilder;
/**
* Implementation of the RESULT_SET data type.
*/
public class ValueResultSet extends Value {
private final ResultSet result;
private ValueResultSet(ResultSet rs) {
this.result = rs;
}
/**
* Create a result set value for the given result set.
* The result set will be wrapped.
*
* @param rs the result set
* @return the value
*/
public static ValueResultSet get(ResultSet rs) {
return new ValueResultSet(rs);
}
/**
* Create a result set value for the given result set. The result set will
* be fully read in memory. The original result set is not closed.
*
* @param rs the result set
* @param maxrows the maximum number of rows to read (0 to just read the
* meta data)
* @return the value
*/
public static ValueResultSet getCopy(ResultSet rs, int maxrows) {
try {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
SimpleResultSet simple = new SimpleResultSet();
simple.setAutoClose(false);
ValueResultSet val = new ValueResultSet(simple);
for (int i = 0; i < columnCount; i++) {
String name = meta.getColumnLabel(i + 1);
int sqlType = meta.getColumnType(i + 1);
int precision = meta.getPrecision(i + 1);
int scale = meta.getScale(i + 1);
simple.addColumn(name, sqlType, precision, scale);
}
for (int i = 0; i < maxrows && rs.next(); i++) {
Object[] list = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
list[j] = rs.getObject(j + 1);
}
simple.addRow(list);
}
return val;
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public int getType() {
return Value.RESULT_SET;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
// it doesn't make sense to calculate it
return Integer.MAX_VALUE;
}
@Override
public String getString() {
try {
StatementBuilder buff = new StatementBuilder("(");
result.beforeFirst();
ResultSetMetaData meta = result.getMetaData();
int columnCount = meta.getColumnCount();
for (int i = 0; result.next(); i++) {
if (i > 0) {
buff.append(", ");
}
buff.append('(');
buff.resetCount();
for (int j = 0; j < columnCount; j++) {
buff.appendExceptFirst(", ");
int t = DataType.getValueTypeFromResultSet(meta, j + 1);
Value v = DataType.readValue(null, result, j + 1, t);
buff.append(v.getString());
}
buff.append(')');
}
result.beforeFirst();
return buff.append(')').toString();
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
protected int compareSecure(Value v, CompareMode mode) {
return this == v ? 0 : super.toString().compareTo(v.toString());
}
@Override
public boolean equals(Object other) {
return other == this;
}
@Override
public int hashCode() {
return 0;
}
@Override
public Object getObject() {
return result;
}
@Override
public ResultSet getResultSet() {
return result;
}
@Override
public void set(PreparedStatement prep, int parameterIndex) {
throw throwUnsupportedExceptionForType("PreparedStatement.set");
}
@Override
public String getSQL() {
return "";
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (!force) {
return this;
}
SimpleResultSet rs = new SimpleResultSet();
rs.setAutoClose(false);
return ValueResultSet.get(rs);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueShort.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Implementation of the SMALLINT data type.
*/
public class ValueShort extends Value {
/**
* The precision in digits.
*/
static final int PRECISION = 5;
/**
* The maximum display size of a short.
* Example: -32768
*/
static final int DISPLAY_SIZE = 6;
private final short value;
private ValueShort(short value) {
this.value = value;
}
@Override
public Value add(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value + other.value);
}
private static ValueShort checkRange(int x) {
if (x < Short.MIN_VALUE || x > Short.MAX_VALUE) {
throw DbException.get(ErrorCode.NUMERIC_VALUE_OUT_OF_RANGE_1,
Integer.toString(x));
}
return ValueShort.get((short) x);
}
@Override
public int getSignum() {
return Integer.signum(value);
}
@Override
public Value negate() {
return checkRange(-(int) value);
}
@Override
public Value subtract(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value - other.value);
}
@Override
public Value multiply(Value v) {
ValueShort other = (ValueShort) v;
return checkRange(value * other.value);
}
@Override
public Value divide(Value v) {
ValueShort other = (ValueShort) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueShort.get((short) (value / other.value));
}
@Override
public Value modulus(Value v) {
ValueShort other = (ValueShort) v;
if (other.value == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
return ValueShort.get((short) (value % other.value));
}
@Override
public String getSQL() {
return getString();
}
@Override
public int getType() {
return Value.SHORT;
}
@Override
public short getShort() {
return value;
}
@Override
public int getInt() {
return value;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueShort v = (ValueShort) o;
return Integer.compare(value, v.value);
}
@Override
public String getString() {
return String.valueOf(value);
}
@Override
public long getPrecision() {
return PRECISION;
}
@Override
public int hashCode() {
return value;
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setShort(parameterIndex, value);
}
/**
* Get or create a short value for the given short.
*
* @param i the short
* @return the value
*/
public static ValueShort get(short i) {
return (ValueShort) Value.cache(new ValueShort(i));
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueShort && value == ((ValueShort) other).value;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueString.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.h2.engine.SysProperties;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
/**
* Implementation of the VARCHAR data type.
* It is also the base class for other ValueString* classes.
*/
public class ValueString extends Value {
private static final ValueString EMPTY = new ValueString("");
/**
* The string data.
*/
protected final String value;
protected ValueString(String value) {
this.value = value;
}
@Override
public String getSQL() {
return StringUtils.quoteStringSQL(value);
}
@Override
public boolean equals(Object other) {
return other instanceof ValueString
&& value.equals(((ValueString) other).value);
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
// compatibility: the other object could be another type
ValueString v = (ValueString) o;
return mode.compareString(value, v.value, false);
}
@Override
public String getString() {
return value;
}
@Override
public long getPrecision() {
return value.length();
}
@Override
public Object getObject() {
return value;
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setString(parameterIndex, value);
}
@Override
public int getDisplaySize() {
return value.length();
}
@Override
public int getMemory() {
return value.length() * 2 + 48;
}
@Override
public Value convertPrecision(long precision, boolean force) {
if (precision == 0 || value.length() <= precision) {
return this;
}
int p = MathUtils.convertLongToInt(precision);
return getNew(value.substring(0, p));
}
@Override
public int hashCode() {
// TODO hash performance: could build a quicker hash
// by hashing the size and a few characters
return value.hashCode();
// proposed code:
// private int hash = 0;
//
// public int hashCode() {
// int h = hash;
// if (h == 0) {
// String s = value;
// int l = s.length();
// if (l > 0) {
// if (l < 16)
// h = s.hashCode();
// else {
// h = l;
// for (int i = 1; i <= l; i <<= 1)
// h = 31 *
// (31 * h + s.charAt(i - 1)) +
// s.charAt(l - i);
// }
// hash = h;
// }
// }
// return h;
// }
}
@Override
public int getType() {
return Value.STRING;
}
/**
* Get or create a string value for the given string.
*
* @param s the string
* @return the value
*/
public static Value get(String s) {
return get(s, false);
}
/**
* Get or create a string value for the given string.
*
* @param s the string
* @param treatEmptyStringsAsNull whether or not to treat empty strings as
* NULL
* @return the value
*/
public static Value get(String s, boolean treatEmptyStringsAsNull) {
if (s.isEmpty()) {
return treatEmptyStringsAsNull ? ValueNull.INSTANCE : EMPTY;
}
ValueString obj = new ValueString(StringUtils.cache(s));
if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return Value.cache(obj);
// this saves memory, but is really slow
// return new ValueString(s.intern());
}
/**
* Create a new String value of the current class.
* This method is meant to be overridden by subclasses.
*
* @param s the string
* @return the value
*/
protected Value getNew(String s) {
return ValueString.get(s);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueStringFixed.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.util.Arrays;
import org.h2.engine.Mode;
import org.h2.engine.SysProperties;
import org.h2.util.StringUtils;
/**
* Implementation of the CHAR data type.
*/
public class ValueStringFixed extends ValueString {
/**
* Special value for the precision in {@link #get(String, int, Mode)} to indicate that the value
* should <i>not</i> be trimmed.
*/
public static final int PRECISION_DO_NOT_TRIM = Integer.MIN_VALUE;
/**
* Special value for the precision in {@link #get(String, int, Mode)} to indicate
* that the default behaviour should of trimming the value should apply.
*/
public static final int PRECISION_TRIM = -1;
private static final ValueStringFixed EMPTY = new ValueStringFixed("");
protected ValueStringFixed(String value) {
super(value);
}
private static String trimRight(String s) {
return trimRight(s, 0);
}
private static String trimRight(String s, int minLength) {
int endIndex = s.length() - 1;
int i = endIndex;
while (i >= minLength && s.charAt(i) == ' ') {
i--;
}
s = i == endIndex ? s : s.substring(0, i + 1);
return s;
}
private static String rightPadWithSpaces(String s, int length) {
int pad = length - s.length();
if (pad <= 0) {
return s;
}
char[] res = new char[length];
s.getChars(0, s.length(), res, 0);
Arrays.fill(res, s.length(), length, ' ');
return new String(res);
}
@Override
public int getType() {
return Value.STRING_FIXED;
}
/**
* Get or create a fixed length string value for the given string.
* Spaces at the end of the string will be removed.
*
* @param s the string
* @return the value
*/
public static ValueStringFixed get(String s) {
// Use the special precision constant PRECISION_TRIM to indicate
// default H2 behaviour of trimming the value.
return get(s, PRECISION_TRIM, null);
}
/**
* Get or create a fixed length string value for the given string.
* <p>
* This method will use a {@link Mode}-specific conversion when <code>mode</code> is not
* <code>null</code>.
* Otherwise it will use the default H2 behaviour of trimming the given string if
* <code>precision</code> is not {@link #PRECISION_DO_NOT_TRIM}.
*
* @param s the string
* @param precision if the {@link Mode#padFixedLengthStrings} indicates that strings should
* be padded, this defines the overall length of the (potentially padded) string.
* If the special constant {@link #PRECISION_DO_NOT_TRIM} is used the value will
* not be trimmed.
* @param mode the database mode
* @return the value
*/
public static ValueStringFixed get(String s, int precision, Mode mode) {
// Should fixed strings be padded?
if (mode != null && mode.padFixedLengthStrings) {
if (precision == Integer.MAX_VALUE) {
// CHAR without a length specification is identical to CHAR(1)
precision = 1;
}
if (s.length() < precision) {
// We have to pad
s = rightPadWithSpaces(s, precision);
} else {
// We should trim, because inserting 'A ' into a CHAR(1) is possible!
s = trimRight(s, precision);
}
} else if (precision != PRECISION_DO_NOT_TRIM) {
// Default behaviour of H2
s = trimRight(s);
}
if (s.length() == 0) {
return EMPTY;
}
ValueStringFixed obj = new ValueStringFixed(StringUtils.cache(s));
if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
return (ValueStringFixed) Value.cache(obj);
}
@Override
protected ValueString getNew(String s) {
return ValueStringFixed.get(s);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueStringIgnoreCase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import org.h2.engine.SysProperties;
import org.h2.util.StringUtils;
/**
* Implementation of the VARCHAR_IGNORECASE data type.
*/
public class ValueStringIgnoreCase extends ValueString {
private static final ValueStringIgnoreCase EMPTY =
new ValueStringIgnoreCase("");
private int hash;
protected ValueStringIgnoreCase(String value) {
super(value);
}
@Override
public int getType() {
return Value.STRING_IGNORECASE;
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueStringIgnoreCase v = (ValueStringIgnoreCase) o;
return mode.compareString(value, v.value, true);
}
@Override
public boolean equals(Object other) {
return other instanceof ValueString
&& value.equalsIgnoreCase(((ValueString) other).value);
}
@Override
public int hashCode() {
if (hash == 0) {
// this is locale sensitive
hash = value.toUpperCase().hashCode();
}
return hash;
}
@Override
public String getSQL() {
return "CAST(" + StringUtils.quoteStringSQL(value) + " AS VARCHAR_IGNORECASE)";
}
/**
* Get or create a case insensitive string value for the given string.
* The value will have the same case as the passed string.
*
* @param s the string
* @return the value
*/
public static ValueStringIgnoreCase get(String s) {
if (s.length() == 0) {
return EMPTY;
}
ValueStringIgnoreCase obj = new ValueStringIgnoreCase(StringUtils.cache(s));
if (s.length() > SysProperties.OBJECT_CACHE_MAX_PER_ELEMENT_SIZE) {
return obj;
}
ValueStringIgnoreCase cache = (ValueStringIgnoreCase) Value.cache(obj);
// the cached object could have the wrong case
// (it would still be 'equal', but we don't like to store it)
if (cache.value.equals(s)) {
return cache;
}
return obj;
}
@Override
protected ValueString getNew(String s) {
return ValueStringIgnoreCase.get(s);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueTime.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import org.h2.api.ErrorCode;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.util.DateTimeUtils;
/**
* Implementation of the TIME data type.
*/
public class ValueTime extends Value {
/**
* The default precision and display size of the textual representation of a time.
* Example: 10:00:00
*/
public static final int DEFAULT_PRECISION = 8;
/**
* The maximum precision and display size of the textual representation of a time.
* Example: 10:00:00.123456789
*/
public static final int MAXIMUM_PRECISION = 18;
/**
* The default scale for time.
*/
static final int DEFAULT_SCALE = 0;
/**
* The maximum scale for time.
*/
public static final int MAXIMUM_SCALE = 9;
/**
* Get display size for the specified scale.
*
* @param scale scale
* @return display size
*/
public static int getDisplaySize(int scale) {
return scale == 0 ? 8 : 9 + scale;
}
/**
* Nanoseconds since midnight
*/
private final long nanos;
/**
* @param nanos nanoseconds since midnight
*/
private ValueTime(long nanos) {
this.nanos = nanos;
}
/**
* Get or create a time value.
*
* @param nanos the nanoseconds since midnight
* @return the value
*/
public static ValueTime fromNanos(long nanos) {
if (!SysProperties.UNLIMITED_TIME_RANGE) {
if (nanos < 0L || nanos >= DateTimeUtils.NANOS_PER_DAY) {
StringBuilder builder = new StringBuilder();
DateTimeUtils.appendTime(builder, nanos);
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2,
"TIME", builder.toString());
}
}
return (ValueTime) Value.cache(new ValueTime(nanos));
}
/**
* Get or create a time value for the given time.
*
* @param time the time
* @return the value
*/
public static ValueTime get(Time time) {
return fromNanos(DateTimeUtils.nanosFromDate(time.getTime()));
}
/**
* Calculate the time value from a given time in
* milliseconds in UTC.
*
* @param ms the milliseconds
* @return the value
*/
public static ValueTime fromMillis(long ms) {
return fromNanos(DateTimeUtils.nanosFromDate(ms));
}
/**
* Parse a string to a ValueTime.
*
* @param s the string to parse
* @return the time
*/
public static ValueTime parse(String s) {
try {
return fromNanos(DateTimeUtils.parseTimeNanos(s, 0, s.length(), false));
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2,
e, "TIME", s);
}
}
/**
* @return nanoseconds since midnight
*/
public long getNanos() {
return nanos;
}
@Override
public Time getTime() {
return DateTimeUtils.convertNanoToTime(nanos);
}
@Override
public int getType() {
return Value.TIME;
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(MAXIMUM_PRECISION);
DateTimeUtils.appendTime(buff, nanos);
return buff.toString();
}
@Override
public String getSQL() {
return "TIME '" + getString() + "'";
}
@Override
public long getPrecision() {
return MAXIMUM_PRECISION;
}
@Override
public int getDisplaySize() {
return MAXIMUM_PRECISION;
}
@Override
public boolean checkPrecision(long precision) {
// TIME data type does not have precision parameter
return true;
}
@Override
public Value convertScale(boolean onlyToSmallerScale, int targetScale) {
if (targetScale >= MAXIMUM_SCALE) {
return this;
}
if (targetScale < 0) {
throw DbException.getInvalidValueException("scale", targetScale);
}
long n = nanos;
long n2 = DateTimeUtils.convertScale(n, targetScale);
if (n2 == n) {
return this;
}
if (n2 >= DateTimeUtils.NANOS_PER_DAY) {
n2 = DateTimeUtils.NANOS_PER_DAY - 1;
}
return fromNanos(n2);
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
return Long.compare(nanos, ((ValueTime) o).nanos);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
return other instanceof ValueTime && nanos == (((ValueTime) other).nanos);
}
@Override
public int hashCode() {
return (int) (nanos ^ (nanos >>> 32));
}
@Override
public Object getObject() {
return getTime();
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setTime(parameterIndex, getTime());
}
@Override
public Value add(Value v) {
ValueTime t = (ValueTime) v.convertTo(Value.TIME);
return ValueTime.fromNanos(nanos + t.getNanos());
}
@Override
public Value subtract(Value v) {
ValueTime t = (ValueTime) v.convertTo(Value.TIME);
return ValueTime.fromNanos(nanos - t.getNanos());
}
@Override
public Value multiply(Value v) {
return ValueTime.fromNanos((long) (nanos * v.getDouble()));
}
@Override
public Value divide(Value v) {
return ValueTime.fromNanos((long) (nanos / v.getDouble()));
}
@Override
public int getSignum() {
return Long.signum(nanos);
}
@Override
public Value negate() {
return ValueTime.fromNanos(-nanos);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueTimestamp.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.h2.api.ErrorCode;
import org.h2.engine.Mode;
import org.h2.message.DbException;
import org.h2.util.DateTimeUtils;
/**
* Implementation of the TIMESTAMP data type.
*/
public class ValueTimestamp extends Value {
/**
* The default precision and display size of the textual representation of a timestamp.
* Example: 2001-01-01 23:59:59.123456
*/
public static final int DEFAULT_PRECISION = 26;
/**
* The maximum precision and display size of the textual representation of a timestamp.
* Example: 2001-01-01 23:59:59.123456789
*/
public static final int MAXIMUM_PRECISION = 29;
/**
* The default scale for timestamps.
*/
static final int DEFAULT_SCALE = 6;
/**
* The maximum scale for timestamps.
*/
public static final int MAXIMUM_SCALE = 9;
/**
* Get display size for the specified scale.
*
* @param scale scale
* @return display size
*/
public static int getDisplaySize(int scale) {
return scale == 0 ? 19 : 20 + scale;
}
/**
* A bit field with bits for the year, month, and day (see DateTimeUtils for
* encoding)
*/
private final long dateValue;
/**
* The nanoseconds since midnight.
*/
private final long timeNanos;
private ValueTimestamp(long dateValue, long timeNanos) {
this.dateValue = dateValue;
if (timeNanos < 0 || timeNanos >= DateTimeUtils.NANOS_PER_DAY) {
throw new IllegalArgumentException("timeNanos out of range " + timeNanos);
}
this.timeNanos = timeNanos;
}
/**
* Get or create a date value for the given date.
*
* @param dateValue the date value, a bit field with bits for the year,
* month, and day
* @param timeNanos the nanoseconds since midnight
* @return the value
*/
public static ValueTimestamp fromDateValueAndNanos(long dateValue, long timeNanos) {
return (ValueTimestamp) Value.cache(new ValueTimestamp(dateValue, timeNanos));
}
/**
* Get or create a timestamp value for the given timestamp.
*
* @param timestamp the timestamp
* @return the value
*/
public static ValueTimestamp get(Timestamp timestamp) {
long ms = timestamp.getTime();
long nanos = timestamp.getNanos() % 1_000_000;
long dateValue = DateTimeUtils.dateValueFromDate(ms);
nanos += DateTimeUtils.nanosFromDate(ms);
return fromDateValueAndNanos(dateValue, nanos);
}
/**
* Get or create a timestamp value for the given date/time in millis.
*
* @param ms the milliseconds
* @param nanos the nanoseconds
* @return the value
*/
public static ValueTimestamp fromMillisNanos(long ms, int nanos) {
long dateValue = DateTimeUtils.dateValueFromDate(ms);
long timeNanos = nanos + DateTimeUtils.nanosFromDate(ms);
return fromDateValueAndNanos(dateValue, timeNanos);
}
/**
* Get or create a timestamp value for the given date/time in millis.
*
* @param ms the milliseconds
* @return the value
*/
public static ValueTimestamp fromMillis(long ms) {
long dateValue = DateTimeUtils.dateValueFromDate(ms);
long nanos = DateTimeUtils.nanosFromDate(ms);
return fromDateValueAndNanos(dateValue, nanos);
}
/**
* Parse a string to a ValueTimestamp. This method supports the format
* +/-year-month-day hour[:.]minute[:.]seconds.fractional and an optional timezone
* part.
*
* @param s the string to parse
* @return the date
*/
public static ValueTimestamp parse(String s) {
return parse(s, null);
}
/**
* Parse a string to a ValueTimestamp, using the given {@link Mode}.
* This method supports the format +/-year-month-day[ -]hour[:.]minute[:.]seconds.fractional
* and an optional timezone part.
*
* @param s the string to parse
* @param mode the database {@link Mode}
* @return the date
*/
public static ValueTimestamp parse(String s, Mode mode) {
try {
return (ValueTimestamp) DateTimeUtils.parseTimestamp(s, mode, false);
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2,
e, "TIMESTAMP", s);
}
}
/**
* A bit field with bits for the year, month, and day (see DateTimeUtils for
* encoding).
*
* @return the data value
*/
public long getDateValue() {
return dateValue;
}
/**
* The nanoseconds since midnight.
*
* @return the nanoseconds
*/
public long getTimeNanos() {
return timeNanos;
}
@Override
public Timestamp getTimestamp() {
return DateTimeUtils.convertDateValueToTimestamp(dateValue, timeNanos);
}
@Override
public int getType() {
return Value.TIMESTAMP;
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(MAXIMUM_PRECISION);
DateTimeUtils.appendDate(buff, dateValue);
buff.append(' ');
DateTimeUtils.appendTime(buff, timeNanos);
return buff.toString();
}
@Override
public String getSQL() {
return "TIMESTAMP '" + getString() + "'";
}
@Override
public long getPrecision() {
return MAXIMUM_PRECISION;
}
@Override
public int getScale() {
return MAXIMUM_SCALE;
}
@Override
public int getDisplaySize() {
return MAXIMUM_PRECISION;
}
@Override
public boolean checkPrecision(long precision) {
// TIMESTAMP data type does not have precision parameter
return true;
}
@Override
public Value convertScale(boolean onlyToSmallerScale, int targetScale) {
if (targetScale >= MAXIMUM_SCALE) {
return this;
}
if (targetScale < 0) {
throw DbException.getInvalidValueException("scale", targetScale);
}
long n = timeNanos;
long n2 = DateTimeUtils.convertScale(n, targetScale);
if (n2 == n) {
return this;
}
long dv = dateValue;
if (n2 >= DateTimeUtils.NANOS_PER_DAY) {
n2 -= DateTimeUtils.NANOS_PER_DAY;
dv = DateTimeUtils.incrementDateValue(dv);
}
return fromDateValueAndNanos(dv, n2);
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueTimestamp t = (ValueTimestamp) o;
int c = Long.compare(dateValue, t.dateValue);
if (c != 0) {
return c;
}
return Long.compare(timeNanos, t.timeNanos);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (!(other instanceof ValueTimestamp)) {
return false;
}
ValueTimestamp x = (ValueTimestamp) other;
return dateValue == x.dateValue && timeNanos == x.timeNanos;
}
@Override
public int hashCode() {
return (int) (dateValue ^ (dateValue >>> 32) ^ timeNanos ^ (timeNanos >>> 32));
}
@Override
public Object getObject() {
return getTimestamp();
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setTimestamp(parameterIndex, getTimestamp());
}
@Override
public Value add(Value v) {
ValueTimestamp t = (ValueTimestamp) v.convertTo(Value.TIMESTAMP);
long d1 = DateTimeUtils.absoluteDayFromDateValue(dateValue);
long d2 = DateTimeUtils.absoluteDayFromDateValue(t.dateValue);
return DateTimeUtils.normalizeTimestamp(d1 + d2, timeNanos + t.timeNanos);
}
@Override
public Value subtract(Value v) {
ValueTimestamp t = (ValueTimestamp) v.convertTo(Value.TIMESTAMP);
long d1 = DateTimeUtils.absoluteDayFromDateValue(dateValue);
long d2 = DateTimeUtils.absoluteDayFromDateValue(t.dateValue);
return DateTimeUtils.normalizeTimestamp(d1 - d2, timeNanos - t.timeNanos);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueTimestampTimeZone.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0, and the
* EPL 1.0 (http://h2database.com/html/license.html). Initial Developer: H2
* Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import org.h2.api.ErrorCode;
import org.h2.api.TimestampWithTimeZone;
import org.h2.message.DbException;
import org.h2.util.DateTimeUtils;
/**
* Implementation of the TIMESTAMP WITH TIME ZONE data type.
*
* @see <a href="https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators">
* ISO 8601 Time zone designators</a>
*/
public class ValueTimestampTimeZone extends Value {
/**
* The default precision and display size of the textual representation of a timestamp.
* Example: 2001-01-01 23:59:59.123456+10:00
*/
public static final int DEFAULT_PRECISION = 32;
/**
* The maximum precision and display size of the textual representation of a timestamp.
* Example: 2001-01-01 23:59:59.123456789+10:00
*/
public static final int MAXIMUM_PRECISION = 35;
/**
* The default scale for timestamps.
*/
static final int DEFAULT_SCALE = ValueTimestamp.DEFAULT_SCALE;
/**
* The default scale for timestamps.
*/
static final int MAXIMUM_SCALE = ValueTimestamp.MAXIMUM_SCALE;
/**
* Get display size for the specified scale.
*
* @param scale scale
* @return display size
*/
public static int getDisplaySize(int scale) {
return scale == 0 ? 25 : 26 + scale;
}
/**
* A bit field with bits for the year, month, and day (see DateTimeUtils for
* encoding)
*/
private final long dateValue;
/**
* The nanoseconds since midnight.
*/
private final long timeNanos;
/**
* Time zone offset from UTC in minutes, range of -18 hours to +18 hours. This
* range is compatible with OffsetDateTime from JSR-310.
*/
private final short timeZoneOffsetMins;
private ValueTimestampTimeZone(long dateValue, long timeNanos,
short timeZoneOffsetMins) {
if (timeNanos < 0 || timeNanos >= DateTimeUtils.NANOS_PER_DAY) {
throw new IllegalArgumentException(
"timeNanos out of range " + timeNanos);
}
/*
* Some current and historic time zones have offsets larger than 12 hours.
* JSR-310 determines 18 hours as maximum possible offset in both directions, so
* we use this limit too for compatibility.
*/
if (timeZoneOffsetMins < (-18 * 60)
|| timeZoneOffsetMins > (18 * 60)) {
throw new IllegalArgumentException(
"timeZoneOffsetMins out of range " + timeZoneOffsetMins);
}
this.dateValue = dateValue;
this.timeNanos = timeNanos;
this.timeZoneOffsetMins = timeZoneOffsetMins;
}
/**
* Get or create a date value for the given date.
*
* @param dateValue the date value, a bit field with bits for the year,
* month, and day
* @param timeNanos the nanoseconds since midnight
* @param timeZoneOffsetMins the timezone offset in minutes
* @return the value
*/
public static ValueTimestampTimeZone fromDateValueAndNanos(long dateValue,
long timeNanos, short timeZoneOffsetMins) {
return (ValueTimestampTimeZone) Value.cache(new ValueTimestampTimeZone(
dateValue, timeNanos, timeZoneOffsetMins));
}
/**
* Get or create a timestamp value for the given timestamp.
*
* @param timestamp the timestamp
* @return the value
*/
public static ValueTimestampTimeZone get(TimestampWithTimeZone timestamp) {
return fromDateValueAndNanos(timestamp.getYMD(),
timestamp.getNanosSinceMidnight(),
timestamp.getTimeZoneOffsetMins());
}
/**
* Parse a string to a ValueTimestamp. This method supports the format
* +/-year-month-day hour:minute:seconds.fractional and an optional timezone
* part.
*
* @param s the string to parse
* @return the date
*/
public static ValueTimestampTimeZone parse(String s) {
try {
return (ValueTimestampTimeZone) DateTimeUtils.parseTimestamp(s, null, true);
} catch (Exception e) {
throw DbException.get(ErrorCode.INVALID_DATETIME_CONSTANT_2, e,
"TIMESTAMP WITH TIME ZONE", s);
}
}
/**
* A bit field with bits for the year, month, and day (see DateTimeUtils for
* encoding).
*
* @return the data value
*/
public long getDateValue() {
return dateValue;
}
/**
* The nanoseconds since midnight.
*
* @return the nanoseconds
*/
public long getTimeNanos() {
return timeNanos;
}
/**
* The timezone offset in minutes.
*
* @return the offset
*/
public short getTimeZoneOffsetMins() {
return timeZoneOffsetMins;
}
@Override
public Timestamp getTimestamp() {
return DateTimeUtils.convertTimestampTimeZoneToTimestamp(dateValue, timeNanos, timeZoneOffsetMins);
}
@Override
public int getType() {
return Value.TIMESTAMP_TZ;
}
@Override
public String getString() {
return DateTimeUtils.timestampTimeZoneToString(dateValue, timeNanos, timeZoneOffsetMins);
}
@Override
public String getSQL() {
return "TIMESTAMP WITH TIME ZONE '" + getString() + "'";
}
@Override
public long getPrecision() {
return MAXIMUM_PRECISION;
}
@Override
public int getScale() {
return MAXIMUM_SCALE;
}
@Override
public int getDisplaySize() {
return MAXIMUM_PRECISION;
}
@Override
public boolean checkPrecision(long precision) {
// TIMESTAMP WITH TIME ZONE data type does not have precision parameter
return true;
}
@Override
public Value convertScale(boolean onlyToSmallerScale, int targetScale) {
if (targetScale >= MAXIMUM_SCALE) {
return this;
}
if (targetScale < 0) {
throw DbException.getInvalidValueException("scale", targetScale);
}
long n = timeNanos;
long n2 = DateTimeUtils.convertScale(n, targetScale);
if (n2 == n) {
return this;
}
long dv = dateValue;
if (n2 >= DateTimeUtils.NANOS_PER_DAY) {
n2 -= DateTimeUtils.NANOS_PER_DAY;
dv = DateTimeUtils.incrementDateValue(dv);
}
return fromDateValueAndNanos(dv, n2, timeZoneOffsetMins);
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
ValueTimestampTimeZone t = (ValueTimestampTimeZone) o;
// Maximum time zone offset is +/-18 hours so difference in days between local
// and UTC cannot be more than one day
long dateValueA = dateValue;
long timeA = timeNanos - timeZoneOffsetMins * 60_000_000_000L;
if (timeA < 0) {
timeA += DateTimeUtils.NANOS_PER_DAY;
dateValueA = DateTimeUtils.decrementDateValue(dateValueA);
} else if (timeA >= DateTimeUtils.NANOS_PER_DAY) {
timeA -= DateTimeUtils.NANOS_PER_DAY;
dateValueA = DateTimeUtils.incrementDateValue(dateValueA);
}
long dateValueB = t.dateValue;
long timeB = t.timeNanos - t.timeZoneOffsetMins * 60_000_000_000L;
if (timeB < 0) {
timeB += DateTimeUtils.NANOS_PER_DAY;
dateValueB = DateTimeUtils.decrementDateValue(dateValueB);
} else if (timeB >= DateTimeUtils.NANOS_PER_DAY) {
timeB -= DateTimeUtils.NANOS_PER_DAY;
dateValueB = DateTimeUtils.incrementDateValue(dateValueB);
}
int cmp = Long.compare(dateValueA, dateValueB);
if (cmp != 0) {
return cmp;
}
return Long.compare(timeA, timeB);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (!(other instanceof ValueTimestampTimeZone)) {
return false;
}
ValueTimestampTimeZone x = (ValueTimestampTimeZone) other;
return dateValue == x.dateValue && timeNanos == x.timeNanos
&& timeZoneOffsetMins == x.timeZoneOffsetMins;
}
@Override
public int hashCode() {
return (int) (dateValue ^ (dateValue >>> 32) ^ timeNanos
^ (timeNanos >>> 32) ^ timeZoneOffsetMins);
}
@Override
public Object getObject() {
return new TimestampWithTimeZone(dateValue, timeNanos,
timeZoneOffsetMins);
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setString(parameterIndex, getString());
}
@Override
public Value add(Value v) {
throw DbException.getUnsupportedException(
"manipulating TIMESTAMP WITH TIME ZONE values is unsupported");
}
@Override
public Value subtract(Value v) {
throw DbException.getUnsupportedException(
"manipulating TIMESTAMP WITH TIME ZONE values is unsupported");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/value/ValueUuid.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.value;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.UUID;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.util.Bits;
import org.h2.util.MathUtils;
import org.h2.util.StringUtils;
/**
* Implementation of the UUID data type.
*/
public class ValueUuid extends Value {
/**
* The precision of this value in number of bytes.
*/
private static final int PRECISION = 16;
/**
* The display size of the textual representation of a UUID.
* Example: cd38d882-7ada-4589-b5fb-7da0ca559d9a
*/
private static final int DISPLAY_SIZE = 36;
private final long high, low;
private ValueUuid(long high, long low) {
this.high = high;
this.low = low;
}
@Override
public int hashCode() {
return (int) ((high >>> 32) ^ high ^ (low >>> 32) ^ low);
}
/**
* Create a new UUID using the pseudo random number generator.
*
* @return the new UUID
*/
public static ValueUuid getNewRandom() {
long high = MathUtils.secureRandomLong();
long low = MathUtils.secureRandomLong();
// version 4 (random)
high = (high & (~0xf000L)) | 0x4000L;
// variant (Leach-Salz)
low = (low & 0x3fff_ffff_ffff_ffffL) | 0x8000_0000_0000_0000L;
return new ValueUuid(high, low);
}
/**
* Get or create a UUID for the given 16 bytes.
*
* @param binary the byte array (must be at least 16 bytes long)
* @return the UUID
*/
public static ValueUuid get(byte[] binary) {
if (binary.length < 16) {
return get(StringUtils.convertBytesToHex(binary));
}
long high = Bits.readLong(binary, 0);
long low = Bits.readLong(binary, 8);
return (ValueUuid) Value.cache(new ValueUuid(high, low));
}
/**
* Get or create a UUID for the given high and low order values.
*
* @param high the most significant bits
* @param low the least significant bits
* @return the UUID
*/
public static ValueUuid get(long high, long low) {
return (ValueUuid) Value.cache(new ValueUuid(high, low));
}
/**
* Get or create a UUID for the given Java UUID.
*
* @param uuid Java UUID
* @return the UUID
*/
public static ValueUuid get(UUID uuid) {
return get(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
}
/**
* Get or create a UUID for the given text representation.
*
* @param s the text representation of the UUID
* @return the UUID
*/
public static ValueUuid get(String s) {
long low = 0, high = 0;
for (int i = 0, j = 0, length = s.length(); i < length; i++) {
char c = s.charAt(i);
if (c >= '0' && c <= '9') {
low = (low << 4) | (c - '0');
} else if (c >= 'a' && c <= 'f') {
low = (low << 4) | (c - 'a' + 0xa);
} else if (c == '-') {
continue;
} else if (c >= 'A' && c <= 'F') {
low = (low << 4) | (c - 'A' + 0xa);
} else if (c <= ' ') {
continue;
} else {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, s);
}
if (j++ == 15) {
high = low;
low = 0;
}
}
return (ValueUuid) Value.cache(new ValueUuid(high, low));
}
@Override
public String getSQL() {
return StringUtils.quoteStringSQL(getString());
}
@Override
public int getType() {
return Value.UUID;
}
@Override
public long getPrecision() {
return PRECISION;
}
private static void appendHex(StringBuilder buff, long x, int bytes) {
for (int i = bytes * 8 - 4; i >= 0; i -= 8) {
buff.append(Integer.toHexString((int) (x >> i) & 0xf)).
append(Integer.toHexString((int) (x >> (i - 4)) & 0xf));
}
}
@Override
public String getString() {
StringBuilder buff = new StringBuilder(36);
appendHex(buff, high >> 32, 4);
buff.append('-');
appendHex(buff, high >> 16, 2);
buff.append('-');
appendHex(buff, high, 2);
buff.append('-');
appendHex(buff, low >> 48, 2);
buff.append('-');
appendHex(buff, low, 6);
return buff.toString();
}
@Override
protected int compareSecure(Value o, CompareMode mode) {
if (o == this) {
return 0;
}
ValueUuid v = (ValueUuid) o;
if (high == v.high) {
return Long.compare(low, v.low);
}
return high > v.high ? 1 : -1;
}
@Override
public boolean equals(Object other) {
return other instanceof ValueUuid && compareSecure((Value) other, null) == 0;
}
@Override
public Object getObject() {
return new UUID(high, low);
}
@Override
public byte[] getBytes() {
return Bits.uuidToBytes(high, low);
}
@Override
public void set(PreparedStatement prep, int parameterIndex)
throws SQLException {
prep.setBytes(parameterIndex, getBytes());
}
/**
* Get the most significant 64 bits of this UUID.
*
* @return the high order bits
*/
public long getHigh() {
return high;
}
/**
* Get the least significant 64 bits of this UUID.
*
* @return the low order bits
*/
public long getLow() {
return low;
}
@Override
public int getDisplaySize() {
return DISPLAY_SIZE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-index/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-index/3.0.15/ai/platon/pulsar/index/package-info.java
|
package ai.platon.pulsar.index;
/*
* The pulsar-index plugin
* */
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/ai/platon/pulsar/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/ai/platon/pulsar/jsoup/ext/NodeExt.java
|
/*
* Copyright (c) 2022.
*
* This program is free software: you can use, redistribute, and/or modify
* it under the terms of the GNU Affero General Public License, version 3
* or later ("AGPL"), as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ai.platon.pulsar.jsoup.ext;
import org.apache.commons.math3.linear.OpenMapRealVector;
import org.apache.commons.math3.linear.RealVector;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The pulsar extension.
*
* We have two modifications to jsoup:
* 1. add NodeExt to Node
* 2. make NodeVisitor and NodeFilter compatible with kotlin lambda
* */
public class NodeExt {
public static final RealVector EMPTY_FEATURE = new OpenMapRealVector();
private final Node node;
private Node ownerDocumentNode;
private Node ownerBody;
private String immutableText;
private RealVector features;
private Map<String, Object> variables;
private Map<String, List<Object>> tuples;
public NodeExt(Node node) {
this.node = node;
}
public void removeAttrs(String... attrNames) {
for (String attrName : attrNames) {
node.removeAttr(attrName);
}
}
public Node getOwnerDocumentNode() {
if (ownerDocumentNode == null) {
ownerDocumentNode = node.ownerDocument();
}
return ownerDocumentNode;
}
public void setOwnerDocumentNode(Node ownerDocumentNode) {
this.ownerDocumentNode = ownerDocumentNode;
}
public Node getOwnerBody() {
if (ownerBody == null) {
Document document = node.ownerDocument();
if (document != null) {
ownerBody = document.body();
}
}
return ownerBody;
}
public void setOwnerBody(Node ownerBody) {
this.ownerBody = ownerBody;
}
@Nonnull
public String getImmutableText() {
if (immutableText == null) {
immutableText = "";
}
return immutableText;
}
public void setImmutableText(String immutableText) {
this.immutableText = immutableText;
}
@Nonnull
public RealVector getFeatures() {
if (features == null) {
features = new OpenMapRealVector();
}
return features;
}
public void setFeatures(RealVector features) {
this.features = features;
}
@Nonnull
public Map<String, Object> getVariables() {
if (variables == null) {
variables = new HashMap<>();
}
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
@Nonnull
public Map<String, List<Object>> getTuples() {
if (tuples == null) {
tuples = new HashMap<>();
}
return tuples;
}
public void setTuples(Map<String, List<Object>> tuples) {
this.tuples = tuples;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/Connection.java
|
package org.jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import javax.annotation.Nullable;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CookieStore;
import java.net.Proxy;
import java.net.URL;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
The Connection interface is a convenient HTTP client and session object to fetch content from the web, and parse them
into Documents.
<p>To start a new session, use either {@link org.jsoup.Jsoup#newSession()} or {@link org.jsoup.Jsoup#connect(String)}.
Connections contain {@link Connection.Request} and {@link Connection.Response} objects (once executed). Configuration
settings (URL, timeout, useragent, etc) set on a session will be applied by default to each subsequent request.</p>
<p>To start a new request from the session, use {@link #newRequest()}.</p>
<p>Cookies are stored in memory for the duration of the session. For that reason, do not use one single session for all
requests in a long-lived application, or you are likely to run out of memory, unless care is taken to clean up the
cookie store. The cookie store for the session is available via {@link #cookieStore()}. You may provide your own
implementation via {@link #cookieStore(java.net.CookieStore)} before making requests.</p>
<p>Request configuration can be made using either the shortcut methods in Connection (e.g. {@link #userAgent(String)}),
or by methods in the Connection.Request object directly. All request configuration must be made before the request is
executed. When used as an ongoing session, initialize all defaults prior to making multi-threaded {@link
#newRequest()}s.</p>
<p>Note that the term "Connection" used here does not mean that a long-lived connection is held against a server for
the lifetime of the Connection object. A socket connection is only made at the point of request execution ({@link
#execute()}, {@link #get()}, or {@link #post()}), and the server's response consumed.</p>
<p>For multi-threaded implementations, it is important to use a {@link #newRequest()} for each request. The session may
be shared across threads but a given request, not.</p>
*/
@SuppressWarnings("unused")
public interface Connection {
/**
* GET and POST http methods.
*/
enum Method {
GET(false), POST(true), PUT(true), DELETE(false), PATCH(true), HEAD(false), OPTIONS(false), TRACE(false);
private final boolean hasBody;
Method(boolean hasBody) {
this.hasBody = hasBody;
}
/**
* Check if this HTTP method has/needs a request body
* @return if body needed
*/
public final boolean hasBody() {
return hasBody;
}
}
/**
Creates a new request, using this Connection as the session-state and to initialize the connection settings (which may then be independently on the returned Connection.Request object).
@return a new Connection object, with a shared Cookie Store and initialized settings from this Connection and Request
@since 1.14.1
*/
Connection newRequest();
/**
* Set the request URL to fetch. The protocol must be HTTP or HTTPS.
* @param url URL to connect to
* @return this Connection, for chaining
*/
Connection url(URL url);
/**
* Set the request URL to fetch. The protocol must be HTTP or HTTPS.
* @param url URL to connect to
* @return this Connection, for chaining
*/
Connection url(String url);
/**
* Set the proxy to use for this request. Set to <code>null</code> to disable a previously set proxy.
* @param proxy proxy to use
* @return this Connection, for chaining
*/
Connection proxy(@Nullable Proxy proxy);
/**
* Set the HTTP proxy to use for this request.
* @param host the proxy hostname
* @param port the proxy port
* @return this Connection, for chaining
*/
Connection proxy(String host, int port);
/**
* Set the request user-agent header.
* @param userAgent user-agent to use
* @return this Connection, for chaining
* @see org.jsoup.helper.HttpConnection#DEFAULT_UA
*/
Connection userAgent(String userAgent);
/**
* Set the total request timeout duration. If a timeout occurs, an {@link java.net.SocketTimeoutException} will be thrown.
* <p>The default timeout is <b>30 seconds</b> (30,000 millis). A timeout of zero is treated as an infinite timeout.
* <p>Note that this timeout specifies the combined maximum duration of the connection time and the time to read
* the full response.
* @param millis number of milliseconds (thousandths of a second) before timing out connects or reads.
* @return this Connection, for chaining
* @see #maxBodySize(int)
*/
Connection timeout(int millis);
/**
* Set the maximum bytes to read from the (uncompressed) connection into the body, before the connection is closed,
* and the input truncated (i.e. the body content will be trimmed). <b>The default maximum is 2MB</b>. A max size of
* <code>0</code> is treated as an infinite amount (bounded only by your patience and the memory available on your
* machine).
*
* @param bytes number of bytes to read from the input before truncating
* @return this Connection, for chaining
*/
Connection maxBodySize(int bytes);
/**
* Set the request referrer (aka "referer") header.
* @param referrer referrer to use
* @return this Connection, for chaining
*/
Connection referrer(String referrer);
/**
* Configures the connection to (not) follow server redirects. By default this is <b>true</b>.
* @param followRedirects true if server redirects should be followed.
* @return this Connection, for chaining
*/
Connection followRedirects(boolean followRedirects);
/**
* Set the request method to use, GET or POST. Default is GET.
* @param method HTTP request method
* @return this Connection, for chaining
*/
Connection method(Method method);
/**
* Configures the connection to not throw exceptions when a HTTP error occurs. (4xx - 5xx, e.g. 404 or 500). By
* default this is <b>false</b>; an IOException is thrown if an error is encountered. If set to <b>true</b>, the
* response is populated with the error body, and the status message will reflect the error.
* @param ignoreHttpErrors - false (default) if HTTP errors should be ignored.
* @return this Connection, for chaining
*/
Connection ignoreHttpErrors(boolean ignoreHttpErrors);
/**
* Ignore the document's Content-Type when parsing the response. By default this is <b>false</b>, an unrecognised
* content-type will cause an IOException to be thrown. (This is to prevent producing garbage by attempting to parse
* a JPEG binary image, for example.) Set to true to force a parse attempt regardless of content type.
* @param ignoreContentType set to true if you would like the content type ignored on parsing the response into a
* Document.
* @return this Connection, for chaining
*/
Connection ignoreContentType(boolean ignoreContentType);
/**
* Set custom SSL socket factory
* @param sslSocketFactory custom SSL socket factory
* @return this Connection, for chaining
*/
Connection sslSocketFactory(SSLSocketFactory sslSocketFactory);
/**
* Add a request data parameter. Request parameters are sent in the request query string for GETs, and in the
* request body for POSTs. A request may have multiple values of the same name.
* @param key data key
* @param value data value
* @return this Connection, for chaining
*/
Connection data(String key, String value);
/**
* Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
* input stream.
* @param key data key (form item name)
* @param filename the name of the file to present to the remove server. Typically just the name, not path,
* component.
* @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
* You must close the InputStream in a {@code finally} block.
* @return this Connections, for chaining
* @see #data(String, String, InputStream, String) if you want to set the uploaded file's mimetype.
*/
Connection data(String key, String filename, InputStream inputStream);
/**
* Add an input stream as a request data parameter. For GETs, has no effect, but for POSTS this will upload the
* input stream.
* @param key data key (form item name)
* @param filename the name of the file to present to the remove server. Typically just the name, not path,
* component.
* @param inputStream the input stream to upload, that you probably obtained from a {@link java.io.FileInputStream}.
* @param contentType the Content Type (aka mimetype) to specify for this file.
* You must close the InputStream in a {@code finally} block.
* @return this Connections, for chaining
*/
Connection data(String key, String filename, InputStream inputStream, String contentType);
/**
* Adds all of the supplied data to the request data parameters
* @param data collection of data parameters
* @return this Connection, for chaining
*/
Connection data(Collection<KeyVal> data);
/**
* Adds all of the supplied data to the request data parameters
* @param data map of data parameters
* @return this Connection, for chaining
*/
Connection data(Map<String, String> data);
/**
Add one or more request {@code key, val} data parameter pairs.<p>Multiple parameters may be set at once, e.g.:
<code>.data("name", "jsoup", "language", "Java", "language", "English");</code> creates a query string like:
<code>{@literal ?name=jsoup&language=Java&language=English}</code></p>
<p>For GET requests, data parameters will be sent on the request query string. For POST (and other methods that
contain a body), they will be sent as body form parameters, unless the body is explicitly set by {@link
#requestBody(String)}, in which case they will be query string parameters.</p>
@param keyvals a set of key value pairs.
@return this Connection, for chaining
*/
Connection data(String... keyvals);
/**
* Get the data KeyVal for this key, if any
* @param key the data key
* @return null if not set
*/
@Nullable KeyVal data(String key);
/**
* Set a POST (or PUT) request body. Useful when a server expects a plain request body, not a set for URL
* encoded form key/value pairs. E.g.:
* <code><pre>Jsoup.connect(url)
* .requestBody(json)
* .header("Content-Type", "application/json")
* .post();</pre></code>
* If any data key/vals are supplied, they will be sent as URL query params.
* @return this Request, for chaining
*/
Connection requestBody(String body);
/**
* Set a request header.
* @param name header name
* @param value header value
* @return this Connection, for chaining
* @see org.jsoup.Connection.Request#headers()
*/
Connection header(String name, String value);
/**
* Adds each of the supplied headers to the request.
* @param headers map of headers name {@literal ->} value pairs
* @return this Connection, for chaining
* @see org.jsoup.Connection.Request#headers()
*/
Connection headers(Map<String,String> headers);
/**
* Set a cookie to be sent in the request.
* @param name name of cookie
* @param value value of cookie
* @return this Connection, for chaining
*/
Connection cookie(String name, String value);
/**
* Adds each of the supplied cookies to the request.
* @param cookies map of cookie name {@literal ->} value pairs
* @return this Connection, for chaining
*/
Connection cookies(Map<String, String> cookies);
/**
Provide a custom or pre-filled CookieStore to be used on requests made by this Connection.
@param cookieStore a cookie store to use for subsequent requests
@return this Connection, for chaining
@since 1.14.1
*/
Connection cookieStore(CookieStore cookieStore);
/**
Get the cookie store used by this Connection.
@return the cookie store
@since 1.14.1
*/
CookieStore cookieStore();
/**
* Provide an alternate parser to use when parsing the response to a Document. If not set, defaults to the HTML
* parser, unless the response content-type is XML, in which case the XML parser is used.
* @param parser alternate parser
* @return this Connection, for chaining
*/
Connection parser(Parser parser);
/**
* Sets the default post data character set for x-www-form-urlencoded post data
* @param charset character set to encode post data
* @return this Connection, for chaining
*/
Connection postDataCharset(String charset);
/**
* Execute the request as a GET, and parse the result.
* @return parsed Document
* @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Document get() throws IOException;
/**
* Execute the request as a POST, and parse the result.
* @return parsed Document
* @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Document post() throws IOException;
/**
* Execute the request.
* @return a response object
* @throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
* @throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
* @throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
* @throws java.net.SocketTimeoutException if the connection times out
* @throws IOException on error
*/
Response execute() throws IOException;
/**
* Get the request object associated with this connection
* @return request
*/
Request request();
/**
* Set the connection's request
* @param request new request object
* @return this Connection, for chaining
*/
Connection request(Request request);
/**
* Get the response, once the request has been executed.
* @return response
* @throws IllegalArgumentException if called before the response has been executed.
*/
Response response();
/**
* Set the connection's response
* @param response new response
* @return this Connection, for chaining
*/
Connection response(Response response);
/**
* Common methods for Requests and Responses
* @param <T> Type of Base, either Request or Response
*/
@SuppressWarnings("UnusedReturnValue")
interface Base<T extends Base<T>> {
/**
* Get the URL of this Request or Response. For redirected responses, this will be the final destination URL.
* @return URL
* @throws IllegalArgumentException if called on a Request that was created without a URL.
*/
URL url();
/**
* Set the URL
* @param url new URL
* @return this, for chaining
*/
T url(URL url);
/**
* Get the request method, which defaults to <code>GET</code>
* @return method
*/
Method method();
/**
* Set the request method
* @param method new method
* @return this, for chaining
*/
T method(Method method);
/**
* Get the value of a header. If there is more than one header value with the same name, the headers are returned
* comma seperated, per <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2">rfc2616-sec4</a>.
* <p>
* Header names are case insensitive.
* </p>
* @param name name of header (case insensitive)
* @return value of header, or null if not set.
* @see #hasHeader(String)
* @see #cookie(String)
*/
@Nullable String header(String name);
/**
* Get the values of a header.
* @param name header name, case insensitive.
* @return a list of values for this header, or an empty list if not set.
*/
List<String> headers(String name);
/**
* Set a header. This method will overwrite any existing header with the same case insensitive name. (If there
* is more than one value for this header, this method will update the first matching header.
* @param name Name of header
* @param value Value of header
* @return this, for chaining
* @see #addHeader(String, String)
*/
T header(String name, String value);
/**
* Add a header. The header will be added regardless of whether a header with the same name already exists.
* @param name Name of new header
* @param value Value of new header
* @return this, for chaining
*/
T addHeader(String name, String value);
/**
* Check if a header is present
* @param name name of header (case insensitive)
* @return if the header is present in this request/response
*/
boolean hasHeader(String name);
/**
* Check if a header is present, with the given value
* @param name header name (case insensitive)
* @param value value (case insensitive)
* @return if the header and value pair are set in this req/res
*/
boolean hasHeaderWithValue(String name, String value);
/**
* Remove headers by name. If there is more than one header with this name, they will all be removed.
* @param name name of header to remove (case insensitive)
* @return this, for chaining
*/
T removeHeader(String name);
/**
* Retrieve all of the request/response header names and corresponding values as a map. For headers with multiple
* values, only the first header is returned.
* <p>Note that this is a view of the headers only, and changes made to this map will not be reflected in the
* request/response object.</p>
* @return headers
* @see #multiHeaders()
*/
Map<String, String> headers();
/**
* Retreive all of the headers, keyed by the header name, and with a list of values per header.
* @return a list of multiple values per header.
*/
Map<String, List<String>> multiHeaders();
/**
* Get a cookie value by name from this request/response.
* <p>
* Response objects have a simplified cookie model. Each cookie set in the response is added to the response
* object's cookie key=value map. The cookie's path, domain, and expiry date are ignored.
* </p>
* @param name name of cookie to retrieve.
* @return value of cookie, or null if not set
*/
@Nullable String cookie(String name);
/**
* Set a cookie in this request/response.
* @param name name of cookie
* @param value value of cookie
* @return this, for chaining
*/
T cookie(String name, String value);
/**
* Check if a cookie is present
* @param name name of cookie
* @return if the cookie is present in this request/response
*/
boolean hasCookie(String name);
/**
* Remove a cookie by name
* @param name name of cookie to remove
* @return this, for chaining
*/
T removeCookie(String name);
/**
* Retrieve all of the request/response cookies as a map
* @return cookies
*/
Map<String, String> cookies();
}
/**
* Represents a HTTP request.
*/
@SuppressWarnings("UnusedReturnValue")
interface Request extends Base<Request> {
/**
* Get the proxy used for this request.
* @return the proxy; <code>null</code> if not enabled.
*/
@Nullable Proxy proxy();
/**
* Update the proxy for this request.
* @param proxy the proxy ot use; <code>null</code> to disable.
* @return this Request, for chaining
*/
Request proxy(@Nullable Proxy proxy);
/**
* Set the HTTP proxy to use for this request.
* @param host the proxy hostname
* @param port the proxy port
* @return this Connection, for chaining
*/
Request proxy(String host, int port);
/**
* Get the request timeout, in milliseconds.
* @return the timeout in milliseconds.
*/
int timeout();
/**
* Update the request timeout.
* @param millis timeout, in milliseconds
* @return this Request, for chaining
*/
Request timeout(int millis);
/**
* Get the maximum body size, in bytes.
* @return the maximum body size, in bytes.
*/
int maxBodySize();
/**
* Update the maximum body size, in bytes.
* @param bytes maximum body size, in bytes.
* @return this Request, for chaining
*/
Request maxBodySize(int bytes);
/**
* Get the current followRedirects configuration.
* @return true if followRedirects is enabled.
*/
boolean followRedirects();
/**
* Configures the request to (not) follow server redirects. By default this is <b>true</b>.
* @param followRedirects true if server redirects should be followed.
* @return this Request, for chaining
*/
Request followRedirects(boolean followRedirects);
/**
* Get the current ignoreHttpErrors configuration.
* @return true if errors will be ignored; false (default) if HTTP errors will cause an IOException to be
* thrown.
*/
boolean ignoreHttpErrors();
/**
* Configures the request to ignore HTTP errors in the response.
* @param ignoreHttpErrors set to true to ignore HTTP errors.
* @return this Request, for chaining
*/
Request ignoreHttpErrors(boolean ignoreHttpErrors);
/**
* Get the current ignoreContentType configuration.
* @return true if invalid content-types will be ignored; false (default) if they will cause an IOException to
* be thrown.
*/
boolean ignoreContentType();
/**
* Configures the request to ignore the Content-Type of the response.
* @param ignoreContentType set to true to ignore the content type.
* @return this Request, for chaining
*/
Request ignoreContentType(boolean ignoreContentType);
/**
* Get the current custom SSL socket factory, if any.
* @return custom SSL socket factory if set, null otherwise
*/
@Nullable SSLSocketFactory sslSocketFactory();
/**
* Set a custom SSL socket factory.
* @param sslSocketFactory SSL socket factory
*/
void sslSocketFactory(SSLSocketFactory sslSocketFactory);
/**
* Add a data parameter to the request
* @param keyval data to add.
* @return this Request, for chaining
*/
Request data(KeyVal keyval);
/**
* Get all of the request's data parameters
* @return collection of keyvals
*/
Collection<KeyVal> data();
/**
* Set a POST (or PUT) request body. Useful when a server expects a plain request body, not a set for URL
* encoded form key/value pairs. E.g.:
* <code><pre>Jsoup.connect(url)
* .requestBody(json)
* .header("Content-Type", "application/json")
* .post();</pre></code>
* If any data key/vals are supplied, they will be sent as URL query params.
* @param body to use as the request body. Set to null to clear a previously set body.
* @return this Request, for chaining
*/
Request requestBody(@Nullable String body);
/**
* Get the current request body.
* @return null if not set.
*/
@Nullable String requestBody();
/**
* Specify the parser to use when parsing the document.
* @param parser parser to use.
* @return this Request, for chaining
*/
Request parser(Parser parser);
/**
* Get the current parser to use when parsing the document.
* @return current Parser
*/
Parser parser();
/**
* Sets the post data character set for x-www-form-urlencoded post data
* @param charset character set to encode post data
* @return this Request, for chaining
*/
Request postDataCharset(String charset);
/**
* Gets the post data character set for x-www-form-urlencoded post data
* @return character set to encode post data
*/
String postDataCharset();
}
/**
* Represents a HTTP response.
*/
interface Response extends Base<Response> {
/**
* Get the status code of the response.
* @return status code
*/
int statusCode();
/**
* Get the status message of the response.
* @return status message
*/
String statusMessage();
/**
* Get the character set name of the response, derived from the content-type header.
* @return character set name if set, <b>null</b> if not
*/
@Nullable String charset();
/**
* Set / override the response character set. When the document body is parsed it will be with this charset.
* @param charset to decode body as
* @return this Response, for chaining
*/
Response charset(String charset);
/**
* Get the response content type (e.g. "text/html");
* @return the response content type, or <b>null</b> if one was not set
*/
@Nullable String contentType();
/**
* Read and parse the body of the response as a Document. If you intend to parse the same response multiple
* times, you should {@link #bufferUp()} first.
* @return a parsed Document
* @throws IOException on error
*/
Document parse() throws IOException;
/**
* Get the body of the response as a plain string.
* @return body
*/
String body();
/**
* Get the body of the response as an array of bytes.
* @return body bytes
*/
byte[] bodyAsBytes();
/**
* Read the body of the response into a local buffer, so that {@link #parse()} may be called repeatedly on the
* same connection response (otherwise, once the response is read, its InputStream will have been drained and
* may not be re-read). Calling {@link #body() } or {@link #bodyAsBytes()} has the same effect.
* @return this response, for chaining
* @throws UncheckedIOException if an IO exception occurs during buffering.
*/
Response bufferUp();
/**
* Get the body of the response as a (buffered) InputStream. You should close the input stream when you're done with it.
* Other body methods (like bufferUp, body, parse, etc) will not work in conjunction with this method.
* <p>This method is useful for writing large responses to disk, without buffering them completely into memory first.</p>
* @return the response body input stream
*/
BufferedInputStream bodyStream();
}
/**
* A Key:Value tuple(+), used for form data.
*/
interface KeyVal {
/**
* Update the key of a keyval
* @param key new key
* @return this KeyVal, for chaining
*/
KeyVal key(String key);
/**
* Get the key of a keyval
* @return the key
*/
String key();
/**
* Update the value of a keyval
* @param value the new value
* @return this KeyVal, for chaining
*/
KeyVal value(String value);
/**
* Get the value of a keyval
* @return the value
*/
String value();
/**
* Add or update an input stream to this keyVal
* @param inputStream new input stream
* @return this KeyVal, for chaining
*/
KeyVal inputStream(InputStream inputStream);
/**
* Get the input stream associated with this keyval, if any
* @return input stream if set, or null
*/
@Nullable InputStream inputStream();
/**
* Does this keyval have an input stream?
* @return true if this keyval does indeed have an input stream
*/
boolean hasInputStream();
/**
* Set the Content Type header used in the MIME body (aka mimetype) when uploading files.
* Only useful if {@link #inputStream(InputStream)} is set.
* <p>Will default to {@code application/octet-stream}.</p>
* @param contentType the new content type
* @return this KeyVal
*/
KeyVal contentType(String contentType);
/**
* Get the current Content Type, or {@code null} if not set.
* @return the current Content Type.
*/
@Nullable String contentType();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/HttpStatusException.java
|
package org.jsoup;
import java.io.IOException;
/**
* Signals that a HTTP request resulted in a not OK HTTP response.
*/
public class HttpStatusException extends IOException {
private final int statusCode;
private final String url;
public HttpStatusException(String message, int statusCode, String url) {
super(message + ". Status=" + statusCode + ", URL=[" + url + "]");
this.statusCode = statusCode;
this.url = url;
}
public int getStatusCode() {
return statusCode;
}
public String getUrl() {
return url;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/Jsoup.java
|
package org.jsoup;
import org.jsoup.helper.DataUtil;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Safelist;
import org.jsoup.safety.Whitelist;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
The core public access point to the jsoup functionality.
@author Jonathan Hedley */
public class Jsoup {
private Jsoup() {}
/**
Parse HTML into a Document. The parser will make a sensible, balanced document tree out of any HTML.
@param html HTML to parse
@param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, that occur
before the HTML declares a {@code <base href>} tag.
@return sane HTML
*/
public static Document parse(String html, String baseUri) {
return Parser.parse(html, baseUri);
}
/**
Parse HTML into a Document, using the provided Parser. You can provide an alternate parser, such as a simple XML
(non-HTML) parser.
@param html HTML to parse
@param baseUri The URL where the HTML was retrieved from. Used to resolve relative URLs to absolute URLs, that occur
before the HTML declares a {@code <base href>} tag.
@param parser alternate {@link Parser#xmlParser() parser} to use.
@return sane HTML
*/
public static Document parse(String html, String baseUri, Parser parser) {
return parser.parseInput(html, baseUri);
}
/**
Parse HTML into a Document, using the provided Parser. You can provide an alternate parser, such as a simple XML
(non-HTML) parser. As no base URI is specified, absolute URL resolution, if required, relies on the HTML including
a {@code <base href>} tag.
@param html HTML to parse
before the HTML declares a {@code <base href>} tag.
@param parser alternate {@link Parser#xmlParser() parser} to use.
@return sane HTML
*/
public static Document parse(String html, Parser parser) {
return parser.parseInput(html, "");
}
/**
Parse HTML into a Document. As no base URI is specified, absolute URL resolution, if required, relies on the HTML
including a {@code <base href>} tag.
@param html HTML to parse
@return sane HTML
@see #parse(String, String)
*/
public static Document parse(String html) {
return Parser.parse(html, "");
}
/**
* Creates a new {@link Connection} (session), with the defined request URL. Use to fetch and parse a HTML page.
* <p>
* Use examples:
* <ul>
* <li><code>Document doc = Jsoup.connect("http://example.com").userAgent("Mozilla").data("name", "jsoup").get();</code></li>
* <li><code>Document doc = Jsoup.connect("http://example.com").cookie("auth", "token").post();</code></li>
* </ul>
* @param url URL to connect to. The protocol must be {@code http} or {@code https}.
* @return the connection. You can add data, cookies, and headers; set the user-agent, referrer, method; and then execute.
* @see #newSession()
* @see Connection#newRequest()
*/
public static Connection connect(String url) {
return HttpConnection.connect(url);
}
/**
Creates a new {@link Connection} to use as a session. Connection settings (user-agent, timeouts, URL, etc), and
cookies will be maintained for the session. Use examples:
<pre><code>
Connection session = Jsoup.newSession()
.timeout(20 * 1000)
.userAgent("FooBar 2000");
Document doc1 = session.newRequest()
.url("https://jsoup.org/").data("ref", "example")
.get();
Document doc2 = session.newRequest()
.url("https://en.wikipedia.org/wiki/Main_Page")
.get();
Connection con3 = session.newRequest();
</code></pre>
<p>For multi-threaded requests, it is safe to use this session between threads, but take care to call {@link
Connection#newRequest()} per request and not share that instance between threads when executing or parsing.</p>
@return a connection
@since 1.14.1
*/
public static Connection newSession() {
return new HttpConnection();
}
/**
Parse the contents of a file as HTML.
@param file file to load HTML from. Supports gzipped files (ending in .z or .gz).
@param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if
present, or fall back to {@code UTF-8} (which is often safe to do).
@param baseUri The URL where the HTML was retrieved from, to resolve relative links against.
@return sane HTML
@throws IOException if the file could not be found, or read, or if the charsetName is invalid.
*/
public static Document parse(File file, @Nullable String charsetName, String baseUri) throws IOException {
return DataUtil.load(file, charsetName, baseUri);
}
/**
Parse the contents of a file as HTML. The location of the file is used as the base URI to qualify relative URLs.
@param file file to load HTML from. Supports gzipped files (ending in .z or .gz).
@param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if
present, or fall back to {@code UTF-8} (which is often safe to do).
@return sane HTML
@throws IOException if the file could not be found, or read, or if the charsetName is invalid.
@see #parse(File, String, String)
*/
public static Document parse(File file, @Nullable String charsetName) throws IOException {
return DataUtil.load(file, charsetName, file.getAbsolutePath());
}
/**
Parse the contents of a file as HTML.
@param file file to load HTML from. Supports gzipped files (ending in .z or .gz).
@param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if
present, or fall back to {@code UTF-8} (which is often safe to do).
@param baseUri The URL where the HTML was retrieved from, to resolve relative links against.
@param parser alternate {@link Parser#xmlParser() parser} to use.
@return sane HTML
@throws IOException if the file could not be found, or read, or if the charsetName is invalid.
@since 1.14.2
*/
public static Document parse(File file, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
return DataUtil.load(file, charsetName, baseUri, parser);
}
/**
Read an input stream, and parse it to a Document.
@param in input stream to read. Make sure to close it after parsing.
@param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if
present, or fall back to {@code UTF-8} (which is often safe to do).
@param baseUri The URL where the HTML was retrieved from, to resolve relative links against.
@return sane HTML
@throws IOException if the file could not be found, or read, or if the charsetName is invalid.
*/
public static Document parse(InputStream in, @Nullable String charsetName, String baseUri) throws IOException {
return DataUtil.load(in, charsetName, baseUri);
}
/**
Read an input stream, and parse it to a Document. You can provide an alternate parser, such as a simple XML
(non-HTML) parser.
@param in input stream to read. Make sure to close it after parsing.
@param charsetName (optional) character set of file contents. Set to {@code null} to determine from {@code http-equiv} meta tag, if
present, or fall back to {@code UTF-8} (which is often safe to do).
@param baseUri The URL where the HTML was retrieved from, to resolve relative links against.
@param parser alternate {@link Parser#xmlParser() parser} to use.
@return sane HTML
@throws IOException if the file could not be found, or read, or if the charsetName is invalid.
*/
public static Document parse(InputStream in, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
return DataUtil.load(in, charsetName, baseUri, parser);
}
/**
Parse a fragment of HTML, with the assumption that it forms the {@code body} of the HTML.
@param bodyHtml body HTML fragment
@param baseUri URL to resolve relative URLs against.
@return sane HTML document
@see Document#body()
*/
public static Document parseBodyFragment(String bodyHtml, String baseUri) {
return Parser.parseBodyFragment(bodyHtml, baseUri);
}
/**
Parse a fragment of HTML, with the assumption that it forms the {@code body} of the HTML.
@param bodyHtml body HTML fragment
@return sane HTML document
@see Document#body()
*/
public static Document parseBodyFragment(String bodyHtml) {
return Parser.parseBodyFragment(bodyHtml, "");
}
/**
Fetch a URL, and parse it as HTML. Provided for compatibility; in most cases use {@link #connect(String)} instead.
<p>
The encoding character set is determined by the content-type header or http-equiv meta tag, or falls back to {@code UTF-8}.
@param url URL to fetch (with a GET). The protocol must be {@code http} or {@code https}.
@param timeoutMillis Connection and read timeout, in milliseconds. If exceeded, IOException is thrown.
@return The parsed HTML.
@throws java.net.MalformedURLException if the request URL is not a HTTP or HTTPS URL, or is otherwise malformed
@throws HttpStatusException if the response is not OK and HTTP response errors are not ignored
@throws UnsupportedMimeTypeException if the response mime type is not supported and those errors are not ignored
@throws java.net.SocketTimeoutException if the connection times out
@throws IOException if a connection or read error occurs
@see #connect(String)
*/
public static Document parse(URL url, int timeoutMillis) throws IOException {
Connection con = HttpConnection.connect(url);
con.timeout(timeoutMillis);
return con.get();
}
/**
Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through an allow-list of safe
tags and attributes.
@param bodyHtml input untrusted HTML (body fragment)
@param baseUri URL to resolve relative URLs against
@param safelist list of permitted HTML elements
@return safe HTML (body fragment)
@see Cleaner#clean(Document)
*/
public static String clean(String bodyHtml, String baseUri, Safelist safelist) {
Document dirty = parseBodyFragment(bodyHtml, baseUri);
Cleaner cleaner = new Cleaner(safelist);
Document clean = cleaner.clean(dirty);
return clean.body().html();
}
/**
Use {@link #clean(String, String, Safelist)} instead.
@deprecated as of 1.14.1.
*/
@Deprecated
public static String clean(String bodyHtml, String baseUri, Whitelist safelist) {
return clean(bodyHtml, baseUri, (Safelist) safelist);
}
/**
Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a safe-list of permitted
tags and attributes.
<p>Note that as this method does not take a base href URL to resolve attributes with relative URLs against, those
URLs will be removed, unless the input HTML contains a {@code <base href> tag}. If you wish to preserve those, use
the {@link Jsoup#clean(String html, String baseHref, Safelist)} method instead, and enable
{@link Safelist#preserveRelativeLinks(boolean)}.</p>
@param bodyHtml input untrusted HTML (body fragment)
@param safelist list of permitted HTML elements
@return safe HTML (body fragment)
@see Cleaner#clean(Document)
*/
public static String clean(String bodyHtml, Safelist safelist) {
return clean(bodyHtml, "", safelist);
}
/**
Use {@link #clean(String, Safelist)} instead.
@deprecated as of 1.14.1.
*/
@Deprecated
public static String clean(String bodyHtml, Whitelist safelist) {
return clean(bodyHtml, (Safelist) safelist);
}
/**
* Get safe HTML from untrusted input HTML, by parsing input HTML and filtering it through a safe-list of
* permitted tags and attributes.
* <p>The HTML is treated as a body fragment; it's expected the cleaned HTML will be used within the body of an
* existing document. If you want to clean full documents, use {@link Cleaner#clean(Document)} instead, and add
* structural tags (<code>html, head, body</code> etc) to the safelist.
*
* @param bodyHtml input untrusted HTML (body fragment)
* @param baseUri URL to resolve relative URLs against
* @param safelist list of permitted HTML elements
* @param outputSettings document output settings; use to control pretty-printing and entity escape modes
* @return safe HTML (body fragment)
* @see Cleaner#clean(Document)
*/
public static String clean(String bodyHtml, String baseUri, Safelist safelist, Document.OutputSettings outputSettings) {
Document dirty = parseBodyFragment(bodyHtml, baseUri);
Cleaner cleaner = new Cleaner(safelist);
Document clean = cleaner.clean(dirty);
clean.outputSettings(outputSettings);
return clean.body().html();
}
/**
Use {@link #clean(String, String, Safelist, Document.OutputSettings)} instead.
@deprecated as of 1.14.1.
*/
@Deprecated
public static String clean(String bodyHtml, String baseUri, Whitelist safelist, Document.OutputSettings outputSettings) {
return clean(bodyHtml, baseUri, (Safelist) safelist, outputSettings);
}
/**
Test if the input body HTML has only tags and attributes allowed by the Safelist. Useful for form validation.
<p>The input HTML should still be run through the cleaner to set up enforced attributes, and to tidy the output.
<p>Assumes the HTML is a body fragment (i.e. will be used in an existing HTML document body.)
@param bodyHtml HTML to test
@param safelist safelist to test against
@return true if no tags or attributes were removed; false otherwise
@see #clean(String, Safelist)
*/
public static boolean isValid(String bodyHtml, Safelist safelist) {
return new Cleaner(safelist).isValidBodyHtml(bodyHtml);
}
/**
Use {@link #isValid(String, Safelist)} instead.
@deprecated as of 1.14.1.
*/
@Deprecated
public static boolean isValid(String bodyHtml, Whitelist safelist) {
return isValid(bodyHtml, (Safelist) safelist);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/SerializationException.java
|
package org.jsoup;
/**
* A SerializationException is raised whenever serialization of a DOM element fails. This exception usually wraps an
* {@link java.io.IOException} that may be thrown due to an inaccessible output stream.
*/
public final class SerializationException extends RuntimeException {
/**
* Creates and initializes a new serialization exception with no error message and cause.
*/
public SerializationException() {
super();
}
/**
* Creates and initializes a new serialization exception with the given error message and no cause.
*
* @param message
* the error message of the new serialization exception (may be <code>null</code>).
*/
public SerializationException(String message) {
super(message);
}
/**
* Creates and initializes a new serialization exception with the specified cause and an error message of
* <code>(cause==null ? null : cause.toString())</code> (which typically contains the class and error message of
* <code>cause</code>).
*
* @param cause
* the cause of the new serialization exception (may be <code>null</code>).
*/
public SerializationException(Throwable cause) {
super(cause);
}
/**
* Creates and initializes a new serialization exception with the given error message and cause.
*
* @param message
* the error message of the new serialization exception.
* @param cause
* the cause of the new serialization exception.
*/
public SerializationException(String message, Throwable cause) {
super(message, cause);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/UncheckedIOException.java
|
package org.jsoup;
import java.io.IOException;
public class UncheckedIOException extends RuntimeException {
public UncheckedIOException(IOException cause) {
super(cause);
}
public UncheckedIOException(String message) {
super(new IOException(message));
}
public IOException ioException() {
return (IOException) getCause();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/UnsupportedMimeTypeException.java
|
package org.jsoup;
import java.io.IOException;
/**
* Signals that a HTTP response returned a mime type that is not supported.
*/
public class UnsupportedMimeTypeException extends IOException {
private final String mimeType;
private final String url;
public UnsupportedMimeTypeException(String message, String mimeType, String url) {
super(message);
this.mimeType = mimeType;
this.url = url;
}
public String getMimeType() {
return mimeType;
}
public String getUrl() {
return url;
}
@Override
public String toString() {
return super.toString() + ". Mimetype=" + mimeType + ", URL="+url;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/package-info.java
|
/**
Contains the main {@link org.jsoup.Jsoup} class, which provides convenient static access to the jsoup functionality.
*/
@NonnullByDefault
package org.jsoup;
import org.jsoup.internal.NonnullByDefault;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/ChangeNotifyingArrayList.java
|
package org.jsoup.helper;
import java.util.ArrayList;
import java.util.Collection;
/**
* Implementation of ArrayList that watches out for changes to the contents.
*/
public abstract class ChangeNotifyingArrayList<E> extends ArrayList<E> {
public ChangeNotifyingArrayList(int initialCapacity) {
super(initialCapacity);
}
public abstract void onContentsChanged();
@Override
public E set(int index, E element) {
onContentsChanged();
return super.set(index, element);
}
@Override
public boolean add(E e) {
onContentsChanged();
return super.add(e);
}
@Override
public void add(int index, E element) {
onContentsChanged();
super.add(index, element);
}
@Override
public E remove(int index) {
onContentsChanged();
return super.remove(index);
}
@Override
public boolean remove(Object o) {
onContentsChanged();
return super.remove(o);
}
@Override
public void clear() {
onContentsChanged();
super.clear();
}
@Override
public boolean addAll(Collection<? extends E> c) {
onContentsChanged();
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c) {
onContentsChanged();
return super.addAll(index, c);
}
@Override
protected void removeRange(int fromIndex, int toIndex) {
onContentsChanged();
super.removeRange(fromIndex, toIndex);
}
@Override
public boolean removeAll(Collection<?> c) {
onContentsChanged();
return super.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
onContentsChanged();
return super.retainAll(c);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/CookieUtil.java
|
package org.jsoup.helper;
import org.jsoup.Connection;
import org.jsoup.internal.StringUtil;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
Helper functions to support the Cookie Manager / Cookie Storage in HttpConnection.
@since 1.14.1 */
class CookieUtil {
// cookie manager get() wants request headers but doesn't use them, so we just pass a dummy object here
private static final Map<String, List<String>> EmptyRequestHeaders = Collections.unmodifiableMap(new HashMap<>());
private static final String Sep = "; ";
private static final String CookieName = "Cookie";
private static final String Cookie2Name = "Cookie2";
/**
Pre-request, get any applicable headers out of the Request cookies and the Cookie Store, and add them to the request
headers. If the Cookie Store duplicates any Request cookies (same name and value), they will be discarded.
*/
static void applyCookiesToRequest(HttpConnection.Request req, HttpURLConnection con) throws IOException {
// Request key/val cookies. LinkedHashSet used to preserve order, as cookie store will return most specific path first
Set<String> cookieSet = requestCookieSet(req);
Set<String> cookies2 = null;
// stored:
Map<String, List<String>> storedCookies = req.cookieManager().get(asUri(req.url), EmptyRequestHeaders);
for (Map.Entry<String, List<String>> entry : storedCookies.entrySet()) {
// might be Cookie: name=value; name=value\nCookie2: name=value; name=value
List<String> cookies = entry.getValue(); // these will be name=val
if (cookies == null || cookies.size() == 0) // the cookie store often returns just an empty "Cookie" key, no val
continue;
String key = entry.getKey(); // Cookie or Cookie2
Set<String> set;
if (CookieName.equals(key))
set = cookieSet;
else if (Cookie2Name.equals(key)) {
set = new HashSet<>();
cookies2 = set;
} else {
continue; // unexpected header key
}
set.addAll(cookies);
}
if (cookieSet.size() > 0)
con.addRequestProperty(CookieName, StringUtil.join(cookieSet, Sep));
if (cookies2 != null && cookies2.size() > 0)
con.addRequestProperty(Cookie2Name, StringUtil.join(cookies2, Sep));
}
private static LinkedHashSet<String> requestCookieSet(Connection.Request req) {
LinkedHashSet<String> set = new LinkedHashSet<>();
// req cookies are the wildcard key/val cookies (no domain, path, etc)
for (Map.Entry<String, String> cookie : req.cookies().entrySet()) {
set.add(cookie.getKey() + "=" + cookie.getValue());
}
return set;
}
static URI asUri(URL url) throws IOException {
try {
return url.toURI();
} catch (URISyntaxException e) { // this would be a WTF because we construct the URL
MalformedURLException ue = new MalformedURLException(e.getMessage());
ue.initCause(e);
throw ue;
}
}
static void storeCookies(HttpConnection.Request req, URL url, Map<String, List<String>> resHeaders) throws IOException {
req.cookieManager().put(CookieUtil.asUri(url), resHeaders); // stores cookies for session
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/DataUtil.java
|
package org.jsoup.helper;
import org.jsoup.UncheckedIOException;
import org.jsoup.internal.ConstrainableInputStream;
import org.jsoup.internal.Normalizer;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.XmlDeclaration;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.Locale;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
/**
* Internal static utilities for handling data.
*
*/
@SuppressWarnings("CharsetObjectCanBeUsed")
public final class DataUtil {
private static final Pattern charsetPattern = Pattern.compile("(?i)\\bcharset=\\s*(?:[\"'])?([^\\s,;\"']*)");
public static final Charset UTF_8 = Charset.forName("UTF-8"); // Don't use StandardCharsets, as those only appear in Android API 19, and we target 10.
static final String defaultCharsetName = UTF_8.name(); // used if not found in header or meta charset
private static final int firstReadBufferSize = 1024 * 5;
static final int bufferSize = 1024 * 32;
private static final char[] mimeBoundaryChars =
"-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
static final int boundaryLength = 32;
private DataUtil() {}
/**
* Loads and parses a file to a Document, with the HtmlParser. Files that are compressed with gzip (and end in {@code .gz} or {@code .z})
* are supported in addition to uncompressed files.
*
* @param file file to load
* @param charsetName (optional) character set of input; specify {@code null} to attempt to autodetect. A BOM in
* the file will always override this setting.
* @param baseUri base URI of document, to resolve relative links against
* @return Document
* @throws IOException on IO error
*/
public static Document load(File file, @Nullable String charsetName, String baseUri) throws IOException {
return load(file, charsetName, baseUri, Parser.htmlParser());
}
/**
* Loads and parses a file to a Document. Files that are compressed with gzip (and end in {@code .gz} or {@code .z})
* are supported in addition to uncompressed files.
*
* @param file file to load
* @param charsetName (optional) character set of input; specify {@code null} to attempt to autodetect. A BOM in
* the file will always override this setting.
* @param baseUri base URI of document, to resolve relative links against
* @param parser alternate {@link Parser#xmlParser() parser} to use.
* @return Document
* @throws IOException on IO error
* @since 1.14.2
*/
public static Document load(File file, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
InputStream stream = new FileInputStream(file);
String name = Normalizer.lowerCase(file.getName());
if (name.endsWith(".gz") || name.endsWith(".z")) {
// unfortunately file input streams don't support marks (why not?), so we will close and reopen after read
boolean zipped;
try {
zipped = (stream.read() == 0x1f && stream.read() == 0x8b); // gzip magic bytes
} finally {
stream.close();
}
stream = zipped ? new GZIPInputStream(new FileInputStream(file)) : new FileInputStream(file);
}
return parseInputStream(stream, charsetName, baseUri, parser);
}
/**
* Parses a Document from an input steam.
* @param in input stream to parse. The stream will be closed after reading.
* @param charsetName character set of input (optional)
* @param baseUri base URI of document, to resolve relative links against
* @return Document
* @throws IOException on IO error
*/
public static Document load(InputStream in, @Nullable String charsetName, String baseUri) throws IOException {
return parseInputStream(in, charsetName, baseUri, Parser.htmlParser());
}
/**
* Parses a Document from an input steam, using the provided Parser.
* @param in input stream to parse. The stream will be closed after reading.
* @param charsetName character set of input (optional)
* @param baseUri base URI of document, to resolve relative links against
* @param parser alternate {@link Parser#xmlParser() parser} to use.
* @return Document
* @throws IOException on IO error
*/
public static Document load(InputStream in, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
return parseInputStream(in, charsetName, baseUri, parser);
}
/**
* Writes the input stream to the output stream. Doesn't close them.
* @param in input stream to read from
* @param out output stream to write to
* @throws IOException on IO error
*/
static void crossStreams(final InputStream in, final OutputStream out) throws IOException {
final byte[] buffer = new byte[bufferSize];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
static Document parseInputStream(@Nullable InputStream input, @Nullable String charsetName, String baseUri, Parser parser) throws IOException {
if (input == null) // empty body
return new Document(baseUri);
input = ConstrainableInputStream.wrap(input, bufferSize, 0);
@Nullable Document doc = null;
// read the start of the stream and look for a BOM or meta charset
try {
input.mark(bufferSize);
ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); // -1 because we read one more to see if completed. First read is < buffer size, so can't be invalid.
boolean fullyRead = (input.read() == -1);
input.reset();
// look for BOM - overrides any other header or input
BomCharset bomCharset = detectCharsetFromBom(firstBytes);
if (bomCharset != null)
charsetName = bomCharset.charset;
if (charsetName == null) { // determine from meta. safe first parse as UTF-8
try {
CharBuffer defaultDecoded = UTF_8.decode(firstBytes);
if (defaultDecoded.hasArray())
doc = parser.parseInput(new CharArrayReader(defaultDecoded.array(), defaultDecoded.arrayOffset(), defaultDecoded.limit()), baseUri);
else
doc = parser.parseInput(defaultDecoded.toString(), baseUri);
} catch (UncheckedIOException e) {
throw e.ioException();
}
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]");
String foundCharset = null; // if not found, will keep utf-8 as best attempt
for (Element meta : metaElements) {
if (meta.hasAttr("http-equiv"))
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset"))
foundCharset = meta.attr("charset");
if (foundCharset != null)
break;
}
// look for <?xml encoding='ISO-8859-1'?>
if (foundCharset == null && doc.childNodeSize() > 0) {
Node first = doc.childNode(0);
XmlDeclaration decl = null;
if (first instanceof XmlDeclaration)
decl = (XmlDeclaration) first;
else if (first instanceof Comment) {
Comment comment = (Comment) first;
if (comment.isXmlDeclaration())
decl = comment.asXmlDeclaration();
}
if (decl != null) {
if (decl.name().equalsIgnoreCase("xml"))
foundCharset = decl.attr("encoding");
}
}
foundCharset = validateCharset(foundCharset);
if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharsetName)) { // need to re-decode. (case insensitive check here to match how validate works)
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
doc = null;
} else if (!fullyRead) {
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");
}
if (doc == null) {
if (charsetName == null)
charsetName = defaultCharsetName;
BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); // Android level does not allow us try-with-resources
try {
if (bomCharset != null && bomCharset.offset) { // creating the buffered reader ignores the input pos, so must skip here
long skipped = reader.skip(1);
Validate.isTrue(skipped == 1); // WTF if this fails.
}
try {
doc = parser.parseInput(reader, baseUri);
} catch (UncheckedIOException e) {
// io exception when parsing (not seen before because reading the stream as we go)
throw e.ioException();
}
Charset charset = charsetName.equals(defaultCharsetName) ? UTF_8 : Charset.forName(charsetName);
doc.outputSettings().charset(charset);
if (!charset.canEncode()) {
// some charsets can read but not encode; switch to an encodable charset and update the meta el
doc.charset(UTF_8);
}
}
finally {
reader.close();
}
}
}
finally {
input.close();
}
return doc;
}
/**
* Read the input stream into a byte buffer. To deal with slow input streams, you may interrupt the thread this
* method is executing on. The data read until being interrupted will be available.
* @param inStream the input stream to read from
* @param maxSize the maximum size in bytes to read from the stream. Set to 0 to be unlimited.
* @return the filled byte buffer
* @throws IOException if an exception occurs whilst reading from the input stream.
*/
public static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize) throws IOException {
Validate.isTrue(maxSize >= 0, "maxSize must be 0 (unlimited) or larger");
final ConstrainableInputStream input = ConstrainableInputStream.wrap(inStream, bufferSize, maxSize);
return input.readToByteBuffer(maxSize);
}
static ByteBuffer emptyByteBuffer() {
return ByteBuffer.allocate(0);
}
/**
* Parse out a charset from a content type header. If the charset is not supported, returns null (so the default
* will kick in.)
* @param contentType e.g. "text/html; charset=EUC-JP"
* @return "EUC-JP", or null if not found. Charset is trimmed and uppercased.
*/
static @Nullable String getCharsetFromContentType(@Nullable String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
charset = charset.replace("charset=", "");
return validateCharset(charset);
}
return null;
}
private @Nullable static String validateCharset(@Nullable String cs) {
if (cs == null || cs.length() == 0) return null;
cs = cs.trim().replaceAll("[\"']", "");
try {
if (Charset.isSupported(cs)) return cs;
cs = cs.toUpperCase(Locale.ENGLISH);
if (Charset.isSupported(cs)) return cs;
} catch (IllegalCharsetNameException e) {
// if our this charset matching fails.... we just take the default
}
return null;
}
/**
* Creates a random string, suitable for use as a mime boundary
*/
static String mimeBoundary() {
final StringBuilder mime = StringUtil.borrowBuilder();
final Random rand = new Random();
for (int i = 0; i < boundaryLength; i++) {
mime.append(mimeBoundaryChars[rand.nextInt(mimeBoundaryChars.length)]);
}
return StringUtil.releaseBuilder(mime);
}
private static @Nullable BomCharset detectCharsetFromBom(final ByteBuffer byteData) {
@SuppressWarnings("UnnecessaryLocalVariable") final Buffer buffer = byteData; // .mark and rewind used to return Buffer, now ByteBuffer, so cast for backward compat
buffer.mark();
byte[] bom = new byte[4];
if (byteData.remaining() >= bom.length) {
byteData.get(bom);
buffer.rewind();
}
if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF || // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { // LE
return new BomCharset("UTF-32", false); // and I hope it's on your system
} else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF || // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {
return new BomCharset("UTF-16", false); // in all Javas
} else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) {
return new BomCharset("UTF-8", true); // in all Javas
// 16 and 32 decoders consume the BOM to determine be/le; utf-8 should be consumed here
}
return null;
}
private static class BomCharset {
private final String charset;
private final boolean offset;
public BomCharset(String charset, boolean offset) {
this.charset = charset;
this.offset = offset;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/HttpConnection.java
|
package org.jsoup.helper;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.UncheckedIOException;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.internal.ConstrainableInputStream;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.parser.TokenQueue;
import javax.annotation.Nullable;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.CookieManager;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.IDN;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import static org.jsoup.Connection.Method.HEAD;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
* Implementation of {@link Connection}.
* @see org.jsoup.Jsoup#connect(String)
*/
@SuppressWarnings("CharsetObjectCanBeUsed")
public class HttpConnection implements Connection {
public static final String CONTENT_ENCODING = "Content-Encoding";
/**
* Many users would get caught by not setting a user-agent and therefore getting different responses on their desktop
* vs in jsoup, which would otherwise default to {@code Java}. So by default, use a desktop UA.
*/
public static final String DEFAULT_UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36";
private static final String USER_AGENT = "User-Agent";
public static final String CONTENT_TYPE = "Content-Type";
public static final String MULTIPART_FORM_DATA = "multipart/form-data";
public static final String FORM_URL_ENCODED = "application/x-www-form-urlencoded";
private static final int HTTP_TEMP_REDIR = 307; // http/1.1 temporary redirect, not in Java's set.
private static final String DefaultUploadType = "application/octet-stream";
private static final Charset UTF_8 = Charset.forName("UTF-8"); // Don't use StandardCharsets, not in Android API 10.
private static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1");
/**
Create a new Connection, with the request URL specified.
@param url the URL to fetch from
@return a new Connection object
*/
public static Connection connect(String url) {
Connection con = new HttpConnection();
con.url(url);
return con;
}
/**
Create a new Connection, with the request URL specified.
@param url the URL to fetch from
@return a new Connection object
*/
public static Connection connect(URL url) {
Connection con = new HttpConnection();
con.url(url);
return con;
}
/**
Creates a new, empty HttpConnection.
*/
public HttpConnection() {
req = new Request();
}
/**
Create a new Request by deep-copying an existing Request
@param copy the request to copy
*/
HttpConnection(Request copy) {
req = new Request(copy);
}
/**
* Encodes the input URL into a safe ASCII URL string
* @param url unescaped URL
* @return escaped URL
*/
private static String encodeUrl(String url) {
try {
URL u = new URL(url);
return encodeUrl(u).toExternalForm();
} catch (Exception e) {
return url;
}
}
static URL encodeUrl(URL u) {
u = punyUrl(u);
try {
// odd way to encode urls, but it works!
String urlS = u.toExternalForm(); // URL external form may have spaces which is illegal in new URL() (odd asymmetry)
urlS = urlS.replace(" ", "%20");
final URI uri = new URI(urlS);
return new URL(uri.toASCIIString());
} catch (URISyntaxException | MalformedURLException e) {
// give up and return the original input
return u;
}
}
/**
Convert an International URL to a Punycode URL.
@param url input URL that may include an international hostname
@return a punycode URL if required, or the original URL
*/
private static URL punyUrl(URL url) {
if (!StringUtil.isAscii(url.getHost())) {
try {
String puny = IDN.toASCII(url.getHost());
url = new URL(url.getProtocol(), puny, url.getPort(), url.getFile()); // file will include ref, query if any
} catch (MalformedURLException e) {
// if passed a valid URL initially, cannot happen
throw new IllegalArgumentException(e);
}
}
return url;
}
private static String encodeMimeName(String val) {
return val.replace("\"", "%22");
}
private HttpConnection.Request req;
private @Nullable Connection.Response res;
@Override
public Connection newRequest() {
// copy the prototype request for the different settings, cookie manager, etc
return new HttpConnection(req);
}
/** Create a new Connection that just wraps the provided Request and Response */
private HttpConnection(Request req, Response res) {
this.req = req;
this.res = res;
}
public Connection url(URL url) {
req.url(url);
return this;
}
public Connection url(String url) {
Validate.notEmpty(url, "Must supply a valid URL");
try {
req.url(new URL(encodeUrl(url)));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Malformed URL: " + url, e);
}
return this;
}
public Connection proxy(@Nullable Proxy proxy) {
req.proxy(proxy);
return this;
}
public Connection proxy(String host, int port) {
req.proxy(host, port);
return this;
}
public Connection userAgent(String userAgent) {
Validate.notNull(userAgent, "User agent must not be null");
req.header(USER_AGENT, userAgent);
return this;
}
public Connection timeout(int millis) {
req.timeout(millis);
return this;
}
public Connection maxBodySize(int bytes) {
req.maxBodySize(bytes);
return this;
}
public Connection followRedirects(boolean followRedirects) {
req.followRedirects(followRedirects);
return this;
}
public Connection referrer(String referrer) {
Validate.notNull(referrer, "Referrer must not be null");
req.header("Referer", referrer);
return this;
}
public Connection method(Method method) {
req.method(method);
return this;
}
public Connection ignoreHttpErrors(boolean ignoreHttpErrors) {
req.ignoreHttpErrors(ignoreHttpErrors);
return this;
}
public Connection ignoreContentType(boolean ignoreContentType) {
req.ignoreContentType(ignoreContentType);
return this;
}
public Connection data(String key, String value) {
req.data(KeyVal.create(key, value));
return this;
}
public Connection sslSocketFactory(SSLSocketFactory sslSocketFactory) {
req.sslSocketFactory(sslSocketFactory);
return this;
}
public Connection data(String key, String filename, InputStream inputStream) {
req.data(KeyVal.create(key, filename, inputStream));
return this;
}
@Override
public Connection data(String key, String filename, InputStream inputStream, String contentType) {
req.data(KeyVal.create(key, filename, inputStream).contentType(contentType));
return this;
}
public Connection data(Map<String, String> data) {
Validate.notNull(data, "Data map must not be null");
for (Map.Entry<String, String> entry : data.entrySet()) {
req.data(KeyVal.create(entry.getKey(), entry.getValue()));
}
return this;
}
public Connection data(String... keyvals) {
Validate.notNull(keyvals, "Data key value pairs must not be null");
Validate.isTrue(keyvals.length %2 == 0, "Must supply an even number of key value pairs");
for (int i = 0; i < keyvals.length; i += 2) {
String key = keyvals[i];
String value = keyvals[i+1];
Validate.notEmpty(key, "Data key must not be empty");
Validate.notNull(value, "Data value must not be null");
req.data(KeyVal.create(key, value));
}
return this;
}
public Connection data(Collection<Connection.KeyVal> data) {
Validate.notNull(data, "Data collection must not be null");
for (Connection.KeyVal entry: data) {
req.data(entry);
}
return this;
}
public Connection.KeyVal data(String key) {
Validate.notEmpty(key, "Data key must not be empty");
for (Connection.KeyVal keyVal : request().data()) {
if (keyVal.key().equals(key))
return keyVal;
}
return null;
}
public Connection requestBody(String body) {
req.requestBody(body);
return this;
}
public Connection header(String name, String value) {
req.header(name, value);
return this;
}
public Connection headers(Map<String,String> headers) {
Validate.notNull(headers, "Header map must not be null");
for (Map.Entry<String,String> entry : headers.entrySet()) {
req.header(entry.getKey(),entry.getValue());
}
return this;
}
public Connection cookie(String name, String value) {
req.cookie(name, value);
return this;
}
public Connection cookies(Map<String, String> cookies) {
Validate.notNull(cookies, "Cookie map must not be null");
for (Map.Entry<String, String> entry : cookies.entrySet()) {
req.cookie(entry.getKey(), entry.getValue());
}
return this;
}
@Override
public Connection cookieStore(CookieStore cookieStore) {
// create a new cookie manager using the new store
req.cookieManager = new CookieManager(cookieStore, null);
return this;
}
@Override
public CookieStore cookieStore() {
return req.cookieManager.getCookieStore();
}
public Connection parser(Parser parser) {
req.parser(parser);
return this;
}
public Document get() throws IOException {
req.method(Method.GET);
execute();
Validate.notNull(res);
return res.parse();
}
public Document post() throws IOException {
req.method(Method.POST);
execute();
Validate.notNull(res);
return res.parse();
}
public Connection.Response execute() throws IOException {
res = Response.execute(req);
return res;
}
public Connection.Request request() {
return req;
}
public Connection request(Connection.Request request) {
req = (HttpConnection.Request) request; // will throw a class-cast exception if the user has extended some but not all of Connection; that's desired
return this;
}
public Connection.Response response() {
if (res == null) {
throw new IllegalArgumentException("You must execute the request before getting a response.");
}
return res;
}
public Connection response(Connection.Response response) {
res = response;
return this;
}
public Connection postDataCharset(String charset) {
req.postDataCharset(charset);
return this;
}
@SuppressWarnings("unchecked")
private static abstract class Base<T extends Connection.Base<T>> implements Connection.Base<T> {
private static final URL UnsetUrl; // only used if you created a new Request()
static {
try {
UnsetUrl = new URL("http://undefined/");
} catch (MalformedURLException e) {
throw new IllegalStateException(e);
}
}
URL url = UnsetUrl;
Method method = Method.GET;
Map<String, List<String>> headers;
Map<String, String> cookies;
private Base() {
headers = new LinkedHashMap<>();
cookies = new LinkedHashMap<>();
}
private Base(Base<T> copy) {
url = copy.url; // unmodifiable object
method = copy.method;
headers = new LinkedHashMap<>();
for (Map.Entry<String, List<String>> entry : copy.headers.entrySet()) {
headers.put(entry.getKey(), new ArrayList<>(entry.getValue()));
}
cookies = new LinkedHashMap<>(); cookies.putAll(copy.cookies); // just holds strings
}
public URL url() {
if (url == UnsetUrl)
throw new IllegalArgumentException("URL not set. Make sure to call #url(...) before executing the request.");
return url;
}
public T url(URL url) {
Validate.notNull(url, "URL must not be null");
this.url = punyUrl(url); // if calling url(url) directly, does not go through encodeUrl, so we punycode it explicitly. todo - should we encode here as well?
return (T) this;
}
public Method method() {
return method;
}
public T method(Method method) {
Validate.notNull(method, "Method must not be null");
this.method = method;
return (T) this;
}
public String header(String name) {
Validate.notNull(name, "Header name must not be null");
List<String> vals = getHeadersCaseInsensitive(name);
if (vals.size() > 0) {
// https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
return StringUtil.join(vals, ", ");
}
return null;
}
@Override
public T addHeader(String name, String value) {
Validate.notEmpty(name);
//noinspection ConstantConditions
value = value == null ? "" : value;
List<String> values = headers(name);
if (values.isEmpty()) {
values = new ArrayList<>();
headers.put(name, values);
}
values.add(fixHeaderEncoding(value));
return (T) this;
}
@Override
public List<String> headers(String name) {
Validate.notEmpty(name);
return getHeadersCaseInsensitive(name);
}
private static String fixHeaderEncoding(String val) {
byte[] bytes = val.getBytes(ISO_8859_1);
if (!looksLikeUtf8(bytes))
return val;
return new String(bytes, UTF_8);
}
private static boolean looksLikeUtf8(byte[] input) {
int i = 0;
// BOM:
if (input.length >= 3
&& (input[0] & 0xFF) == 0xEF
&& (input[1] & 0xFF) == 0xBB
&& (input[2] & 0xFF) == 0xBF) {
i = 3;
}
int end;
for (int j = input.length; i < j; ++i) {
int o = input[i];
if ((o & 0x80) == 0) {
continue; // ASCII
}
// UTF-8 leading:
if ((o & 0xE0) == 0xC0) {
end = i + 1;
} else if ((o & 0xF0) == 0xE0) {
end = i + 2;
} else if ((o & 0xF8) == 0xF0) {
end = i + 3;
} else {
return false;
}
if (end >= input.length)
return false;
while (i < end) {
i++;
o = input[i];
if ((o & 0xC0) != 0x80) {
return false;
}
}
}
return true;
}
public T header(String name, String value) {
Validate.notEmpty(name, "Header name must not be empty");
removeHeader(name); // ensures we don't get an "accept-encoding" and a "Accept-Encoding"
addHeader(name, value);
return (T) this;
}
public boolean hasHeader(String name) {
Validate.notEmpty(name, "Header name must not be empty");
return !getHeadersCaseInsensitive(name).isEmpty();
}
/**
* Test if the request has a header with this value (case insensitive).
*/
public boolean hasHeaderWithValue(String name, String value) {
Validate.notEmpty(name);
Validate.notEmpty(value);
List<String> values = headers(name);
for (String candidate : values) {
if (value.equalsIgnoreCase(candidate))
return true;
}
return false;
}
public T removeHeader(String name) {
Validate.notEmpty(name, "Header name must not be empty");
Map.Entry<String, List<String>> entry = scanHeaders(name); // remove is case insensitive too
if (entry != null)
headers.remove(entry.getKey()); // ensures correct case
return (T) this;
}
public Map<String, String> headers() {
LinkedHashMap<String, String> map = new LinkedHashMap<>(headers.size());
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
String header = entry.getKey();
List<String> values = entry.getValue();
if (values.size() > 0)
map.put(header, values.get(0));
}
return map;
}
@Override
public Map<String, List<String>> multiHeaders() {
return headers;
}
private List<String> getHeadersCaseInsensitive(String name) {
Validate.notNull(name);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (name.equalsIgnoreCase(entry.getKey()))
return entry.getValue();
}
return Collections.emptyList();
}
private @Nullable Map.Entry<String, List<String>> scanHeaders(String name) {
String lc = lowerCase(name);
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
if (lowerCase(entry.getKey()).equals(lc))
return entry;
}
return null;
}
public String cookie(String name) {
Validate.notEmpty(name, "Cookie name must not be empty");
return cookies.get(name);
}
public T cookie(String name, String value) {
Validate.notEmpty(name, "Cookie name must not be empty");
Validate.notNull(value, "Cookie value must not be null");
cookies.put(name, value);
return (T) this;
}
public boolean hasCookie(String name) {
Validate.notEmpty(name, "Cookie name must not be empty");
return cookies.containsKey(name);
}
public T removeCookie(String name) {
Validate.notEmpty(name, "Cookie name must not be empty");
cookies.remove(name);
return (T) this;
}
public Map<String, String> cookies() {
return cookies;
}
}
public static class Request extends HttpConnection.Base<Connection.Request> implements Connection.Request {
static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
// make sure that we can send Sec-Fetch-Site headers etc.
}
private @Nullable Proxy proxy;
private int timeoutMilliseconds;
private int maxBodySizeBytes;
private boolean followRedirects;
private final Collection<Connection.KeyVal> data;
private @Nullable String body = null;
private boolean ignoreHttpErrors = false;
private boolean ignoreContentType = false;
private Parser parser;
private boolean parserDefined = false; // called parser(...) vs initialized in ctor
private String postDataCharset = DataUtil.defaultCharsetName;
private @Nullable SSLSocketFactory sslSocketFactory;
private CookieManager cookieManager;
private volatile boolean executing = false;
Request() {
super();
timeoutMilliseconds = 30000; // 30 seconds
maxBodySizeBytes = 1024 * 1024 * 2; // 2MB
followRedirects = true;
data = new ArrayList<>();
method = Method.GET;
addHeader("Accept-Encoding", "gzip");
addHeader(USER_AGENT, DEFAULT_UA);
parser = Parser.htmlParser();
cookieManager = new CookieManager(); // creates a default InMemoryCookieStore
}
Request(Request copy) {
super(copy);
proxy = copy.proxy;
postDataCharset = copy.postDataCharset;
timeoutMilliseconds = copy.timeoutMilliseconds;
maxBodySizeBytes = copy.maxBodySizeBytes;
followRedirects = copy.followRedirects;
data = new ArrayList<>(); data.addAll(copy.data()); // this is shallow, but holds immutable string keyval, and possibly an InputStream which can only be read once anyway, so using as a prototype would be unsupported
body = copy.body;
ignoreHttpErrors = copy.ignoreHttpErrors;
ignoreContentType = copy.ignoreContentType;
parser = copy.parser.newInstance(); // parsers and their tree-builders maintain state, so need a fresh copy
parserDefined = copy.parserDefined;
sslSocketFactory = copy.sslSocketFactory; // these are all synchronized so safe to share
cookieManager = copy.cookieManager;
executing = false;
}
public Proxy proxy() {
return proxy;
}
public Request proxy(@Nullable Proxy proxy) {
this.proxy = proxy;
return this;
}
public Request proxy(String host, int port) {
this.proxy = new Proxy(Proxy.Type.HTTP, InetSocketAddress.createUnresolved(host, port));
return this;
}
public int timeout() {
return timeoutMilliseconds;
}
public Request timeout(int millis) {
Validate.isTrue(millis >= 0, "Timeout milliseconds must be 0 (infinite) or greater");
timeoutMilliseconds = millis;
return this;
}
public int maxBodySize() {
return maxBodySizeBytes;
}
public Connection.Request maxBodySize(int bytes) {
Validate.isTrue(bytes >= 0, "maxSize must be 0 (unlimited) or larger");
maxBodySizeBytes = bytes;
return this;
}
public boolean followRedirects() {
return followRedirects;
}
public Connection.Request followRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
return this;
}
public boolean ignoreHttpErrors() {
return ignoreHttpErrors;
}
public SSLSocketFactory sslSocketFactory() {
return sslSocketFactory;
}
public void sslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
public Connection.Request ignoreHttpErrors(boolean ignoreHttpErrors) {
this.ignoreHttpErrors = ignoreHttpErrors;
return this;
}
public boolean ignoreContentType() {
return ignoreContentType;
}
public Connection.Request ignoreContentType(boolean ignoreContentType) {
this.ignoreContentType = ignoreContentType;
return this;
}
public Request data(Connection.KeyVal keyval) {
Validate.notNull(keyval, "Key val must not be null");
data.add(keyval);
return this;
}
public Collection<Connection.KeyVal> data() {
return data;
}
public Connection.Request requestBody(@Nullable String body) {
this.body = body;
return this;
}
public String requestBody() {
return body;
}
public Request parser(Parser parser) {
this.parser = parser;
parserDefined = true;
return this;
}
public Parser parser() {
return parser;
}
public Connection.Request postDataCharset(String charset) {
Validate.notNull(charset, "Charset must not be null");
if (!Charset.isSupported(charset)) throw new IllegalCharsetNameException(charset);
this.postDataCharset = charset;
return this;
}
public String postDataCharset() {
return postDataCharset;
}
CookieManager cookieManager() {
return cookieManager;
}
}
public static class Response extends HttpConnection.Base<Connection.Response> implements Connection.Response {
private static final int MAX_REDIRECTS = 20;
private static final String LOCATION = "Location";
private final int statusCode;
private final String statusMessage;
private @Nullable ByteBuffer byteData;
private @Nullable InputStream bodyStream;
private @Nullable HttpURLConnection conn;
private @Nullable String charset;
private @Nullable final String contentType;
private boolean executed = false;
private boolean inputStreamRead = false;
private int numRedirects = 0;
private final HttpConnection.Request req;
/*
* Matches XML content types (like text/xml, application/xhtml+xml;charset=UTF8, etc)
*/
private static final Pattern xmlContentTypeRxp = Pattern.compile("(application|text)/\\w*\\+?xml.*");
/**
<b>Internal only! </b>Creates a dummy HttpConnection.Response, useful for testing. All actual responses
are created from the HttpURLConnection and fields defined.
*/
Response() {
super();
statusCode = 400;
statusMessage = "Request not made";
req = new Request();
contentType = null;
}
static Response execute(HttpConnection.Request req) throws IOException {
return execute(req, null);
}
static Response execute(HttpConnection.Request req, @Nullable Response previousResponse) throws IOException {
synchronized (req) {
Validate.isFalse(req.executing, "Multiple threads were detected trying to execute the same request concurrently. Make sure to use Connection#newRequest() and do not share an executing request between threads.");
req.executing = true;
}
Validate.notNull(req, "Request must not be null");
URL url = req.url();
Validate.notNull(url, "URL must be specified to connect");
String protocol = url.getProtocol();
if (!protocol.equals("http") && !protocol.equals("https"))
throw new MalformedURLException("Only http & https protocols supported");
final boolean methodHasBody = req.method().hasBody();
final boolean hasRequestBody = req.requestBody() != null;
if (!methodHasBody)
Validate.isFalse(hasRequestBody, "Cannot set a request body for HTTP method " + req.method());
// set up the request for execution
String mimeBoundary = null;
if (req.data().size() > 0 && (!methodHasBody || hasRequestBody))
serialiseRequestUrl(req);
else if (methodHasBody)
mimeBoundary = setOutputContentType(req);
long startTime = System.nanoTime();
HttpURLConnection conn = createConnection(req);
Response res = null;
try {
conn.connect();
if (conn.getDoOutput()) {
OutputStream out = conn.getOutputStream();
try { writePost(req, out, mimeBoundary); }
catch (IOException e) { conn.disconnect(); throw e; }
finally { out.close(); }
}
int status = conn.getResponseCode();
res = new Response(conn, req, previousResponse);
// redirect if there's a location header (from 3xx, or 201 etc)
if (res.hasHeader(LOCATION) && req.followRedirects()) {
if (status != HTTP_TEMP_REDIR) {
req.method(Method.GET); // always redirect with a get. any data param from original req are dropped.
req.data().clear();
req.requestBody(null);
req.removeHeader(CONTENT_TYPE);
}
String location = res.header(LOCATION);
Validate.notNull(location);
if (location.startsWith("http:/") && location.charAt(6) != '/') // fix broken Location: http:/temp/AAG_New/en/index.php
location = location.substring(6);
URL redir = StringUtil.resolve(req.url(), location);
req.url(encodeUrl(redir));
req.executing = false;
return execute(req, res);
}
if ((status < 200 || status >= 400) && !req.ignoreHttpErrors())
throw new HttpStatusException("HTTP error fetching URL", status, req.url().toString());
// check that we can handle the returned content type; if not, abort before fetching it
String contentType = res.contentType();
if (contentType != null
&& !req.ignoreContentType()
&& !contentType.startsWith("text/")
&& !xmlContentTypeRxp.matcher(contentType).matches()
)
throw new UnsupportedMimeTypeException("Unhandled content type. Must be text/*, application/xml, or application/*+xml",
contentType, req.url().toString());
// switch to the XML parser if content type is xml and not parser not explicitly set
if (contentType != null && xmlContentTypeRxp.matcher(contentType).matches()) {
if (!req.parserDefined) req.parser(Parser.xmlParser());
}
res.charset = DataUtil.getCharsetFromContentType(res.contentType); // may be null, readInputStream deals with it
if (conn.getContentLength() != 0 && req.method() != HEAD) { // -1 means unknown, chunked. sun throws an IO exception on 500 response with no content when trying to read body
res.bodyStream = conn.getErrorStream() != null ? conn.getErrorStream() : conn.getInputStream();
Validate.notNull(res.bodyStream);
if (res.hasHeaderWithValue(CONTENT_ENCODING, "gzip")) {
res.bodyStream = new GZIPInputStream(res.bodyStream);
} else if (res.hasHeaderWithValue(CONTENT_ENCODING, "deflate")) {
res.bodyStream = new InflaterInputStream(res.bodyStream, new Inflater(true));
}
res.bodyStream = ConstrainableInputStream
.wrap(res.bodyStream, DataUtil.bufferSize, req.maxBodySize())
.timeout(startTime, req.timeout())
;
} else {
res.byteData = DataUtil.emptyByteBuffer();
}
} catch (IOException e) {
if (res != null) res.safeClose(); // will be non-null if got to conn
throw e;
} finally {
req.executing = false;
}
res.executed = true;
return res;
}
public int statusCode() {
return statusCode;
}
public String statusMessage() {
return statusMessage;
}
public String charset() {
return charset;
}
public Response charset(String charset) {
this.charset = charset;
return this;
}
public String contentType() {
return contentType;
}
public Document parse() throws IOException {
Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before parsing response");
if (byteData != null) { // bytes have been read in to the buffer, parse that
bodyStream = new ByteArrayInputStream(byteData.array());
inputStreamRead = false; // ok to reparse if in bytes
}
Validate.isFalse(inputStreamRead, "Input stream already read and parsed, cannot re-read.");
Document doc = DataUtil.parseInputStream(bodyStream, charset, url.toExternalForm(), req.parser());
doc.connection(new HttpConnection(req, this)); // because we're static, don't have the connection obj. // todo - maybe hold in the req?
charset = doc.outputSettings().charset().name(); // update charset from meta-equiv, possibly
inputStreamRead = true;
safeClose();
return doc;
}
private void prepareByteData() {
Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body");
if (bodyStream != null && byteData == null) {
Validate.isFalse(inputStreamRead, "Request has already been read (with .parse())");
try {
byteData = DataUtil.readToByteBuffer(bodyStream, req.maxBodySize());
} catch (IOException e) {
throw new UncheckedIOException(e);
} finally {
inputStreamRead = true;
safeClose();
}
}
}
public String body() {
prepareByteData();
Validate.notNull(byteData);
// charset gets set from header on execute, and from meta-equiv on parse. parse may not have happened yet
String body = (charset == null ? DataUtil.UTF_8 : Charset.forName(charset))
.decode(byteData).toString();
((Buffer)byteData).rewind(); // cast to avoid covariant return type change in jdk9
return body;
}
public byte[] bodyAsBytes() {
prepareByteData();
Validate.notNull(byteData);
return byteData.array();
}
@Override
public Connection.Response bufferUp() {
prepareByteData();
return this;
}
@Override
public BufferedInputStream bodyStream() {
Validate.isTrue(executed, "Request must be executed (with .execute(), .get(), or .post() before getting response body");
Validate.isFalse(inputStreamRead, "Request has already been read");
inputStreamRead = true;
return ConstrainableInputStream.wrap(bodyStream, DataUtil.bufferSize, req.maxBodySize());
}
// set up connection defaults, and details from request
private static HttpURLConnection createConnection(HttpConnection.Request req) throws IOException {
Proxy proxy = req.proxy();
final HttpURLConnection conn = (HttpURLConnection) (
proxy == null ?
req.url().openConnection() :
req.url().openConnection(proxy)
);
conn.setRequestMethod(req.method().name());
conn.setInstanceFollowRedirects(false); // don't rely on native redirection support
conn.setConnectTimeout(req.timeout());
conn.setReadTimeout(req.timeout() / 2); // gets reduced after connection is made and status is read
if (req.sslSocketFactory() != null && conn instanceof HttpsURLConnection)
((HttpsURLConnection) conn).setSSLSocketFactory(req.sslSocketFactory());
if (req.method().hasBody())
conn.setDoOutput(true);
CookieUtil.applyCookiesToRequest(req, conn); // from the Request key/val cookies and the Cookie Store
for (Map.Entry<String, List<String>> header : req.multiHeaders().entrySet()) {
for (String value : header.getValue()) {
conn.addRequestProperty(header.getKey(), value);
}
}
return conn;
}
/**
* Call on completion of stream read, to close the body (or error) stream. The connection.disconnect allows
* keep-alives to work (as the underlying connection is actually held open, despite the name).
*/
private void safeClose() {
if (bodyStream != null) {
try {
bodyStream.close();
} catch (IOException e) {
// no-op
} finally {
bodyStream = null;
}
}
if (conn != null) {
conn.disconnect();
conn = null;
}
}
// set up url, method, header, cookies
private Response(HttpURLConnection conn, HttpConnection.Request request, @Nullable HttpConnection.Response previousResponse) throws IOException {
this.conn = conn;
this.req = request;
method = Method.valueOf(conn.getRequestMethod());
url = conn.getURL();
statusCode = conn.getResponseCode();
statusMessage = conn.getResponseMessage();
contentType = conn.getContentType();
Map<String, List<String>> resHeaders = createHeaderMap(conn);
processResponseHeaders(resHeaders); // includes cookie key/val read during header scan
CookieUtil.storeCookies(req, url, resHeaders); // add set cookies to cookie store
if (previousResponse != null) { // was redirected
// map previous response cookies into this response cookies() object
for (Map.Entry<String, String> prevCookie : previousResponse.cookies().entrySet()) {
if (!hasCookie(prevCookie.getKey()))
cookie(prevCookie.getKey(), prevCookie.getValue());
}
previousResponse.safeClose();
// enforce too many redirects:
numRedirects = previousResponse.numRedirects + 1;
if (numRedirects >= MAX_REDIRECTS)
throw new IOException(String.format("Too many redirects occurred trying to load URL %s", previousResponse.url()));
}
}
private static LinkedHashMap<String, List<String>> createHeaderMap(HttpURLConnection conn) {
// the default sun impl of conn.getHeaderFields() returns header values out of order
final LinkedHashMap<String, List<String>> headers = new LinkedHashMap<>();
int i = 0;
while (true) {
final String key = conn.getHeaderFieldKey(i);
final String val = conn.getHeaderField(i);
if (key == null && val == null)
break;
i++;
if (key == null || val == null)
continue; // skip http1.1 line
if (headers.containsKey(key))
headers.get(key).add(val);
else {
final ArrayList<String> vals = new ArrayList<>();
vals.add(val);
headers.put(key, vals);
}
}
return headers;
}
void processResponseHeaders(Map<String, List<String>> resHeaders) {
for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
String name = entry.getKey();
if (name == null)
continue; // http/1.1 line
List<String> values = entry.getValue();
if (name.equalsIgnoreCase("Set-Cookie")) {
for (String value : values) {
if (value == null)
continue;
TokenQueue cd = new TokenQueue(value);
String cookieName = cd.chompTo("=").trim();
String cookieVal = cd.consumeTo(";").trim();
// ignores path, date, domain, validateTLSCertificates et al. full details will be available in cookiestore if required
// name not blank, value not null
if (cookieName.length() > 0 && !cookies.containsKey(cookieName)) // if duplicates, only keep the first
cookie(cookieName, cookieVal);
}
}
for (String value : values) {
addHeader(name, value);
}
}
}
private @Nullable static String setOutputContentType(final Connection.Request req) {
final String contentType = req.header(CONTENT_TYPE);
String bound = null;
if (contentType != null) {
// no-op; don't add content type as already set (e.g. for requestBody())
// todo - if content type already set, we could add charset
// if user has set content type to multipart/form-data, auto add boundary.
if(contentType.contains(MULTIPART_FORM_DATA) && !contentType.contains("boundary")) {
bound = DataUtil.mimeBoundary();
req.header(CONTENT_TYPE, MULTIPART_FORM_DATA + "; boundary=" + bound);
}
}
else if (needsMultipart(req)) {
bound = DataUtil.mimeBoundary();
req.header(CONTENT_TYPE, MULTIPART_FORM_DATA + "; boundary=" + bound);
} else {
req.header(CONTENT_TYPE, FORM_URL_ENCODED + "; charset=" + req.postDataCharset());
}
return bound;
}
private static void writePost(final Connection.Request req, final OutputStream outputStream, @Nullable final String boundary) throws IOException {
final Collection<Connection.KeyVal> data = req.data();
final BufferedWriter w = new BufferedWriter(new OutputStreamWriter(outputStream, req.postDataCharset()));
if (boundary != null) {
// boundary will be set if we're in multipart mode
for (Connection.KeyVal keyVal : data) {
w.write("--");
w.write(boundary);
w.write("\r\n");
w.write("Content-Disposition: form-data; name=\"");
w.write(encodeMimeName(keyVal.key())); // encodes " to %22
w.write("\"");
final InputStream input = keyVal.inputStream();
if (input != null) {
w.write("; filename=\"");
w.write(encodeMimeName(keyVal.value()));
w.write("\"\r\nContent-Type: ");
String contentType = keyVal.contentType();
w.write(contentType != null ? contentType : DefaultUploadType);
w.write("\r\n\r\n");
w.flush(); // flush
DataUtil.crossStreams(input, outputStream);
outputStream.flush();
} else {
w.write("\r\n\r\n");
w.write(keyVal.value());
}
w.write("\r\n");
}
w.write("--");
w.write(boundary);
w.write("--");
} else {
String body = req.requestBody();
if (body != null) {
// data will be in query string, we're sending a plaintext body
w.write(body);
}
else {
// regular form data (application/x-www-form-urlencoded)
boolean first = true;
for (Connection.KeyVal keyVal : data) {
if (!first)
w.append('&');
else
first = false;
w.write(URLEncoder.encode(keyVal.key(), req.postDataCharset()));
w.write('=');
w.write(URLEncoder.encode(keyVal.value(), req.postDataCharset()));
}
}
}
w.close();
}
// for get url reqs, serialise the data map into the url
private static void serialiseRequestUrl(Connection.Request req) throws IOException {
URL in = req.url();
StringBuilder url = StringUtil.borrowBuilder();
boolean first = true;
// reconstitute the query, ready for appends
url
.append(in.getProtocol())
.append("://")
.append(in.getAuthority()) // includes host, port
.append(in.getPath())
.append("?");
if (in.getQuery() != null) {
url.append(in.getQuery());
first = false;
}
for (Connection.KeyVal keyVal : req.data()) {
Validate.isFalse(keyVal.hasInputStream(), "InputStream data not supported in URL query string.");
if (!first)
url.append('&');
else
first = false;
url
.append(URLEncoder.encode(keyVal.key(), DataUtil.defaultCharsetName))
.append('=')
.append(URLEncoder.encode(keyVal.value(), DataUtil.defaultCharsetName));
}
req.url(new URL(StringUtil.releaseBuilder(url)));
req.data().clear(); // moved into url as get params
}
}
private static boolean needsMultipart(Connection.Request req) {
// multipart mode, for files. add the header if we see something with an inputstream, and return a non-null boundary
for (Connection.KeyVal keyVal : req.data()) {
if (keyVal.hasInputStream())
return true;
}
return false;
}
public static class KeyVal implements Connection.KeyVal {
private String key;
private String value;
private @Nullable InputStream stream;
private @Nullable String contentType;
public static KeyVal create(String key, String value) {
return new KeyVal(key, value);
}
public static KeyVal create(String key, String filename, InputStream stream) {
return new KeyVal(key, filename)
.inputStream(stream);
}
private KeyVal(String key, String value) {
Validate.notEmpty(key, "Data key must not be empty");
Validate.notNull(value, "Data value must not be null");
this.key = key;
this.value = value;
}
public KeyVal key(String key) {
Validate.notEmpty(key, "Data key must not be empty");
this.key = key;
return this;
}
public String key() {
return key;
}
public KeyVal value(String value) {
Validate.notNull(value, "Data value must not be null");
this.value = value;
return this;
}
public String value() {
return value;
}
public KeyVal inputStream(InputStream inputStream) {
Validate.notNull(value, "Data input stream must not be null");
this.stream = inputStream;
return this;
}
public InputStream inputStream() {
return stream;
}
public boolean hasInputStream() {
return stream != null;
}
@Override
public Connection.KeyVal contentType(String contentType) {
Validate.notEmpty(contentType);
this.contentType = contentType;
return this;
}
@Override
public String contentType() {
return contentType;
}
@Override
public String toString() {
return key + "=" + value;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/Validate.java
|
package org.jsoup.helper;
import javax.annotation.Nullable;
/**
* Simple validation methods. Designed for jsoup internal use
*/
public final class Validate {
private Validate() {}
/**
* Validates that the object is not null
* @param obj object to test
*/
public static void notNull(@Nullable Object obj) {
if (obj == null)
throw new IllegalArgumentException("Object must not be null");
}
/**
* Validates that the object is not null
* @param obj object to test
* @param msg message to output if validation fails
*/
public static void notNull(@Nullable Object obj, String msg) {
if (obj == null)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the value is true
* @param val object to test
*/
public static void isTrue(boolean val) {
if (!val)
throw new IllegalArgumentException("Must be true");
}
/**
* Validates that the value is true
* @param val object to test
* @param msg message to output if validation fails
*/
public static void isTrue(boolean val, String msg) {
if (!val)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the value is false
* @param val object to test
*/
public static void isFalse(boolean val) {
if (val)
throw new IllegalArgumentException("Must be false");
}
/**
* Validates that the value is false
* @param val object to test
* @param msg message to output if validation fails
*/
public static void isFalse(boolean val, String msg) {
if (val)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the array contains no null elements
* @param objects the array to test
*/
public static void noNullElements(Object[] objects) {
noNullElements(objects, "Array must not contain any null objects");
}
/**
* Validates that the array contains no null elements
* @param objects the array to test
* @param msg message to output if validation fails
*/
public static void noNullElements(Object[] objects, String msg) {
for (Object obj : objects)
if (obj == null)
throw new IllegalArgumentException(msg);
}
/**
* Validates that the string is not null and is not empty
* @param string the string to test
*/
public static void notEmpty(@Nullable String string) {
if (string == null || string.length() == 0)
throw new IllegalArgumentException("String must not be empty");
}
/**
* Validates that the string is not null and is not empty
* @param string the string to test
* @param msg message to output if validation fails
*/
public static void notEmpty(@Nullable String string, String msg) {
if (string == null || string.length() == 0)
throw new IllegalArgumentException(msg);
}
/**
* Blow up if we reach an unexpected state.
* @param msg message to think about
*/
public static void wtf(String msg) {
throw new IllegalStateException(msg);
}
/**
Cause a failure.
@param msg message to output.
*/
public static void fail(String msg) {
throw new IllegalArgumentException(msg);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/W3CDom.java
|
package org.jsoup.helper;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.jsoup.select.Selector;
import org.w3c.dom.Comment;
import org.w3c.dom.DOMException;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import javax.annotation.Nullable;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFactoryConfigurationException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.regex.Pattern;
import static javax.xml.transform.OutputKeys.METHOD;
import static org.jsoup.nodes.Document.OutputSettings.Syntax.xml;
/**
* Helper class to transform a {@link org.jsoup.nodes.Document} to a {@link org.w3c.dom.Document org.w3c.dom.Document},
* for integration with toolsets that use the W3C DOM.
*/
public class W3CDom {
/** For W3C Documents created by this class, this property is set on each node to link back to the original jsoup node. */
public static final String SourceProperty = "jsoupSource";
/**
To get support for XPath versions > 1, set this property to the classname of an alternate XPathFactory
implementation (e.g. {@code net.sf.saxon.xpath.XPathFactoryImpl}).
*/
public static final String XPathFactoryProperty = "javax.xml.xpath.XPathFactory:jsoup";
protected DocumentBuilderFactory factory;
public W3CDom() {
factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
}
/**
* Converts a jsoup DOM to a W3C DOM.
*
* @param in jsoup Document
* @return W3C Document
*/
public static Document convert(org.jsoup.nodes.Document in) {
return (new W3CDom().fromJsoup(in));
}
/**
* Serialize a W3C document to a String. Provide Properties to define output settings including if HTML or XML. If
* you don't provide the properties ({@code null}), the output will be auto-detected based on the content of the
* document.
*
* @param doc Document
* @param properties (optional/nullable) the output properties to use. See {@link
* Transformer#setOutputProperties(Properties)} and {@link OutputKeys}
* @return Document as string
* @see #OutputHtml
* @see #OutputXml
* @see OutputKeys#ENCODING
* @see OutputKeys#OMIT_XML_DECLARATION
* @see OutputKeys#STANDALONE
* @see OutputKeys#STANDALONE
* @see OutputKeys#DOCTYPE_PUBLIC
* @see OutputKeys#DOCTYPE_PUBLIC
* @see OutputKeys#CDATA_SECTION_ELEMENTS
* @see OutputKeys#INDENT
* @see OutputKeys#MEDIA_TYPE
*/
public static String asString(Document doc, @Nullable Map<String, String> properties) {
try {
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
if (properties != null)
transformer.setOutputProperties(propertiesFromMap(properties));
if (doc.getDoctype() != null) {
DocumentType doctype = doc.getDoctype();
if (!StringUtil.isBlank(doctype.getPublicId()))
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
if (!StringUtil.isBlank(doctype.getSystemId()))
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
// handle <!doctype html> for legacy dom. TODO: nicer if <!doctype html>
else if (doctype.getName().equalsIgnoreCase("html")
&& StringUtil.isBlank(doctype.getPublicId())
&& StringUtil.isBlank(doctype.getSystemId()))
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "about:legacy-compat");
}
transformer.transform(domSource, result);
return writer.toString();
} catch (TransformerException e) {
throw new IllegalStateException(e);
}
}
static Properties propertiesFromMap(Map<String, String> map) {
Properties props = new Properties();
props.putAll(map);
return props;
}
/** Canned default for HTML output. */
public static HashMap<String, String> OutputHtml() {
return methodMap("html");
}
/** Canned default for XML output. */
public static HashMap<String, String> OutputXml() {
return methodMap("xml");
}
private static HashMap<String, String> methodMap(String method) {
HashMap<String, String> map = new HashMap<>();
map.put(METHOD, method);
return map;
}
/**
* Convert a jsoup Document to a W3C Document. The created nodes will link back to the original
* jsoup nodes in the user property {@link #SourceProperty} (but after conversion, changes on one side will not
* flow to the other).
*
* @param in jsoup doc
* @return a W3C DOM Document representing the jsoup Document or Element contents.
*/
public Document fromJsoup(org.jsoup.nodes.Document in) {
// just method API backcompat
return fromJsoup((org.jsoup.nodes.Element) in);
}
/**
* Convert a jsoup Element to a W3C Document. The created nodes will link back to the original
* jsoup nodes in the user property {@link #SourceProperty} (but after conversion, changes on one side will not
* flow to the other).
*
* @param in jsoup element or doc
* @return a W3C DOM Document representing the jsoup Document or Element contents.
*/
public Document fromJsoup(org.jsoup.nodes.Element in) {
Validate.notNull(in);
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
DOMImplementation impl = builder.getDOMImplementation();
Document out;
out = builder.newDocument();
org.jsoup.nodes.Document inDoc = in.ownerDocument();
org.jsoup.nodes.DocumentType doctype = inDoc != null ? inDoc.documentType() : null;
if (doctype != null) {
org.w3c.dom.DocumentType documentType = impl.createDocumentType(doctype.name(), doctype.publicId(), doctype.systemId());
out.appendChild(documentType);
}
out.setXmlStandalone(true);
convert(in, out);
return out;
} catch (ParserConfigurationException e) {
throw new IllegalStateException(e);
}
}
/**
* Converts a jsoup document into the provided W3C Document. If required, you can set options on the output
* document before converting.
*
* @param in jsoup doc
* @param out w3c doc
* @see org.jsoup.helper.W3CDom#fromJsoup(org.jsoup.nodes.Element)
*/
public void convert(org.jsoup.nodes.Document in, Document out) {
// just provides method API backcompat
convert((org.jsoup.nodes.Element) in, out);
}
/**
* Converts a jsoup element into the provided W3C Document. If required, you can set options on the output
* document before converting.
*
* @param in jsoup element
* @param out w3c doc
* @see org.jsoup.helper.W3CDom#fromJsoup(org.jsoup.nodes.Element)
*/
public void convert(org.jsoup.nodes.Element in, Document out) {
org.jsoup.nodes.Document inDoc = in.ownerDocument();
if (inDoc != null) {
if (!StringUtil.isBlank(inDoc.location()))
out.setDocumentURI(inDoc.location());
}
org.jsoup.nodes.Element rootEl = in instanceof org.jsoup.nodes.Document ? in.child(0) : in; // skip the #root node if a Document
NodeTraversor.traverse(new W3CBuilder(out), rootEl);
}
public NodeList selectXpath(String xpath, Document doc) {
Validate.notEmpty(xpath);
Validate.notNull(doc);
NodeList nodeList;
try {
// if there is a configured XPath factory, use that instead of the Java base impl:
String property = System.getProperty(XPathFactoryProperty);
final XPathFactory xPathFactory = property != null ?
XPathFactory.newInstance("jsoup") :
XPathFactory.newInstance();
XPathExpression expression = xPathFactory.newXPath().compile(xpath);
nodeList = (NodeList) expression.evaluate(doc, XPathConstants.NODESET); // love the strong typing here /s
Validate.notNull(nodeList);
} catch (XPathExpressionException | XPathFactoryConfigurationException e) {
throw new Selector.SelectorParseException("Could not evaluate XPath query [%s]: %s", xpath, e.getMessage());
}
return nodeList;
}
public <T extends org.jsoup.nodes.Node> List<T> sourceNodes(NodeList nodeList, Class<T> nodeType) {
Validate.notNull(nodeList);
Validate.notNull(nodeType);
List<T> nodes = new ArrayList<>(nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
org.w3c.dom.Node node = nodeList.item(i);
Object source = node.getUserData(W3CDom.SourceProperty);
if (nodeType.isInstance(source))
nodes.add(nodeType.cast(source));
}
return nodes;
}
/**
* Serialize a W3C document to a String. The output format will be XML or HTML depending on the content of the doc.
*
* @param doc Document
* @return Document as string
* @see W3CDom#asString(Document, Map)
*/
public String asString(Document doc) {
return asString(doc, null);
}
/**
* Implements the conversion by walking the input.
*/
protected static class W3CBuilder implements NodeVisitor {
private static final String xmlnsKey = "xmlns";
private static final String xmlnsPrefix = "xmlns:";
private final Document doc;
private final Stack<HashMap<String, String>> namespacesStack = new Stack<>(); // stack of namespaces, prefix => urn
private Node dest;
public W3CBuilder(Document doc) {
this.doc = doc;
this.namespacesStack.push(new HashMap<>());
this.dest = doc;
}
public void head(org.jsoup.nodes.Node source, int depth) {
namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack
if (source instanceof org.jsoup.nodes.Element) {
org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source;
String prefix = updateNamespaces(sourceEl);
String namespace = namespacesStack.peek().get(prefix);
String tagName = sourceEl.tagName();
/* Tag names in XML are quite permissive, but less permissive than HTML. Rather than reimplement the validation,
we just try to use it as-is. If it fails, insert as a text node instead. We don't try to normalize the
tagname to something safe, because that isn't going to be meaningful downstream. This seems(?) to be
how browsers handle the situation, also. https://github.com/jhy/jsoup/issues/1093 */
try {
Element el = namespace == null && tagName.contains(":") ?
doc.createElementNS("", tagName) : // doesn't have a real namespace defined
doc.createElementNS(namespace, tagName);
copyAttributes(sourceEl, el);
append(el, sourceEl);
dest = el; // descend
} catch (DOMException e) {
append(doc.createTextNode("<" + tagName + ">"), sourceEl);
}
} else if (source instanceof org.jsoup.nodes.TextNode) {
org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source;
Text text = doc.createTextNode(sourceText.getWholeText());
append(text, sourceText);
} else if (source instanceof org.jsoup.nodes.Comment) {
org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source;
Comment comment = doc.createComment(sourceComment.getData());
append(comment, sourceComment);
} else if (source instanceof org.jsoup.nodes.DataNode) {
org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source;
Text node = doc.createTextNode(sourceData.getWholeData());
append(node, sourceData);
} else {
// unhandled. note that doctype is not handled here - rather it is used in the initial doc creation
}
}
private void append(Node append, org.jsoup.nodes.Node source) {
append.setUserData(SourceProperty, source, null);
dest.appendChild(append);
}
public void tail(org.jsoup.nodes.Node source, int depth) {
if (source instanceof org.jsoup.nodes.Element && dest.getParentNode() instanceof Element) {
dest = dest.getParentNode(); // undescend
}
namespacesStack.pop();
}
private void copyAttributes(org.jsoup.nodes.Node source, Element el) {
for (Attribute attribute : source.attributes()) {
String key = Attribute.getValidKey(attribute.getKey(), xml);
if (key != null) { // null if couldn't be coerced to validity
el.setAttribute(key, attribute.getValue());
}
}
}
/**
* Finds any namespaces defined in this element. Returns any tag prefix.
*/
private String updateNamespaces(org.jsoup.nodes.Element el) {
// scan the element for namespace declarations
// like: xmlns="blah" or xmlns:prefix="blah"
Attributes attributes = el.attributes();
for (Attribute attr : attributes) {
String key = attr.getKey();
String prefix;
if (key.equals(xmlnsKey)) {
prefix = "";
} else if (key.startsWith(xmlnsPrefix)) {
prefix = key.substring(xmlnsPrefix.length());
} else {
continue;
}
namespacesStack.peek().put(prefix, attr.getValue());
}
// get the element prefix if any
int pos = el.tagName().indexOf(':');
return pos > 0 ? el.tagName().substring(0, pos) : "";
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/helper/package-info.java
|
/**
Package containing classes supporting the core jsoup code.
*/
@NonnullByDefault
package org.jsoup.helper;
import org.jsoup.internal.NonnullByDefault;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/ConstrainableInputStream.java
|
package org.jsoup.internal;
import org.jsoup.helper.Validate;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
/**
* A jsoup internal class (so don't use it as there is no contract API) that enables constraints on an Input Stream,
* namely a maximum read size, and the ability to Thread.interrupt() the read.
*/
public final class ConstrainableInputStream extends BufferedInputStream {
private static final int DefaultSize = 1024 * 32;
private final boolean capped;
private final int maxSize;
private long startTime;
private long timeout = 0; // optional max time of request
private int remaining;
private boolean interrupted;
private ConstrainableInputStream(InputStream in, int bufferSize, int maxSize) {
super(in, bufferSize);
Validate.isTrue(maxSize >= 0);
this.maxSize = maxSize;
remaining = maxSize;
capped = maxSize != 0;
startTime = System.nanoTime();
}
/**
* If this InputStream is not already a ConstrainableInputStream, let it be one.
* @param in the input stream to (maybe) wrap
* @param bufferSize the buffer size to use when reading
* @param maxSize the maximum size to allow to be read. 0 == infinite.
* @return a constrainable input stream
*/
public static ConstrainableInputStream wrap(InputStream in, int bufferSize, int maxSize) {
return in instanceof ConstrainableInputStream
? (ConstrainableInputStream) in
: new ConstrainableInputStream(in, bufferSize, maxSize);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (interrupted || capped && remaining <= 0)
return -1;
if (Thread.interrupted()) {
// interrupted latches, because parse() may call twice (and we still want the thread interupt to clear)
interrupted = true;
return -1;
}
if (expired())
throw new SocketTimeoutException("Read timeout");
if (capped && len > remaining)
len = remaining; // don't read more than desired, even if available
try {
final int read = super.read(b, off, len);
remaining -= read;
return read;
} catch (SocketTimeoutException e) {
return 0;
}
}
/**
* Reads this inputstream to a ByteBuffer. The supplied max may be less than the inputstream's max, to support
* reading just the first bytes.
*/
public ByteBuffer readToByteBuffer(int max) throws IOException {
Validate.isTrue(max >= 0, "maxSize must be 0 (unlimited) or larger");
final boolean localCapped = max > 0; // still possibly capped in total stream
final int bufferSize = localCapped && max < DefaultSize ? max : DefaultSize;
final byte[] readBuffer = new byte[bufferSize];
final ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
int read;
int remaining = max;
while (true) {
read = read(readBuffer);
if (read == -1) break;
if (localCapped) { // this local byteBuffer cap may be smaller than the overall maxSize (like when reading first bytes)
if (read >= remaining) {
outStream.write(readBuffer, 0, remaining);
break;
}
remaining -= read;
}
outStream.write(readBuffer, 0, read);
}
return ByteBuffer.wrap(outStream.toByteArray());
}
@Override
public void reset() throws IOException {
super.reset();
remaining = maxSize - markpos;
}
public ConstrainableInputStream timeout(long startTimeNanos, long timeoutMillis) {
this.startTime = startTimeNanos;
this.timeout = timeoutMillis * 1000000;
return this;
}
private boolean expired() {
if (timeout == 0)
return false;
final long now = System.nanoTime();
final long dur = now - startTime;
return (dur > timeout);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/FieldsAreNonnullByDefault.java
|
package org.jsoup.internal;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Nonnull
@TypeQualifierDefault(ElementType.FIELD)
@Retention(value = RetentionPolicy.CLASS)
/**
Indicates that fields types are not nullable, unless otherwise specified by @Nullable.
@see javax.annotation.ParametersAreNonnullByDefault
*/
public @interface FieldsAreNonnullByDefault {
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/NonnullByDefault.java
|
package org.jsoup.internal;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Nonnull
@TypeQualifierDefault({ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD})
@Retention(value = RetentionPolicy.CLASS)
/**
Indicates that all components (methods, returns, fields) are not nullable, unless otherwise specified by @Nullable.
@see javax.annotation.ParametersAreNonnullByDefault
*/
public @interface NonnullByDefault {
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/Normalizer.java
|
package org.jsoup.internal;
import java.util.Locale;
/**
* Util methods for normalizing strings. Jsoup internal use only, please don't depend on this API.
*/
public final class Normalizer {
/** Drops the input string to lower case. */
public static String lowerCase(final String input) {
return input != null ? input.toLowerCase(Locale.ENGLISH) : "";
}
/** Lower-cases and trims the input string. */
public static String normalize(final String input) {
return lowerCase(input).trim();
}
/** If a string literal, just lower case the string; otherwise lower-case and trim. */
public static String normalize(final String input, boolean isStringLiteral) {
return isStringLiteral ? lowerCase(input) : normalize(input);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/ReturnsAreNonnullByDefault.java
|
package org.jsoup.internal;
import javax.annotation.Nonnull;
import javax.annotation.meta.TypeQualifierDefault;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Documented
@Nonnull
@TypeQualifierDefault(ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
/**
Indicates return types are not nullable, unless otherwise specified by @Nullable.
@see javax.annotation.ParametersAreNonnullByDefault
*/
public @interface ReturnsAreNonnullByDefault {
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/StringUtil.java
|
package org.jsoup.internal;
import org.jsoup.helper.Validate;
import javax.annotation.Nullable;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Stack;
import java.util.regex.Pattern;
/**
A minimal String utility class. Designed for <b>internal</b> jsoup use only - the API and outcome may change without
notice.
*/
public final class StringUtil {
// memoised padding up to 21
static final String[] padding = {"", " ", " ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " "};
private static final int maxPaddingWidth = 30; // so very deeply nested nodes don't get insane padding amounts
/**
* Join a collection of strings by a separator
* @param strings collection of string objects
* @param sep string to place between strings
* @return joined string
*/
public static String join(Collection<?> strings, String sep) {
return join(strings.iterator(), sep);
}
/**
* Join a collection of strings by a separator
* @param strings iterator of string objects
* @param sep string to place between strings
* @return joined string
*/
public static String join(Iterator<?> strings, String sep) {
if (!strings.hasNext())
return "";
String start = strings.next().toString();
if (!strings.hasNext()) // only one, avoid builder
return start;
StringJoiner j = new StringJoiner(sep);
j.add(start);
while (strings.hasNext()) {
j.add(strings.next());
}
return j.complete();
}
/**
* Join an array of strings by a separator
* @param strings collection of string objects
* @param sep string to place between strings
* @return joined string
*/
public static String join(String[] strings, String sep) {
return join(Arrays.asList(strings), sep);
}
/**
A StringJoiner allows incremental / filtered joining of a set of stringable objects.
@since 1.14.1
*/
public static class StringJoiner {
@Nullable StringBuilder sb = borrowBuilder(); // sets null on builder release so can't accidentally be reused
final String separator;
boolean first = true;
/**
Create a new joiner, that uses the specified separator. MUST call {@link #complete()} or will leak a thread
local string builder.
@param separator the token to insert between strings
*/
public StringJoiner(String separator) {
this.separator = separator;
}
/**
Add another item to the joiner, will be separated
*/
public StringJoiner add(Object stringy) {
Validate.notNull(sb); // don't reuse
if (!first)
sb.append(separator);
sb.append(stringy);
first = false;
return this;
}
/**
Append content to the current item; not separated
*/
public StringJoiner append(Object stringy) {
Validate.notNull(sb); // don't reuse
sb.append(stringy);
return this;
}
/**
Return the joined string, and release the builder back to the pool. This joiner cannot be reused.
*/
public String complete() {
String string = releaseBuilder(sb);
sb = null;
return string;
}
}
/**
* Returns space padding (up to a max of 30).
* @param width amount of padding desired
* @return string of spaces * width
*/
public static String padding(int width) {
if (width < 0)
throw new IllegalArgumentException("width must be > 0");
if (width < padding.length)
return padding[width];
width = Math.min(width, maxPaddingWidth);
char[] out = new char[width];
for (int i = 0; i < width; i++)
out[i] = ' ';
return String.valueOf(out);
}
/**
* Tests if a string is blank: null, empty, or only whitespace (" ", \r\n, \t, etc)
* @param string string to test
* @return if string is blank
*/
public static boolean isBlank(String string) {
if (string == null || string.length() == 0)
return true;
int l = string.length();
for (int i = 0; i < l; i++) {
if (!StringUtil.isWhitespace(string.codePointAt(i)))
return false;
}
return true;
}
/**
* Tests if a string is numeric, i.e. contains only digit characters
* @param string string to test
* @return true if only digit chars, false if empty or null or contains non-digit chars
*/
public static boolean isNumeric(String string) {
if (string == null || string.length() == 0)
return false;
int l = string.length();
for (int i = 0; i < l; i++) {
if (!Character.isDigit(string.codePointAt(i)))
return false;
}
return true;
}
/**
* Tests if a code point is "whitespace" as defined in the HTML spec. Used for output HTML.
* @param c code point to test
* @return true if code point is whitespace, false otherwise
* @see #isActuallyWhitespace(int)
*/
public static boolean isWhitespace(int c){
return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r';
}
/**
* Tests if a code point is "whitespace" as defined by what it looks like. Used for Element.text etc.
* @param c code point to test
* @return true if code point is whitespace, false otherwise
*/
public static boolean isActuallyWhitespace(int c){
return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == 160;
// 160 is (non-breaking space). Not in the spec but expected.
}
public static boolean isInvisibleChar(int c) {
return c == 8203 || c == 173; // zero width sp, soft hyphen
// previously also included zw non join, zw join - but removing those breaks semantic meaning of text
}
/**
* Normalise the whitespace within this string; multiple spaces collapse to a single, and all whitespace characters
* (e.g. newline, tab) convert to a simple space.
* @param string content to normalise
* @return normalised string
*/
public static String normaliseWhitespace(String string) {
StringBuilder sb = StringUtil.borrowBuilder();
appendNormalisedWhitespace(sb, string, false);
return StringUtil.releaseBuilder(sb);
}
/**
* After normalizing the whitespace within a string, appends it to a string builder.
* @param accum builder to append to
* @param string string to normalize whitespace within
* @param stripLeading set to true if you wish to remove any leading whitespace
*/
public static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) {
boolean lastWasWhite = false;
boolean reachedNonWhite = false;
int len = string.length();
int c;
for (int i = 0; i < len; i+= Character.charCount(c)) {
c = string.codePointAt(i);
if (isActuallyWhitespace(c)) {
if ((stripLeading && !reachedNonWhite) || lastWasWhite)
continue;
accum.append(' ');
lastWasWhite = true;
}
else if (!isInvisibleChar(c)) {
accum.appendCodePoint(c);
lastWasWhite = false;
reachedNonWhite = true;
}
}
}
public static boolean in(final String needle, final String... haystack) {
final int len = haystack.length;
for (int i = 0; i < len; i++) {
if (haystack[i].equals(needle))
return true;
}
return false;
}
public static boolean inSorted(String needle, String[] haystack) {
return Arrays.binarySearch(haystack, needle) >= 0;
}
/**
Tests that a String contains only ASCII characters.
@param string scanned string
@return true if all characters are in range 0 - 127
*/
public static boolean isAscii(String string) {
Validate.notNull(string);
for (int i = 0; i < string.length(); i++) {
int c = string.charAt(i);
if (c > 127) { // ascii range
return false;
}
}
return true;
}
private static final Pattern extraDotSegmentsPattern = Pattern.compile("^/((\\.{1,2}/)+)");
/**
* Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
* @param base the existing absolute base URL
* @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
* @return the resolved absolute URL
* @throws MalformedURLException if an error occurred generating the URL
*/
public static URL resolve(URL base, String relUrl) throws MalformedURLException {
// workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
if (relUrl.startsWith("?"))
relUrl = base.getPath() + relUrl;
// workaround: //example.com + ./foo = //example.com/./foo, not //example.com/foo
URL url = new URL(base, relUrl);
String fixedFile = extraDotSegmentsPattern.matcher(url.getFile()).replaceFirst("/");
if (url.getRef() != null) {
fixedFile = fixedFile + "#" + url.getRef();
}
return new URL(url.getProtocol(), url.getHost(), url.getPort(), fixedFile);
}
/**
* Create a new absolute URL, from a provided existing absolute URL and a relative URL component.
* @param baseUrl the existing absolute base URL
* @param relUrl the relative URL to resolve. (If it's already absolute, it will be returned)
* @return an absolute URL if one was able to be generated, or the empty string if not
*/
public static String resolve(final String baseUrl, final String relUrl) {
try {
URL base;
try {
base = new URL(baseUrl);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute/rel may be abs on its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
return resolve(base, relUrl).toExternalForm();
} catch (MalformedURLException e) {
// it may still be valid, just that Java doesn't have a registered stream handler for it, e.g. tel
// we test here vs at start to normalize supported URLs (e.g. HTTP -> http)
return validUriScheme.matcher(relUrl).find() ? relUrl : "";
}
}
private static final Pattern validUriScheme = Pattern.compile("^[a-zA-Z][a-zA-Z0-9+-.]*:");
private static final ThreadLocal<Stack<StringBuilder>> threadLocalBuilders = new ThreadLocal<Stack<StringBuilder>>() {
@Override
protected Stack<StringBuilder> initialValue() {
return new Stack<>();
}
};
/**
* Maintains cached StringBuilders in a flyweight pattern, to minimize new StringBuilder GCs. The StringBuilder is
* prevented from growing too large.
* <p>
* Care must be taken to release the builder once its work has been completed, with {@link #releaseBuilder}
* @return an empty StringBuilder
*/
public static StringBuilder borrowBuilder() {
Stack<StringBuilder> builders = threadLocalBuilders.get();
return builders.empty() ?
new StringBuilder(MaxCachedBuilderSize) :
builders.pop();
}
/**
* Release a borrowed builder. Care must be taken not to use the builder after it has been returned, as its
* contents may be changed by this method, or by a concurrent thread.
* @param sb the StringBuilder to release.
* @return the string value of the released String Builder (as an incentive to release it!).
*/
public static String releaseBuilder(StringBuilder sb) {
Validate.notNull(sb);
String string = sb.toString();
if (sb.length() > MaxCachedBuilderSize)
sb = new StringBuilder(MaxCachedBuilderSize); // make sure it hasn't grown too big
else
sb.delete(0, sb.length()); // make sure it's emptied on release
Stack<StringBuilder> builders = threadLocalBuilders.get();
builders.push(sb);
while (builders.size() > MaxIdleBuilders) {
builders.pop();
}
return string;
}
private static final int MaxCachedBuilderSize = 8 * 1024;
private static final int MaxIdleBuilders = 8;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/internal/package-info.java
|
/**
* Util methods used by Jsoup. Please don't depend on the APIs implemented here as the contents may change without
* notice.
*/
package org.jsoup.internal;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Attribute.java
|
package org.jsoup.nodes;
import org.jsoup.SerializationException;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Document.OutputSettings.Syntax;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.regex.Pattern;
/**
A single key + value attribute. (Only used for presentation.)
*/
public class Attribute implements Map.Entry<String, String>, Cloneable {
private static final String[] booleanAttributes = {
"allowfullscreen", "async", "autofocus", "checked", "compact", "declare", "default", "defer", "disabled",
"formnovalidate", "hidden", "inert", "ismap", "itemscope", "multiple", "muted", "nohref", "noresize",
"noshade", "novalidate", "nowrap", "open", "readonly", "required", "reversed", "seamless", "selected",
"sortable", "truespeed", "typemustmatch"
};
private String key;
@Nullable private String val;
@Nullable Attributes parent; // used to update the holding Attributes when the key / value is changed via this interface
/**
* Create a new attribute from unencoded (raw) key and value.
* @param key attribute key; case is preserved.
* @param value attribute value (may be null)
* @see #createFromEncoded
*/
public Attribute(String key, @Nullable String value) {
this(key, value, null);
}
/**
* Create a new attribute from unencoded (raw) key and value.
* @param key attribute key; case is preserved.
* @param val attribute value (may be null)
* @param parent the containing Attributes (this Attribute is not automatically added to said Attributes)
* @see #createFromEncoded*/
public Attribute(String key, @Nullable String val, @Nullable Attributes parent) {
Validate.notNull(key);
key = key.trim();
Validate.notEmpty(key); // trimming could potentially make empty, so validate here
this.key = key;
this.val = val;
this.parent = parent;
}
/**
Get the attribute key.
@return the attribute key
*/
public String getKey() {
return key;
}
/**
Set the attribute key; case is preserved.
@param key the new key; must not be null
*/
public void setKey(String key) {
Validate.notNull(key);
key = key.trim();
Validate.notEmpty(key); // trimming could potentially make empty, so validate here
if (parent != null) {
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound)
parent.keys[i] = key;
}
this.key = key;
}
/**
Get the attribute value. Will return an empty string if the value is not set.
@return the attribute value
*/
public String getValue() {
return Attributes.checkNotNull(val);
}
/**
* Check if this Attribute has a value. Set boolean attributes have no value.
* @return if this is a boolean attribute / attribute without a value
*/
public boolean hasDeclaredValue() {
return val != null;
}
/**
Set the attribute value.
@param val the new attribute value; may be null (to set an enabled boolean attribute)
@return the previous value (if was null; an empty string)
*/
public String setValue(@Nullable String val) {
String oldVal = this.val;
if (parent != null) {
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound) {
oldVal = parent.get(this.key); // trust the container more
parent.vals[i] = val;
}
}
this.val = val;
return Attributes.checkNotNull(oldVal);
}
/**
Get the HTML representation of this attribute; e.g. {@code href="index.html"}.
@return HTML
*/
public String html() {
StringBuilder sb = StringUtil.borrowBuilder();
try {
html(sb, (new Document("")).outputSettings());
} catch(IOException exception) {
throw new SerializationException(exception);
}
return StringUtil.releaseBuilder(sb);
}
protected void html(Appendable accum, Document.OutputSettings out) throws IOException {
html(key, val, accum, out);
}
protected static void html(String key, @Nullable String val, Appendable accum, Document.OutputSettings out) throws IOException {
key = getValidKey(key, out.syntax());
if (key == null) return; // can't write it :(
htmlNoValidate(key, val, accum, out);
}
static void htmlNoValidate(String key, @Nullable String val, Appendable accum, Document.OutputSettings out) throws IOException {
// structured like this so that Attributes can check we can write first, so it can add whitespace correctly
accum.append(key);
if (!shouldCollapseAttribute(key, val, out)) {
accum.append("=\"");
Entities.escape(accum, Attributes.checkNotNull(val) , out, true, false, false);
accum.append('"');
}
}
private static final Pattern xmlKeyValid = Pattern.compile("[a-zA-Z_:][-a-zA-Z0-9_:.]*");
private static final Pattern xmlKeyReplace = Pattern.compile("[^-a-zA-Z0-9_:.]");
private static final Pattern htmlKeyValid = Pattern.compile("[^\\x00-\\x1f\\x7f-\\x9f \"'/=]+");
private static final Pattern htmlKeyReplace = Pattern.compile("[\\x00-\\x1f\\x7f-\\x9f \"'/=]");
@Nullable public static String getValidKey(String key, Syntax syntax) {
// we consider HTML attributes to always be valid. XML checks key validity
if (syntax == Syntax.xml && !xmlKeyValid.matcher(key).matches()) {
key = xmlKeyReplace.matcher(key).replaceAll("");
return xmlKeyValid.matcher(key).matches() ? key : null; // null if could not be coerced
}
else if (syntax == Syntax.html && !htmlKeyValid.matcher(key).matches()) {
key = htmlKeyReplace.matcher(key).replaceAll("");
return htmlKeyValid.matcher(key).matches() ? key : null; // null if could not be coerced
}
return key;
}
/**
Get the string representation of this attribute, implemented as {@link #html()}.
@return string
*/
@Override
public String toString() {
return html();
}
/**
* Create a new Attribute from an unencoded key and a HTML attribute encoded value.
* @param unencodedKey assumes the key is not encoded, as can be only run of simple \w chars.
* @param encodedValue HTML attribute encoded value
* @return attribute
*/
public static Attribute createFromEncoded(String unencodedKey, String encodedValue) {
String value = Entities.unescape(encodedValue, true);
return new Attribute(unencodedKey, value, null); // parent will get set when Put
}
protected boolean isDataAttribute() {
return isDataAttribute(key);
}
protected static boolean isDataAttribute(String key) {
return key.startsWith(Attributes.dataPrefix) && key.length() > Attributes.dataPrefix.length();
}
/**
* Collapsible if it's a boolean attribute and value is empty or same as name
*
* @param out output settings
* @return Returns whether collapsible or not
*/
protected final boolean shouldCollapseAttribute(Document.OutputSettings out) {
return shouldCollapseAttribute(key, val, out);
}
// collapse unknown foo=null, known checked=null, checked="", checked=checked; write out others
protected static boolean shouldCollapseAttribute(final String key, @Nullable final String val, final Document.OutputSettings out) {
return (
out.syntax() == Syntax.html &&
(val == null || (val.isEmpty() || val.equalsIgnoreCase(key)) && Attribute.isBooleanAttribute(key)));
}
/**
* Checks if this attribute name is defined as a boolean attribute in HTML5
*/
public static boolean isBooleanAttribute(final String key) {
return Arrays.binarySearch(booleanAttributes, key) >= 0;
}
@Override
public boolean equals(@Nullable Object o) { // note parent not considered
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attribute attribute = (Attribute) o;
if (key != null ? !key.equals(attribute.key) : attribute.key != null) return false;
return val != null ? val.equals(attribute.val) : attribute.val == null;
}
@Override
public int hashCode() { // note parent not considered
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (val != null ? val.hashCode() : 0);
return result;
}
@Override
public Attribute clone() {
try {
return (Attribute) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Attributes.java
|
package org.jsoup.nodes;
import org.jsoup.SerializationException;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.parser.ParseSettings;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
* The attributes of an Element.
* <p>
* Attributes are treated as a map: there can be only one value associated with an attribute key/name.
* </p>
* <p>
* Attribute name and value comparisons are generally <b>case sensitive</b>. By default for HTML, attribute names are
* normalized to lower-case on parsing. That means you should use lower-case strings when referring to attributes by
* name.
* </p>
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class Attributes implements Iterable<Attribute>, Cloneable {
// The Attributes object is only created on the first use of an attribute; the Element will just have a null
// Attribute slot otherwise
protected static final String dataPrefix = "data-";
// Indicates a jsoup internal key. Can't be set via HTML. (It could be set via accessor, but not too worried about
// that. Suppressed from list, iter.
static final char InternalPrefix = '/';
private static final int InitialCapacity = 3; // sampling found mean count when attrs present = 1.49; 1.08 overall. 2.6:1 don't have any attrs.
// manages the key/val arrays
private static final int GrowthFactor = 2;
static final int NotFound = -1;
private static final String EmptyString = "";
// the number of instance fields is kept as low as possible giving an object size of 24 bytes
private int size = 0; // number of slots used (not total capacity, which is keys.length)
String[] keys = new String[InitialCapacity];
String[] vals = new String[InitialCapacity];
// check there's room for more
private void checkCapacity(int minNewSize) {
Validate.isTrue(minNewSize >= size);
int curCap = keys.length;
if (curCap >= minNewSize)
return;
int newCap = curCap >= InitialCapacity ? size * GrowthFactor : InitialCapacity;
if (minNewSize > newCap)
newCap = minNewSize;
keys = Arrays.copyOf(keys, newCap);
vals = Arrays.copyOf(vals, newCap);
}
int indexOfKey(String key) {
Validate.notNull(key);
for (int i = 0; i < size; i++) {
if (key.equals(keys[i]))
return i;
}
return NotFound;
}
private int indexOfKeyIgnoreCase(String key) {
Validate.notNull(key);
for (int i = 0; i < size; i++) {
if (key.equalsIgnoreCase(keys[i]))
return i;
}
return NotFound;
}
// we track boolean attributes as null in values - they're just keys. so returns empty for consumers
static String checkNotNull(@Nullable String val) {
return val == null ? EmptyString : val;
}
/**
Get an attribute value by key.
@param key the (case-sensitive) attribute key
@return the attribute value if set; or empty string if not set (or a boolean attribute).
@see #hasKey(String)
*/
public String get(String key) {
int i = indexOfKey(key);
return i == NotFound ? EmptyString : checkNotNull(vals[i]);
}
/**
* Get an attribute's value by case-insensitive key
* @param key the attribute name
* @return the first matching attribute value if set; or empty string if not set (ora boolean attribute).
*/
public String getIgnoreCase(String key) {
int i = indexOfKeyIgnoreCase(key);
return i == NotFound ? EmptyString : checkNotNull(vals[i]);
}
/**
* Adds a new attribute. Will produce duplicates if the key already exists.
* @see Attributes#put(String, String)
*/
public Attributes add(String key, @Nullable String value) {
checkCapacity(size + 1);
keys[size] = key;
vals[size] = value;
size++;
return this;
}
/**
* Set a new attribute, or replace an existing one by key.
* @param key case sensitive attribute key (not null)
* @param value attribute value (may be null, to set a boolean attribute)
* @return these attributes, for chaining
*/
public Attributes put(String key, @Nullable String value) {
Validate.notNull(key);
int i = indexOfKey(key);
if (i != NotFound)
vals[i] = value;
else
add(key, value);
return this;
}
void putIgnoreCase(String key, @Nullable String value) {
int i = indexOfKeyIgnoreCase(key);
if (i != NotFound) {
vals[i] = value;
if (!keys[i].equals(key)) // case changed, update
keys[i] = key;
}
else
add(key, value);
}
/**
* Set a new boolean attribute, remove attribute if value is false.
* @param key case <b>insensitive</b> attribute key
* @param value attribute value
* @return these attributes, for chaining
*/
public Attributes put(String key, boolean value) {
if (value)
putIgnoreCase(key, null);
else
remove(key);
return this;
}
/**
Set a new attribute, or replace an existing one by key.
@param attribute attribute with case sensitive key
@return these attributes, for chaining
*/
public Attributes put(Attribute attribute) {
Validate.notNull(attribute);
put(attribute.getKey(), attribute.getValue());
attribute.parent = this;
return this;
}
// removes and shifts up
@SuppressWarnings("AssignmentToNull")
private void remove(int index) {
Validate.isFalse(index >= size);
int shifted = size - index - 1;
if (shifted > 0) {
System.arraycopy(keys, index + 1, keys, index, shifted);
System.arraycopy(vals, index + 1, vals, index, shifted);
}
size--;
keys[size] = null; // release hold
vals[size] = null;
}
/**
Remove an attribute by key. <b>Case sensitive.</b>
@param key attribute key to remove
*/
public void remove(String key) {
int i = indexOfKey(key);
if (i != NotFound)
remove(i);
}
/**
Remove an attribute by key. <b>Case insensitive.</b>
@param key attribute key to remove
*/
public void removeIgnoreCase(String key) {
int i = indexOfKeyIgnoreCase(key);
if (i != NotFound)
remove(i);
}
/**
Tests if these attributes contain an attribute with this key.
@param key case-sensitive key to check for
@return true if key exists, false otherwise
*/
public boolean hasKey(String key) {
return indexOfKey(key) != NotFound;
}
/**
Tests if these attributes contain an attribute with this key.
@param key key to check for
@return true if key exists, false otherwise
*/
public boolean hasKeyIgnoreCase(String key) {
return indexOfKeyIgnoreCase(key) != NotFound;
}
/**
* Check if these attributes contain an attribute with a value for this key.
* @param key key to check for
* @return true if key exists, and it has a value
*/
public boolean hasDeclaredValueForKey(String key) {
int i = indexOfKey(key);
return i != NotFound && vals[i] != null;
}
/**
* Check if these attributes contain an attribute with a value for this key.
* @param key case-insensitive key to check for
* @return true if key exists, and it has a value
*/
public boolean hasDeclaredValueForKeyIgnoreCase(String key) {
int i = indexOfKeyIgnoreCase(key);
return i != NotFound && vals[i] != null;
}
/**
Get the number of attributes in this set, including any jsoup internal-only attributes. Internal attributes are
excluded from the {@link #html()}, {@link #asList()}, and {@link #iterator()} methods.
@return size
*/
public int size() {
return size;
}
/**
* Test if this Attributes list is empty (size==0).
*/
public boolean isEmpty() {
return size == 0;
}
/**
Add all the attributes from the incoming set to this set.
@param incoming attributes to add to these attributes.
*/
public void addAll(Attributes incoming) {
if (incoming.size() == 0)
return;
checkCapacity(size + incoming.size);
for (Attribute attr : incoming) {
// todo - should this be case insensitive?
put(attr);
}
}
public Iterator<Attribute> iterator() {
return new Iterator<Attribute>() {
int i = 0;
@Override
public boolean hasNext() {
while (i < size) {
if (isInternalKey(keys[i])) // skip over internal keys
i++;
else
break;
}
return i < size;
}
@Override
public Attribute next() {
final Attribute attr = new Attribute(keys[i], vals[i], Attributes.this);
i++;
return attr;
}
@Override
public void remove() {
Attributes.this.remove(--i); // next() advanced, so rewind
}
};
}
/**
Get the attributes as a List, for iteration.
@return an view of the attributes as an unmodifiable List.
*/
public List<Attribute> asList() {
ArrayList<Attribute> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
if (isInternalKey(keys[i]))
continue; // skip internal keys
Attribute attr = new Attribute(keys[i], vals[i], Attributes.this);
list.add(attr);
}
return Collections.unmodifiableList(list);
}
/**
* Retrieves a filtered view of attributes that are HTML5 custom data attributes; that is, attributes with keys
* starting with {@code data-}.
* @return map of custom data attributes.
*/
public Map<String, String> dataset() {
return new Dataset(this);
}
/**
Get the HTML representation of these attributes.
@return HTML
*/
public String html() {
StringBuilder sb = StringUtil.borrowBuilder();
try {
html(sb, (new Document("")).outputSettings()); // output settings a bit funky, but this html() seldom used
} catch (IOException e) { // ought never happen
throw new SerializationException(e);
}
return StringUtil.releaseBuilder(sb);
}
final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {
final int sz = size;
for (int i = 0; i < sz; i++) {
if (isInternalKey(keys[i]))
continue;
final String key = Attribute.getValidKey(keys[i], out.syntax());
if (key != null)
Attribute.htmlNoValidate(key, vals[i], accum.append(' '), out);
}
}
@Override
public String toString() {
return html();
}
/**
* Checks if these attributes are equal to another set of attributes, by comparing the two sets. Note that the order
* of the attributes does not impact this equality (as per the Map interface equals()).
* @param o attributes to compare with
* @return if both sets of attributes have the same content
*/
@Override
public boolean equals(@Nullable Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Attributes that = (Attributes) o;
if (size != that.size) return false;
for (int i = 0; i < size; i++) {
String key = keys[i];
int thatI = that.indexOfKey(key);
if (thatI == NotFound)
return false;
String val = vals[i];
String thatVal = that.vals[thatI];
if (val == null) {
if (thatVal != null)
return false;
} else if (!val.equals(thatVal))
return false;
}
return true;
}
/**
* Calculates the hashcode of these attributes, by iterating all attributes and summing their hashcodes.
* @return calculated hashcode
*/
@Override
public int hashCode() {
int result = size;
result = 31 * result + Arrays.hashCode(keys);
result = 31 * result + Arrays.hashCode(vals);
return result;
}
@Override
public Attributes clone() {
Attributes clone;
try {
clone = (Attributes) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
clone.size = size;
keys = Arrays.copyOf(keys, size);
vals = Arrays.copyOf(vals, size);
return clone;
}
/**
* Internal method. Lowercases all keys.
*/
public void normalize() {
for (int i = 0; i < size; i++) {
keys[i] = lowerCase(keys[i]);
}
}
/**
* Internal method. Removes duplicate attribute by name. Settings for case sensitivity of key names.
* @param settings case sensitivity
* @return number of removed dupes
*/
public int deduplicate(ParseSettings settings) {
if (isEmpty())
return 0;
boolean preserve = settings.preserveAttributeCase();
int dupes = 0;
OUTER: for (int i = 0; i < keys.length; i++) {
for (int j = i + 1; j < keys.length; j++) {
if (keys[j] == null)
continue OUTER; // keys.length doesn't shrink when removing, so re-test
if ((preserve && keys[i].equals(keys[j])) || (!preserve && keys[i].equalsIgnoreCase(keys[j]))) {
dupes++;
remove(j);
j--;
}
}
}
return dupes;
}
private static class Dataset extends AbstractMap<String, String> {
private final Attributes attributes;
private Dataset(Attributes attributes) {
this.attributes = attributes;
}
@Override
public Set<Entry<String, String>> entrySet() {
return new EntrySet();
}
@Override
public String put(String key, String value) {
String dataKey = dataKey(key);
String oldValue = attributes.hasKey(dataKey) ? attributes.get(dataKey) : null;
attributes.put(dataKey, value);
return oldValue;
}
private class EntrySet extends AbstractSet<Map.Entry<String, String>> {
@Override
public Iterator<Map.Entry<String, String>> iterator() {
return new DatasetIterator();
}
@Override
public int size() {
int count = 0;
Iterator iter = new DatasetIterator();
while (iter.hasNext())
count++;
return count;
}
}
private class DatasetIterator implements Iterator<Map.Entry<String, String>> {
private Iterator<Attribute> attrIter = attributes.iterator();
private Attribute attr;
public boolean hasNext() {
while (attrIter.hasNext()) {
attr = attrIter.next();
if (attr.isDataAttribute()) return true;
}
return false;
}
public Entry<String, String> next() {
return new Attribute(attr.getKey().substring(dataPrefix.length()), attr.getValue());
}
public void remove() {
attributes.remove(attr.getKey());
}
}
}
private static String dataKey(String key) {
return dataPrefix + key;
}
static String internalKey(String key) {
return InternalPrefix + key;
}
private boolean isInternalKey(String key) {
return key != null && key.length() > 1 && key.charAt(0) == InternalPrefix;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/CDataNode.java
|
package org.jsoup.nodes;
import org.jsoup.UncheckedIOException;
import java.io.IOException;
/**
* A Character Data node, to support CDATA sections.
*/
public class CDataNode extends TextNode {
public CDataNode(String text) {
super(text);
}
@Override
public String nodeName() {
return "#cdata";
}
/**
* Get the unencoded, <b>non-normalized</b> text content of this CDataNode.
* @return unencoded, non-normalized text
*/
@Override
public String text() {
return getWholeText();
}
@Override
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
accum
.append("<![CDATA[")
.append(getWholeText());
}
@Override
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {
try {
accum.append("]]>");
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public CDataNode clone() {
return (CDataNode) super.clone();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Comment.java
|
package org.jsoup.nodes;
import org.jsoup.parser.ParseSettings;
import org.jsoup.parser.Parser;
import javax.annotation.Nullable;
import java.io.IOException;
/**
A comment node.
@author Jonathan Hedley, jonathan@hedley.net */
public class Comment extends LeafNode {
/**
Create a new comment node.
@param data The contents of the comment
*/
public Comment(String data) {
value = data;
}
public String nodeName() {
return "#comment";
}
/**
Get the contents of the comment.
@return comment content
*/
public String getData() {
return coreValue();
}
public Comment setData(String data) {
coreValue(data);
return this;
}
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock()) || (out.outline() )))
indent(accum, depth, out);
accum
.append("<!--")
.append(getData())
.append("-->");
}
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {}
@Override
public String toString() {
return outerHtml();
}
@Override
public Comment clone() {
return (Comment) super.clone();
}
/**
* Check if this comment looks like an XML Declaration.
* @return true if it looks like, maybe, it's an XML Declaration.
*/
public boolean isXmlDeclaration() {
String data = getData();
return isXmlDeclarationData(data);
}
private static boolean isXmlDeclarationData(String data) {
return (data.length() > 1 && (data.startsWith("!") || data.startsWith("?")));
}
/**
* Attempt to cast this comment to an XML Declaration node.
* @return an XML declaration if it could be parsed as one, null otherwise.
*/
public @Nullable XmlDeclaration asXmlDeclaration() {
String data = getData();
XmlDeclaration decl = null;
String declContent = data.substring(1, data.length() - 1);
// make sure this bogus comment is not immediately followed by another, treat as comment if so
if (isXmlDeclarationData(declContent))
return null;
String fragment = "<" + declContent + ">";
// use the HTML parser not XML, so we don't get into a recursive XML Declaration on contrived data
Document doc = Parser.htmlParser().settings(ParseSettings.preserveCase).parseInput(fragment, baseUri());
if (doc.body().children().size() > 0) {
Element el = doc.body().child(0);
decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!"));
decl.attributes().addAll(el.attributes());
}
return decl;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/DataNode.java
|
package org.jsoup.nodes;
import java.io.IOException;
/**
A data node, for contents of style, script tags etc, where contents should not show in text().
@author Jonathan Hedley, jonathan@hedley.net */
public class DataNode extends LeafNode {
/**
Create a new DataNode.
@param data data contents
*/
public DataNode(String data) {
value = data;
}
public String nodeName() {
return "#data";
}
/**
Get the data contents of this node. Will be unescaped and with original new lines, space etc.
@return data
*/
public String getWholeData() {
return coreValue();
}
/**
* Set the data contents of this node.
* @param data unencoded data
* @return this node, for chaining
*/
public DataNode setWholeData(String data) {
coreValue(data);
return this;
}
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
accum.append(getWholeData()); // data is not escaped in return from data nodes, so " in script, style is plain
}
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {}
@Override
public String toString() {
return outerHtml();
}
@Override
public DataNode clone() {
return (DataNode) super.clone();
}
/**
Create a new DataNode from HTML encoded data.
@param encodedData encoded data
@param baseUri base URI
@return new DataNode
@deprecated Unused, and will be removed in 1.15.1.
*/
@Deprecated
public static DataNode createFromEncoded(String encodedData, String baseUri) {
String data = Entities.unescape(encodedData);
return new DataNode(data);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Document.java
|
package org.jsoup.nodes;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.DataUtil;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.parser.ParseSettings;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator;
import javax.annotation.Nullable;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.List;
/**
A HTML Document.
@author Jonathan Hedley, jonathan@hedley.net */
public class Document extends Element {
private @Nullable Connection connection; // the connection this doc was fetched from, if any
private OutputSettings outputSettings = new OutputSettings();
private Parser parser; // the parser used to parse this document
private QuirksMode quirksMode = QuirksMode.noQuirks;
private final String location;
private boolean updateMetaCharset = false;
/**
Create a new, empty Document.
@param baseUri base URI of document
@see org.jsoup.Jsoup#parse
@see #createShell
*/
public Document(String baseUri) {
super(Tag.valueOf("#root", ParseSettings.htmlDefault), baseUri);
this.location = baseUri;
this.parser = Parser.htmlParser(); // default, but overridable
}
/**
Create a valid, empty shell of a document, suitable for adding more elements to.
@param baseUri baseUri of document
@return document with html, head, and body elements.
*/
public static Document createShell(String baseUri) {
Validate.notNull(baseUri);
Document doc = new Document(baseUri);
doc.parser = doc.parser();
Element html = doc.appendElement("html");
html.appendElement("head");
html.appendElement("body");
return doc;
}
/**
* Get the URL this Document was parsed from. If the starting URL is a redirect,
* this will return the final URL from which the document was served from.
* <p>Will return an empty string if the location is unknown (e.g. if parsed from a String).
* @return location
*/
public String location() {
return location;
}
/**
Returns the Connection (Request/Response) object that was used to fetch this document, if any; otherwise, a new
default Connection object. This can be used to continue a session, preserving settings and cookies, etc.
@return the Connection (session) associated with this Document, or an empty one otherwise.
@see Connection#newRequest()
*/
public Connection connection() {
if (connection == null)
return Jsoup.newSession();
else
return connection;
}
/**
* Returns this Document's doctype.
* @return document type, or null if not set
*/
public @Nullable DocumentType documentType() {
for (Node node : childNodes) {
if (node instanceof DocumentType)
return (DocumentType) node;
else if (!(node instanceof LeafNode)) // scans forward across comments, text, processing instructions etc
break;
}
return null;
// todo - add a set document type?
}
/**
Find the root HTML element, or create it if it doesn't exist.
@return the root HTML element.
*/
private Element htmlEl() {
for (Element el: childElementsList()) {
if (el.normalName().equals("html"))
return el;
}
return appendElement("html");
}
/**
Get this document's {@code head} element.
<p>
As a side-effect, if this Document does not already have a HTML structure, it will be created. If you do not want
that, use {@code #selectFirst("head")} instead.
@return {@code head} element.
*/
public Element head() {
Element html = htmlEl();
for (Element el: html.childElementsList()) {
if (el.normalName().equals("head"))
return el;
}
return html.prependElement("head");
}
/**
Get this document's {@code <body>} or {@code <frameset>} element.
<p>
As a <b>side-effect</b>, if this Document does not already have a HTML structure, it will be created with a {@code
<body>} element. If you do not want that, use {@code #selectFirst("body")} instead.
@return {@code body} element for documents with a {@code <body>}, a new {@code <body>} element if the document
had no contents, or the outermost {@code <frameset> element} for frameset documents.
*/
public Element body() {
Element html = htmlEl();
for (Element el: html.childElementsList()) {
if ("body".equals(el.normalName()) || "frameset".equals(el.normalName()))
return el;
}
return html.appendElement("body");
}
/**
Get the string contents of the document's {@code title} element.
@return Trimmed title, or empty string if none set.
*/
public String title() {
// title is a preserve whitespace tag (for document output), but normalised here
Element titleEl = head().selectFirst(titleEval);
return titleEl != null ? StringUtil.normaliseWhitespace(titleEl.text()).trim() : "";
}
private static final Evaluator titleEval = new Evaluator.Tag("title");
/**
Set the document's {@code title} element. Updates the existing element, or adds {@code title} to {@code head} if
not present
@param title string to set as title
*/
public void title(String title) {
Validate.notNull(title);
Element titleEl = head().selectFirst(titleEval);
if (titleEl == null) // add to head
titleEl = head().appendElement("title");
titleEl.text(title);
}
/**
Create a new Element, with this document's base uri. Does not make the new element a child of this document.
@param tagName element tag name (e.g. {@code a})
@return new element
*/
public Element createElement(String tagName) {
return new Element(Tag.valueOf(tagName, ParseSettings.preserveCase), this.baseUri());
}
/**
Normalise the document. This happens after the parse phase so generally does not need to be called.
Moves any text content that is not in the body element into the body.
@return this document after normalisation
*/
public Document normalise() {
Element htmlEl = htmlEl(); // these all create if not found
Element head = head();
body();
// pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care
// of. do in inverse order to maintain text order.
normaliseTextNodes(head);
normaliseTextNodes(htmlEl);
normaliseTextNodes(this);
normaliseStructure("head", htmlEl);
normaliseStructure("body", htmlEl);
ensureMetaCharsetElement();
return this;
}
// does not recurse.
private void normaliseTextNodes(Element element) {
List<Node> toMove = new ArrayList<>();
for (Node node: element.childNodes) {
if (node instanceof TextNode) {
TextNode tn = (TextNode) node;
if (!tn.isBlank())
toMove.add(tn);
}
}
for (int i = toMove.size()-1; i >= 0; i--) {
Node node = toMove.get(i);
element.removeChild(node);
body().prependChild(new TextNode(" "));
body().prependChild(node);
}
}
// merge multiple <head> or <body> contents into one, delete the remainder, and ensure they are owned by <html>
private void normaliseStructure(String tag, Element htmlEl) {
Elements elements = this.getElementsByTag(tag);
Element master = elements.first(); // will always be available as created above if not existent
if (elements.size() > 1) { // dupes, move contents to master
List<Node> toMove = new ArrayList<>();
for (int i = 1; i < elements.size(); i++) {
Node dupe = elements.get(i);
toMove.addAll(dupe.ensureChildNodes());
dupe.remove();
}
for (Node dupe : toMove)
master.appendChild(dupe);
}
// ensure parented by <html>
if (master.parent() != null && !master.parent().equals(htmlEl)) {
htmlEl.appendChild(master); // includes remove()
}
}
@Override
public String outerHtml() {
return super.html(); // no outer wrapper tag
}
/**
Set the text of the {@code body} of this document. Any existing nodes within the body will be cleared.
@param text unencoded text
@return this document
*/
@Override
public Element text(String text) {
body().text(text); // overridden to not nuke doc structure
return this;
}
@Override
public String nodeName() {
return "#document";
}
/**
* Sets the charset used in this document. This method is equivalent
* to {@link OutputSettings#charset(java.nio.charset.Charset)
* OutputSettings.charset(Charset)} but in addition it updates the
* charset / encoding element within the document.
*
* <p>This enables
* {@link #updateMetaCharsetElement(boolean) meta charset update}.</p>
*
* <p>If there's no element with charset / encoding information yet it will
* be created. Obsolete charset / encoding definitions are removed!</p>
*
* <p><b>Elements used:</b></p>
*
* <ul>
* <li><b>Html:</b> <i><meta charset="CHARSET"></i></li>
* <li><b>Xml:</b> <i><?xml version="1.0" encoding="CHARSET"></i></li>
* </ul>
*
* @param charset Charset
*
* @see #updateMetaCharsetElement(boolean)
* @see OutputSettings#charset(java.nio.charset.Charset)
*/
public void charset(Charset charset) {
updateMetaCharsetElement(true);
outputSettings.charset(charset);
ensureMetaCharsetElement();
}
/**
* Returns the charset used in this document. This method is equivalent
* to {@link OutputSettings#charset()}.
*
* @return Current Charset
*
* @see OutputSettings#charset()
*/
public Charset charset() {
return outputSettings.charset();
}
/**
* Sets whether the element with charset information in this document is
* updated on changes through {@link #charset(java.nio.charset.Charset)
* Document.charset(Charset)} or not.
*
* <p>If set to <tt>false</tt> <i>(default)</i> there are no elements
* modified.</p>
*
* @param update If <tt>true</tt> the element updated on charset
* changes, <tt>false</tt> if not
*
* @see #charset(java.nio.charset.Charset)
*/
public void updateMetaCharsetElement(boolean update) {
this.updateMetaCharset = update;
}
/**
* Returns whether the element with charset information in this document is
* updated on changes through {@link #charset(java.nio.charset.Charset)
* Document.charset(Charset)} or not.
*
* @return Returns <tt>true</tt> if the element is updated on charset
* changes, <tt>false</tt> if not
*/
public boolean updateMetaCharsetElement() {
return updateMetaCharset;
}
@Override
public Document clone() {
Document clone = (Document) super.clone();
clone.outputSettings = this.outputSettings.clone();
return clone;
}
/**
* Ensures a meta charset (html) or xml declaration (xml) with the current
* encoding used. This only applies with
* {@link #updateMetaCharsetElement(boolean) updateMetaCharset} set to
* <tt>true</tt>, otherwise this method does nothing.
*
* <ul>
* <li>An existing element gets updated with the current charset</li>
* <li>If there's no element yet it will be inserted</li>
* <li>Obsolete elements are removed</li>
* </ul>
*
* <p><b>Elements used:</b></p>
*
* <ul>
* <li><b>Html:</b> <i><meta charset="CHARSET"></i></li>
* <li><b>Xml:</b> <i><?xml version="1.0" encoding="CHARSET"></i></li>
* </ul>
*/
private void ensureMetaCharsetElement() {
if (updateMetaCharset) {
OutputSettings.Syntax syntax = outputSettings().syntax();
if (syntax == OutputSettings.Syntax.html) {
Element metaCharset = selectFirst("meta[charset]");
if (metaCharset != null) {
metaCharset.attr("charset", charset().displayName());
} else {
head().appendElement("meta").attr("charset", charset().displayName());
}
select("meta[name=charset]").remove(); // Remove obsolete elements
} else if (syntax == OutputSettings.Syntax.xml) {
Node node = ensureChildNodes().get(0);
if (node instanceof XmlDeclaration) {
XmlDeclaration decl = (XmlDeclaration) node;
if (decl.name().equals("xml")) {
decl.attr("encoding", charset().displayName());
if (decl.hasAttr("version"))
decl.attr("version", "1.0");
} else {
decl = new XmlDeclaration("xml", false);
decl.attr("version", "1.0");
decl.attr("encoding", charset().displayName());
prependChild(decl);
}
} else {
XmlDeclaration decl = new XmlDeclaration("xml", false);
decl.attr("version", "1.0");
decl.attr("encoding", charset().displayName());
prependChild(decl);
}
}
}
}
/**
* A Document's output settings control the form of the text() and html() methods.
*/
public static class OutputSettings implements Cloneable {
/**
* The output serialization syntax.
*/
public enum Syntax {html, xml}
private Entities.EscapeMode escapeMode = Entities.EscapeMode.base;
private Charset charset = DataUtil.UTF_8;
private final ThreadLocal<CharsetEncoder> encoderThreadLocal = new ThreadLocal<>(); // initialized by start of OuterHtmlVisitor
@Nullable Entities.CoreCharset coreCharset; // fast encoders for ascii and utf8
private boolean prettyPrint = true;
private boolean outline = false;
private int indentAmount = 1;
private Syntax syntax = Syntax.html;
public OutputSettings() {}
/**
* Get the document's current HTML escape mode: <code>base</code>, which provides a limited set of named HTML
* entities and escapes other characters as numbered entities for maximum compatibility; or <code>extended</code>,
* which uses the complete set of HTML named entities.
* <p>
* The default escape mode is <code>base</code>.
* @return the document's current escape mode
*/
public Entities.EscapeMode escapeMode() {
return escapeMode;
}
/**
* Set the document's escape mode, which determines how characters are escaped when the output character set
* does not support a given character:- using either a named or a numbered escape.
* @param escapeMode the new escape mode to use
* @return the document's output settings, for chaining
*/
public OutputSettings escapeMode(Entities.EscapeMode escapeMode) {
this.escapeMode = escapeMode;
return this;
}
/**
* Get the document's current output charset, which is used to control which characters are escaped when
* generating HTML (via the <code>html()</code> methods), and which are kept intact.
* <p>
* Where possible (when parsing from a URL or File), the document's output charset is automatically set to the
* input charset. Otherwise, it defaults to UTF-8.
* @return the document's current charset.
*/
public Charset charset() {
return charset;
}
/**
* Update the document's output charset.
* @param charset the new charset to use.
* @return the document's output settings, for chaining
*/
public OutputSettings charset(Charset charset) {
this.charset = charset;
return this;
}
/**
* Update the document's output charset.
* @param charset the new charset (by name) to use.
* @return the document's output settings, for chaining
*/
public OutputSettings charset(String charset) {
charset(Charset.forName(charset));
return this;
}
CharsetEncoder prepareEncoder() {
// created at start of OuterHtmlVisitor so each pass has own encoder, so OutputSettings can be shared among threads
CharsetEncoder encoder = charset.newEncoder();
encoderThreadLocal.set(encoder);
coreCharset = Entities.CoreCharset.byName(encoder.charset().name());
return encoder;
}
CharsetEncoder encoder() {
CharsetEncoder encoder = encoderThreadLocal.get();
return encoder != null ? encoder : prepareEncoder();
}
/**
* Get the document's current output syntax.
* @return current syntax
*/
public Syntax syntax() {
return syntax;
}
/**
* Set the document's output syntax. Either {@code html}, with empty tags and boolean attributes (etc), or
* {@code xml}, with self-closing tags.
* @param syntax serialization syntax
* @return the document's output settings, for chaining
*/
public OutputSettings syntax(Syntax syntax) {
this.syntax = syntax;
return this;
}
/**
* Get if pretty printing is enabled. Default is true. If disabled, the HTML output methods will not re-format
* the output, and the output will generally look like the input.
* @return if pretty printing is enabled.
*/
public boolean prettyPrint() {
return prettyPrint;
}
/**
* Enable or disable pretty printing.
* @param pretty new pretty print setting
* @return this, for chaining
*/
public OutputSettings prettyPrint(boolean pretty) {
prettyPrint = pretty;
return this;
}
/**
* Get if outline mode is enabled. Default is false. If enabled, the HTML output methods will consider
* all tags as block.
* @return if outline mode is enabled.
*/
public boolean outline() {
return outline;
}
/**
* Enable or disable HTML outline mode.
* @param outlineMode new outline setting
* @return this, for chaining
*/
public OutputSettings outline(boolean outlineMode) {
outline = outlineMode;
return this;
}
/**
* Get the current tag indent amount, used when pretty printing.
* @return the current indent amount
*/
public int indentAmount() {
return indentAmount;
}
/**
* Set the indent amount for pretty printing
* @param indentAmount number of spaces to use for indenting each level. Must be {@literal >=} 0.
* @return this, for chaining
*/
public OutputSettings indentAmount(int indentAmount) {
Validate.isTrue(indentAmount >= 0);
this.indentAmount = indentAmount;
return this;
}
@Override
public OutputSettings clone() {
OutputSettings clone;
try {
clone = (OutputSettings) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
clone.charset(charset.name()); // new charset and charset encoder
clone.escapeMode = Entities.EscapeMode.valueOf(escapeMode.name());
// indentAmount, prettyPrint are primitives so object.clone() will handle
return clone;
}
}
/**
* Get the document's current output settings.
* @return the document's current output settings.
*/
public OutputSettings outputSettings() {
return outputSettings;
}
/**
* Set the document's output settings.
* @param outputSettings new output settings.
* @return this document, for chaining.
*/
public Document outputSettings(OutputSettings outputSettings) {
Validate.notNull(outputSettings);
this.outputSettings = outputSettings;
return this;
}
public enum QuirksMode {
noQuirks, quirks, limitedQuirks
}
public QuirksMode quirksMode() {
return quirksMode;
}
public Document quirksMode(QuirksMode quirksMode) {
this.quirksMode = quirksMode;
return this;
}
/**
* Get the parser that was used to parse this document.
* @return the parser
*/
public Parser parser() {
return parser;
}
/**
* Set the parser used to create this document. This parser is then used when further parsing within this document
* is required.
* @param parser the configured parser to use when further parsing is required for this document.
* @return this document, for chaining.
*/
public Document parser(Parser parser) {
this.parser = parser;
return this;
}
/**
Set the Connection used to fetch this document. This Connection is used as a session object when further requests are
made (e.g. when a form is submitted).
@param connection to set
@return this document, for chaining
@see Connection#newRequest()
@since 1.14.1
*/
public Document connection(Connection connection) {
Validate.notNull(connection);
this.connection = connection;
return this;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/DocumentType.java
|
package org.jsoup.nodes;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document.OutputSettings.Syntax;
import java.io.IOException;
/**
* A {@code <!DOCTYPE>} node.
*/
public class DocumentType extends LeafNode {
// todo needs a bit of a chunky cleanup. this level of detail isn't needed
public static final String PUBLIC_KEY = "PUBLIC";
public static final String SYSTEM_KEY = "SYSTEM";
private static final String NAME = "name";
private static final String PUB_SYS_KEY = "pubSysKey"; // PUBLIC or SYSTEM
private static final String PUBLIC_ID = "publicId";
private static final String SYSTEM_ID = "systemId";
// todo: quirk mode from publicId and systemId
/**
* Create a new doctype element.
* @param name the doctype's name
* @param publicId the doctype's public ID
* @param systemId the doctype's system ID
*/
public DocumentType(String name, String publicId, String systemId) {
Validate.notNull(name);
Validate.notNull(publicId);
Validate.notNull(systemId);
attr(NAME, name);
attr(PUBLIC_ID, publicId);
attr(SYSTEM_ID, systemId);
updatePubSyskey();
}
public void setPubSysKey(String value) {
if (value != null)
attr(PUB_SYS_KEY, value);
}
private void updatePubSyskey() {
if (has(PUBLIC_ID)) {
attr(PUB_SYS_KEY, PUBLIC_KEY);
} else if (has(SYSTEM_ID))
attr(PUB_SYS_KEY, SYSTEM_KEY);
}
/**
* Get this doctype's name (when set, or empty string)
* @return doctype name
*/
public String name() {
return attr(NAME);
}
/**
* Get this doctype's Public ID (when set, or empty string)
* @return doctype Public ID
*/
public String publicId() {
return attr(PUBLIC_ID);
}
/**
* Get this doctype's System ID (when set, or empty string)
* @return doctype System ID
*/
public String systemId() {
return attr(SYSTEM_ID);
}
@Override
public String nodeName() {
return "#doctype";
}
@Override
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
if (out.syntax() == Syntax.html && !has(PUBLIC_ID) && !has(SYSTEM_ID)) {
// looks like a html5 doctype, go lowercase for aesthetics
accum.append("<!doctype");
} else {
accum.append("<!DOCTYPE");
}
if (has(NAME))
accum.append(" ").append(attr(NAME));
if (has(PUB_SYS_KEY))
accum.append(" ").append(attr(PUB_SYS_KEY));
if (has(PUBLIC_ID))
accum.append(" \"").append(attr(PUBLIC_ID)).append('"');
if (has(SYSTEM_ID))
accum.append(" \"").append(attr(SYSTEM_ID)).append('"');
accum.append('>');
}
@Override
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {
}
private boolean has(final String attribute) {
return !StringUtil.isBlank(attr(attribute));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Element.java
|
package org.jsoup.nodes;
import org.jsoup.helper.ChangeNotifyingArrayList;
import org.jsoup.helper.Validate;
import org.jsoup.internal.NonnullByDefault;
import org.jsoup.internal.StringUtil;
import org.jsoup.parser.ParseSettings;
import org.jsoup.parser.Tag;
import org.jsoup.select.Collector;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator;
import org.jsoup.select.NodeFilter;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import org.jsoup.select.QueryParser;
import org.jsoup.select.Selector;
import javax.annotation.Nullable;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import static org.jsoup.internal.Normalizer.normalize;
/**
* A HTML element consists of a tag name, attributes, and child nodes (including text nodes and
* other elements).
*
* From an Element, you can extract data, traverse the node graph, and manipulate the HTML.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
@NonnullByDefault
public class Element extends Node {
private static final List<Element> EmptyChildren = Collections.emptyList();
private static final Pattern ClassSplit = Pattern.compile("\\s+");
private static final String BaseUriKey = Attributes.internalKey("baseUri");
private Tag tag;
private @Nullable WeakReference<List<Element>> shadowChildrenRef; // points to child elements shadowed from node children
List<Node> childNodes;
private @Nullable Attributes attributes; // field is nullable but all methods for attributes are non null
/**
* Create a new, standalone element.
* @param tag tag name
*/
public Element(String tag) {
this(Tag.valueOf(tag), "", null);
}
/**
* Create a new, standalone Element. (Standalone in that is has no parent.)
*
* @param tag tag of this element
* @param baseUri the base URI (optional, may be null to inherit from parent, or "" to clear parent's)
* @param attributes initial attributes (optional, may be null)
* @see #appendChild(Node)
* @see #appendElement(String)
*/
public Element(Tag tag, @Nullable String baseUri, @Nullable Attributes attributes) {
Validate.notNull(tag);
childNodes = EmptyNodes;
this.attributes = attributes;
this.tag = tag;
if (baseUri != null)
this.setBaseUri(baseUri);
}
/**
* Create a new Element from a Tag and a base URI.
*
* @param tag element tag
* @param baseUri the base URI of this element. Optional, and will inherit from its parent, if any.
* @see Tag#valueOf(String, ParseSettings)
*/
public Element(Tag tag, @Nullable String baseUri) {
this(tag, baseUri, null);
}
/**
Internal test to check if a nodelist object has been created.
*/
protected boolean hasChildNodes() {
return childNodes != EmptyNodes;
}
protected List<Node> ensureChildNodes() {
if (childNodes == EmptyNodes) {
childNodes = new NodeList(this, 4);
}
return childNodes;
}
@Override
protected boolean hasAttributes() {
return attributes != null;
}
@Override
public Attributes attributes() {
if (attributes == null) // not using hasAttributes, as doesn't clear warning
attributes = new Attributes();
return attributes;
}
@Override
public String baseUri() {
return searchUpForAttribute(this, BaseUriKey);
}
private static String searchUpForAttribute(final Element start, final String key) {
Element el = start;
while (el != null) {
if (el.attributes != null && el.attributes.hasKey(key))
return el.attributes.get(key);
el = el.parent();
}
return "";
}
@Override
protected void doSetBaseUri(String baseUri) {
attributes().put(BaseUriKey, baseUri);
}
@Override
public int childNodeSize() {
return childNodes.size();
}
@Override
public String nodeName() {
return tag.getName();
}
/**
* Get the name of the tag for this element. E.g. {@code div}. If you are using {@link ParseSettings#preserveCase
* case preserving parsing}, this will return the source's original case.
*
* @return the tag name
*/
public String tagName() {
return tag.getName();
}
/**
* Get the normalized name of this Element's tag. This will always be the lowercased version of the tag, regardless
* of the tag case preserving setting of the parser. For e.g., {@code <DIV>} and {@code <div>} both have a
* normal name of {@code div}.
* @return normal name
*/
public String normalName() {
return tag.normalName();
}
/**
* Change (rename) the tag of this element. For example, convert a {@code <span>} to a {@code <div>} with
* {@code el.tagName("div");}.
*
* @param tagName new tag name for this element
* @return this element, for chaining
* @see Elements#tagName(String)
*/
public Element tagName(String tagName) {
Validate.notEmpty(tagName, "Tag name must not be empty.");
tag = Tag.valueOf(tagName, NodeUtils.parser(this).settings()); // maintains the case option of the original parse
return this;
}
/**
* Get the Tag for this element.
*
* @return the tag object
*/
public Tag tag() {
return tag;
}
/**
* Test if this element is a block-level element. (E.g. {@code <div> == true} or an inline element
* {@code <span> == false}).
*
* @return true if block, false if not (and thus inline)
*/
public boolean isBlock() {
return tag.isBlock();
}
/**
* Get the {@code id} attribute of this element.
*
* @return The id attribute, if present, or an empty string if not.
*/
public String id() {
return attributes != null ? attributes.getIgnoreCase("id") :"";
}
/**
Set the {@code id} attribute of this element.
@param id the ID value to use
@return this Element, for chaining
*/
public Element id(String id) {
Validate.notNull(id);
attr("id", id);
return this;
}
/**
* Set an attribute value on this element. If this element already has an attribute with the
* key, its value is updated; otherwise, a new attribute is added.
*
* @return this element
*/
public Element attr(String attributeKey, String attributeValue) {
super.attr(attributeKey, attributeValue);
return this;
}
/**
* Set a boolean attribute value on this element. Setting to <code>true</code> sets the attribute value to "" and
* marks the attribute as boolean so no value is written out. Setting to <code>false</code> removes the attribute
* with the same key if it exists.
*
* @param attributeKey the attribute key
* @param attributeValue the attribute value
*
* @return this element
*/
public Element attr(String attributeKey, boolean attributeValue) {
attributes().put(attributeKey, attributeValue);
return this;
}
/**
* Get this element's HTML5 custom data attributes. Each attribute in the element that has a key
* starting with "data-" is included the dataset.
* <p>
* E.g., the element {@code <div data-package="jsoup" data-language="Java" class="group">...} has the dataset
* {@code package=jsoup, language=java}.
* <p>
* This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected
* in the other map.
* <p>
* You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector.
* @return a map of {@code key=value} custom data attributes.
*/
public Map<String, String> dataset() {
return attributes().dataset();
}
@Override @Nullable
public final Element parent() {
return (Element) parentNode;
}
/**
* Get this element's parent and ancestors, up to the document root.
* @return this element's stack of parents, closest first.
*/
public Elements parents() {
Elements parents = new Elements();
accumulateParents(this, parents);
return parents;
}
private static void accumulateParents(Element el, Elements parents) {
Element parent = el.parent();
if (parent != null && !parent.tagName().equals("#root")) {
parents.add(parent);
accumulateParents(parent, parents);
}
}
/**
* Get a child element of this element, by its 0-based index number.
* <p>
* Note that an element can have both mixed Nodes and Elements as children. This method inspects
* a filtered list of children that are elements, and the index is based on that filtered list.
* </p>
*
* @param index the index number of the element to retrieve
* @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException}
* @see #childNode(int)
*/
public Element child(int index) {
return childElementsList().get(index);
}
/**
* Get the number of child nodes of this element that are elements.
* <p>
* This method works on the same filtered list like {@link #child(int)}. Use {@link #childNodes()} and {@link
* #childNodeSize()} to get the unfiltered Nodes (e.g. includes TextNodes etc.)
* </p>
*
* @return the number of child nodes that are elements
* @see #children()
* @see #child(int)
*/
public int childrenSize() {
return childElementsList().size();
}
/**
* Get this element's child elements.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Element nodes.
* </p>
* @return child elements. If this element has no children, returns an empty list.
* @see #childNodes()
*/
public Elements children() {
return new Elements(childElementsList());
}
/**
* Maintains a shadow copy of this element's child elements. If the nodelist is changed, this cache is invalidated.
* TODO - think about pulling this out as a helper as there are other shadow lists (like in Attributes) kept around.
* @return a list of child elements
*/
List<Element> childElementsList() {
if (childNodeSize() == 0)
return EmptyChildren; // short circuit creating empty
List<Element> children;
if (shadowChildrenRef == null || (children = shadowChildrenRef.get()) == null) {
final int size = childNodes.size();
children = new ArrayList<>(size);
//noinspection ForLoopReplaceableByForEach (beacause it allocates an Iterator which is wasteful here)
for (int i = 0; i < size; i++) {
final Node node = childNodes.get(i);
if (node instanceof Element)
children.add((Element) node);
}
shadowChildrenRef = new WeakReference<>(children);
}
return children;
}
/**
* Clears the cached shadow child elements.
*/
@Override
void nodelistChanged() {
super.nodelistChanged();
shadowChildrenRef = null;
}
/**
* Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Text nodes.
* @return child text nodes. If this element has no text nodes, returns an
* empty list.
* </p>
* For example, with the input HTML: {@code <p>One <span>Two</span> Three <br> Four</p>} with the {@code p} element selected:
* <ul>
* <li>{@code p.text()} = {@code "One Two Three Four"}</li>
* <li>{@code p.ownText()} = {@code "One Three Four"}</li>
* <li>{@code p.children()} = {@code Elements[<span>, <br>]}</li>
* <li>{@code p.childNodes()} = {@code List<Node>["One ", <span>, " Three ", <br>, " Four"]}</li>
* <li>{@code p.textNodes()} = {@code List<TextNode>["One ", " Three ", " Four"]}</li>
* </ul>
*/
public List<TextNode> textNodes() {
List<TextNode> textNodes = new ArrayList<>();
for (Node node : childNodes) {
if (node instanceof TextNode)
textNodes.add((TextNode) node);
}
return Collections.unmodifiableList(textNodes);
}
/**
* Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Data nodes.
* </p>
* @return child data nodes. If this element has no data nodes, returns an
* empty list.
* @see #data()
*/
public List<DataNode> dataNodes() {
List<DataNode> dataNodes = new ArrayList<>();
for (Node node : childNodes) {
if (node instanceof DataNode)
dataNodes.add((DataNode) node);
}
return Collections.unmodifiableList(dataNodes);
}
/**
* Find elements that match the {@link Selector} CSS query, with this element as the starting context. Matched elements
* may include this element, or any of its children.
* <p>This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because
* multiple filters can be combined, e.g.:</p>
* <ul>
* <li>{@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes)
* <li>{@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely)
* </ul>
* <p>See the query syntax documentation in {@link org.jsoup.select.Selector}.</p>
* <p>Also known as {@code querySelectorAll()} in the Web DOM.</p>
*
* @param cssQuery a {@link Selector} CSS-like query
* @return an {@link Elements} list containing elements that match the query (empty if none match)
* @see Selector selector query syntax
* @see QueryParser#parse(String)
* @throws Selector.SelectorParseException (unchecked) on an invalid CSS query.
*/
public Elements select(String cssQuery) {
return Selector.select(cssQuery, this);
}
/**
* Find elements that match the supplied Evaluator. This has the same functionality as {@link #select(String)}, but
* may be useful if you are running the same query many times (on many documents) and want to save the overhead of
* repeatedly parsing the CSS query.
* @param evaluator an element evaluator
* @return an {@link Elements} list containing elements that match the query (empty if none match)
*/
public Elements select(Evaluator evaluator) {
return Selector.select(evaluator, this);
}
/**
* Find the first Element that matches the {@link Selector} CSS query, with this element as the starting context.
* <p>This is effectively the same as calling {@code element.select(query).first()}, but is more efficient as query
* execution stops on the first hit.</p>
* <p>Also known as {@code querySelector()} in the Web DOM.</p>
* @param cssQuery cssQuery a {@link Selector} CSS-like query
* @return the first matching element, or <b>{@code null}</b> if there is no match.
*/
public @Nullable Element selectFirst(String cssQuery) {
return Selector.selectFirst(cssQuery, this);
}
/**
* Finds the first Element that matches the supplied Evaluator, with this element as the starting context, or
* {@code null} if none match.
*
* @param evaluator an element evaluator
* @return the first matching element (walking down the tree, starting from this element), or {@code null} if none
* matchn.
*/
public @Nullable Element selectFirst(Evaluator evaluator) {
return Collector.findFirst(evaluator, this);
}
/**
* Checks if this element matches the given {@link Selector} CSS query. Also knows as {@code matches()} in the Web
* DOM.
*
* @param cssQuery a {@link Selector} CSS query
* @return if this element matches the query
*/
public boolean is(String cssQuery) {
return is(QueryParser.parse(cssQuery));
}
/**
* Check if this element matches the given evaluator.
* @param evaluator an element evaluator
* @return if this element matches
*/
public boolean is(Evaluator evaluator) {
return evaluator.matches(this.root(), this);
}
/**
* Find the closest element up the tree of parents that matches the specified CSS query. Will return itself, an
* ancestor, or {@code null} if there is no such matching element.
* @param cssQuery a {@link Selector} CSS query
* @return the closest ancestor element (possibly itself) that matches the provided evaluator. {@code null} if not
* found.
*/
public @Nullable Element closest(String cssQuery) {
return closest(QueryParser.parse(cssQuery));
}
/**
* Find the closest element up the tree of parents that matches the specified evaluator. Will return itself, an
* ancestor, or {@code null} if there is no such matching element.
* @param evaluator a query evaluator
* @return the closest ancestor element (possibly itself) that matches the provided evaluator. {@code null} if not
* found.
*/
public @Nullable Element closest(Evaluator evaluator) {
Validate.notNull(evaluator);
Element el = this;
final Element root = root();
do {
if (evaluator.matches(root, el))
return el;
el = el.parent();
} while (el != null);
return null;
}
/**
<b>Beta:</b> find Elements that match the supplied XPath expression.
<p>(This functionality is currently in beta and is subject to change. Feedback on the API is requested and
welcomed!)</p>
<p>By default, XPath 1.0 expressions are supported. If you would to use XPath 2.0 or higher, you can provide an
alternate XPathFactory implementation:</p>
<ol>
<li>Add the implementation to your classpath. E.g. to use <a href="https://www.saxonica.com/products/products.xml">Saxon-HE</a>, add <a href="https://mvnrepository.com/artifact/net.sf.saxon/Saxon-HE">net.sf.saxon:Saxon-HE</a> to your build.</li>
<li>Set the system property <code>javax.xml.xpath.XPathFactory:jsoup</code> to the implementing classname. E.g.:<br>
<code>System.setProperty(W3CDom.XPathFactoryProperty, "net.sf.saxon.xpath.XPathFactoryImpl");</code>
</li>
</ol>
@param xpath XPath expression
@return matching elements, or an empty list if none match.
@see #selectXpath(String, Class)
@since 1.14.3
*/
public Elements selectXpath(String xpath) {
return new Elements(NodeUtils.selectXpath(xpath, this, Element.class));
}
/**
<b>Beta:</b> find Nodes that match the supplied XPath expression.
<p>For example, to select TextNodes under {@code p} elements: </p>
<pre>List<TextNode> textNodes = doc.selectXpath("//body//p//text()", TextNode.class);</pre>
<p>Note that in the jsoup DOM, Attribute objects are not Nodes. To directly select attribute values, do something
like:</p>
<pre>List<String> hrefs = doc.selectXpath("//a").eachAttr("href");</pre>
@param xpath XPath expression
@param nodeType the jsoup node type to return
@see #selectXpath(String)
@return a list of matching nodes
@since 1.14.3
*/
public <T extends Node> List<T> selectXpath(String xpath, Class<T> nodeType) {
return NodeUtils.selectXpath(xpath, this, nodeType);
}
/**
* Insert a node to the end of this Element's children. The incoming node will be re-parented.
*
* @param child node to add.
* @return this Element, for chaining
* @see #prependChild(Node)
* @see #insertChildren(int, Collection)
*/
public Element appendChild(Node child) {
Validate.notNull(child);
// was - Node#addChildren(child). short-circuits an array create and a loop.
reparentChild(child);
ensureChildNodes();
childNodes.add(child);
child.setSiblingIndex(childNodes.size() - 1);
return this;
}
/**
Insert the given nodes to the end of this Element's children.
@param children nodes to add
@return this Element, for chaining
@see #insertChildren(int, Collection)
*/
public Element appendChildren(Collection<? extends Node> children) {
insertChildren(-1, children);
return this;
}
/**
* Add this element to the supplied parent element, as its next child.
*
* @param parent element to which this element will be appended
* @return this element, so that you can continue modifying the element
*/
public Element appendTo(Element parent) {
Validate.notNull(parent);
parent.appendChild(this);
return this;
}
/**
* Add a node to the start of this element's children.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element prependChild(Node child) {
Validate.notNull(child);
addChildren(0, child);
return this;
}
/**
Insert the given nodes to the start of this Element's children.
@param children nodes to add
@return this Element, for chaining
@see #insertChildren(int, Collection)
*/
public Element prependChildren(Collection<? extends Node> children) {
insertChildren(0, children);
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Collection<? extends Node> children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
ArrayList<Node> nodes = new ArrayList<>(children);
Node[] nodeArray = nodes.toArray(new Node[0]);
addChildren(index, nodeArray);
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Node... children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
addChildren(index, children);
return this;
}
/**
* Create a new element by tag name, and add it as the last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.appendElement("h1").attr("id", "header").text("Welcome");}
*/
public Element appendElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName, NodeUtils.parser(this).settings()), baseUri());
appendChild(child);
return child;
}
/**
* Create a new element by tag name, and add it as the first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.prependElement("h1").attr("id", "header").text("Welcome");}
*/
public Element prependElement(String tagName) {
Element child = new Element(Tag.valueOf(tagName, NodeUtils.parser(this).settings()), baseUri());
prependChild(child);
return child;
}
/**
* Create and append a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element appendText(String text) {
Validate.notNull(text);
TextNode node = new TextNode(text);
appendChild(node);
return this;
}
/**
* Create and prepend a new TextNode to this element.
*
* @param text the unencoded text to add
* @return this element
*/
public Element prependText(String text) {
Validate.notNull(text);
TextNode node = new TextNode(text);
prependChild(node);
return this;
}
/**
* Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children.
* @param html HTML to add inside this element, after the existing HTML
* @return this element
* @see #html(String)
*/
public Element append(String html) {
Validate.notNull(html);
List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, this, baseUri());
addChildren(nodes.toArray(new Node[0]));
return this;
}
/**
* Add inner HTML into this element. The supplied HTML will be parsed, and each node prepended to the start of the element's children.
* @param html HTML to add inside this element, before the existing HTML
* @return this element
* @see #html(String)
*/
public Element prepend(String html) {
Validate.notNull(html);
List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, this, baseUri());
addChildren(0, nodes.toArray(new Node[0]));
return this;
}
/**
* Insert the specified HTML into the DOM before this element (as a preceding sibling).
*
* @param html HTML to add before this element
* @return this element, for chaining
* @see #after(String)
*/
@Override
public Element before(String html) {
return (Element) super.before(html);
}
/**
* Insert the specified node into the DOM before this node (as a preceding sibling).
* @param node to add before this element
* @return this Element, for chaining
* @see #after(Node)
*/
@Override
public Element before(Node node) {
return (Element) super.before(node);
}
/**
* Insert the specified HTML into the DOM after this element (as a following sibling).
*
* @param html HTML to add after this element
* @return this element, for chaining
* @see #before(String)
*/
@Override
public Element after(String html) {
return (Element) super.after(html);
}
/**
* Insert the specified node into the DOM after this node (as a following sibling).
* @param node to add after this element
* @return this element, for chaining
* @see #before(Node)
*/
@Override
public Element after(Node node) {
return (Element) super.after(node);
}
/**
* Remove all of the element's child nodes. Any attributes are left as-is.
* @return this element
*/
@Override
public Element empty() {
childNodes.clear();
return this;
}
/**
* Wrap the supplied HTML around this element.
*
* @param html HTML to wrap around this element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
* @return this element, for chaining.
*/
@Override
public Element wrap(String html) {
return (Element) super.wrap(html);
}
/**
* Get a CSS selector that will uniquely select this element.
* <p>
* If the element has an ID, returns #id;
* otherwise returns the parent (if any) CSS selector, followed by {@literal '>'},
* followed by a unique selector for the element (tag.class.class:nth-child(n)).
* </p>
*
* @return the CSS Path that can be used to retrieve the element in a selector.
*/
public String cssSelector() {
if (id().length() > 0) {
// prefer to return the ID - but check that it's actually unique first!
String idSel = "#" + id();
Document doc = ownerDocument();
if (doc != null) {
Elements els = doc.select(idSel);
if (els.size() == 1 && els.get(0) == this) // otherwise, continue to the nth-child impl
return idSel;
} else {
return idSel; // no ownerdoc, return the ID selector
}
}
// Translate HTML namespace ns:tag to CSS namespace syntax ns|tag
String tagName = tagName().replace(':', '|');
StringBuilder selector = new StringBuilder(tagName);
String classes = StringUtil.join(classNames(), ".");
if (classes.length() > 0)
selector.append('.').append(classes);
if (parent() == null || parent() instanceof Document) // don't add Document to selector, as will always have a html node
return selector.toString();
selector.insert(0, " > ");
if (parent().select(selector.toString()).size() > 1)
selector.append(String.format(
":nth-child(%d)", elementSiblingIndex() + 1));
return parent().cssSelector() + selector.toString();
}
/**
* Get sibling elements. If the element has no sibling elements, returns an empty list. An element is not a sibling
* of itself, so will not be included in the returned list.
* @return sibling elements
*/
public Elements siblingElements() {
if (parentNode == null)
return new Elements(0);
List<Element> elements = parent().childElementsList();
Elements siblings = new Elements(elements.size() - 1);
for (Element el: elements)
if (el != this)
siblings.add(el);
return siblings;
}
/**
* Gets the next sibling element of this element. E.g., if a {@code div} contains two {@code p}s,
* the {@code nextElementSibling} of the first {@code p} is the second {@code p}.
* <p>
* This is similar to {@link #nextSibling()}, but specifically finds only Elements
* </p>
* @return the next element, or null if there is no next element
* @see #previousElementSibling()
*/
public @Nullable Element nextElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().childElementsList();
int index = indexInList(this, siblings);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
}
/**
* Get each of the sibling elements that come after this element.
*
* @return each of the element siblings after this element, or an empty list if there are no next sibling elements
*/
public Elements nextElementSiblings() {
return nextElementSiblings(true);
}
/**
* Gets the previous element sibling of this element.
* @return the previous element, or null if there is no previous element
* @see #nextElementSibling()
*/
public @Nullable Element previousElementSibling() {
if (parentNode == null) return null;
List<Element> siblings = parent().childElementsList();
int index = indexInList(this, siblings);
if (index > 0)
return siblings.get(index-1);
else
return null;
}
/**
* Get each of the element siblings before this element.
*
* @return the previous element siblings, or an empty list if there are none.
*/
public Elements previousElementSiblings() {
return nextElementSiblings(false);
}
private Elements nextElementSiblings(boolean next) {
Elements els = new Elements();
if (parentNode == null)
return els;
els.add(this);
return next ? els.nextAll() : els.prevAll();
}
/**
* Gets the first Element sibling of this element. That may be this element.
* @return the first sibling that is an element (aka the parent's first element child)
*/
public Element firstElementSibling() {
if (parent() != null) {
List<Element> siblings = parent().childElementsList();
return siblings.size() > 1 ? siblings.get(0) : this;
} else
return this; // orphan is its own first sibling
}
/**
* Get the list index of this element in its element sibling list. I.e. if this is the first element
* sibling, returns 0.
* @return position in element sibling list
*/
public int elementSiblingIndex() {
if (parent() == null) return 0;
return indexInList(this, parent().childElementsList());
}
/**
* Gets the last element sibling of this element. That may be this element.
* @return the last sibling that is an element (aka the parent's last element child)
*/
public Element lastElementSibling() {
if (parent() != null) {
List<Element> siblings = parent().childElementsList();
return siblings.size() > 1 ? siblings.get(siblings.size() - 1) : this;
} else
return this;
}
private static <E extends Element> int indexInList(Element search, List<E> elements) {
final int size = elements.size();
for (int i = 0; i < size; i++) {
if (elements.get(i) == search)
return i;
}
return 0;
}
// DOM type methods
/**
* Finds elements, including and recursively under this element, with the specified tag name.
* @param tagName The tag name to search for (case insensitively).
* @return a matching unmodifiable list of elements. Will be empty if this element and none of its children match.
*/
public Elements getElementsByTag(String tagName) {
Validate.notEmpty(tagName);
tagName = normalize(tagName);
return Collector.collect(new Evaluator.Tag(tagName), this);
}
/**
* Find an element by ID, including or under this element.
* <p>
* Note that this finds the first matching ID, starting with this element. If you search down from a different
* starting point, it is possible to find a different element by ID. For unique element by ID within a Document,
* use {@link Document#getElementById(String)}
* @param id The ID to search for.
* @return The first matching element by ID, starting with this element, or null if none found.
*/
public @Nullable Element getElementById(String id) {
Validate.notEmpty(id);
Elements elements = Collector.collect(new Evaluator.Id(id), this);
if (elements.size() > 0)
return elements.get(0);
else
return null;
}
/**
* Find elements that have this class, including or under this element. Case insensitive.
* <p>
* Elements can have multiple classes (e.g. {@code <div class="header round first">}. This method
* checks each class, so you can find the above with {@code el.getElementsByClass("header");}.
*
* @param className the name of the class to search for.
* @return elements with the supplied class name, empty if none
* @see #hasClass(String)
* @see #classNames()
*/
public Elements getElementsByClass(String className) {
Validate.notEmpty(className);
return Collector.collect(new Evaluator.Class(className), this);
}
/**
* Find elements that have a named attribute set. Case insensitive.
*
* @param key name of the attribute, e.g. {@code href}
* @return elements that have this attribute, empty if none
*/
public Elements getElementsByAttribute(String key) {
Validate.notEmpty(key);
key = key.trim();
return Collector.collect(new Evaluator.Attribute(key), this);
}
/**
* Find elements that have an attribute name starting with the supplied prefix. Use {@code data-} to find elements
* that have HTML5 datasets.
* @param keyPrefix name prefix of the attribute e.g. {@code data-}
* @return elements that have attribute names that start with with the prefix, empty if none.
*/
public Elements getElementsByAttributeStarting(String keyPrefix) {
Validate.notEmpty(keyPrefix);
keyPrefix = keyPrefix.trim();
return Collector.collect(new Evaluator.AttributeStarting(keyPrefix), this);
}
/**
* Find elements that have an attribute with the specific value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that have this attribute with this value, empty if none
*/
public Elements getElementsByAttributeValue(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValue(key, value), this);
}
/**
* Find elements that either do not have this attribute, or have it with a different value. Case insensitive.
*
* @param key name of the attribute
* @param value value of the attribute
* @return elements that do not have a matching attribute
*/
public Elements getElementsByAttributeValueNot(String key, String value) {
return Collector.collect(new Evaluator.AttributeWithValueNot(key, value), this);
}
/**
* Find elements that have attributes that start with the value prefix. Case insensitive.
*
* @param key name of the attribute
* @param valuePrefix start of attribute value
* @return elements that have attributes that start with the value prefix
*/
public Elements getElementsByAttributeValueStarting(String key, String valuePrefix) {
return Collector.collect(new Evaluator.AttributeWithValueStarting(key, valuePrefix), this);
}
/**
* Find elements that have attributes that end with the value suffix. Case insensitive.
*
* @param key name of the attribute
* @param valueSuffix end of the attribute value
* @return elements that have attributes that end with the value suffix
*/
public Elements getElementsByAttributeValueEnding(String key, String valueSuffix) {
return Collector.collect(new Evaluator.AttributeWithValueEnding(key, valueSuffix), this);
}
/**
* Find elements that have attributes whose value contains the match string. Case insensitive.
*
* @param key name of the attribute
* @param match substring of value to search for
* @return elements that have attributes containing this text
*/
public Elements getElementsByAttributeValueContaining(String key, String match) {
return Collector.collect(new Evaluator.AttributeWithValueContaining(key, match), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param pattern compiled regular expression to match against attribute values
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, Pattern pattern) {
return Collector.collect(new Evaluator.AttributeWithValueMatching(key, pattern), this);
}
/**
* Find elements that have attributes whose values match the supplied regular expression.
* @param key name of the attribute
* @param regex regular expression to match against attribute values. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements that have attributes matching this regular expression
*/
public Elements getElementsByAttributeValueMatching(String key, String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsByAttributeValueMatching(key, pattern);
}
/**
* Find elements whose sibling index is less than the supplied index.
* @param index 0-based index
* @return elements less than index
*/
public Elements getElementsByIndexLessThan(int index) {
return Collector.collect(new Evaluator.IndexLessThan(index), this);
}
/**
* Find elements whose sibling index is greater than the supplied index.
* @param index 0-based index
* @return elements greater than index
*/
public Elements getElementsByIndexGreaterThan(int index) {
return Collector.collect(new Evaluator.IndexGreaterThan(index), this);
}
/**
* Find elements whose sibling index is equal to the supplied index.
* @param index 0-based index
* @return elements equal to index
*/
public Elements getElementsByIndexEquals(int index) {
return Collector.collect(new Evaluator.IndexEquals(index), this);
}
/**
* Find elements that contain the specified string. The search is case insensitive. The text may appear directly
* in the element, or in any of its descendants.
* @param searchText to look for in the element's text
* @return elements that contain the string, case insensitive.
* @see Element#text()
*/
public Elements getElementsContainingText(String searchText) {
return Collector.collect(new Evaluator.ContainsText(searchText), this);
}
/**
* Find elements that directly contain the specified string. The search is case insensitive. The text must appear directly
* in the element, not in any of its descendants.
* @param searchText to look for in the element's own text
* @return elements that contain the string, case insensitive.
* @see Element#ownText()
*/
public Elements getElementsContainingOwnText(String searchText) {
return Collector.collect(new Evaluator.ContainsOwnText(searchText), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(Pattern pattern) {
return Collector.collect(new Evaluator.Matches(pattern), this);
}
/**
* Find elements whose text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#text()
*/
public Elements getElementsMatchingText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingText(pattern);
}
/**
* Find elements whose own text matches the supplied regular expression.
* @param pattern regular expression to match text against
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(Pattern pattern) {
return Collector.collect(new Evaluator.MatchesOwn(pattern), this);
}
/**
* Find elements whose own text matches the supplied regular expression.
* @param regex regular expression to match text against. You can use <a href="http://java.sun.com/docs/books/tutorial/essential/regex/pattern.html#embedded">embedded flags</a> (such as (?i) and (?m) to control regex options.
* @return elements matching the supplied regular expression.
* @see Element#ownText()
*/
public Elements getElementsMatchingOwnText(String regex) {
Pattern pattern;
try {
pattern = Pattern.compile(regex);
} catch (PatternSyntaxException e) {
throw new IllegalArgumentException("Pattern syntax error: " + regex, e);
}
return getElementsMatchingOwnText(pattern);
}
/**
* Find all elements under this element (including self, and children of children).
*
* @return all elements
*/
public Elements getAllElements() {
return Collector.collect(new Evaluator.AllElements(), this);
}
/**
Gets the <b>normalized, combined text</b> of this element and all its children. Whitespace is normalized and
trimmed.
<p>For example, given HTML {@code <p>Hello <b>there</b> now! </p>}, {@code p.text()} returns {@code "Hello there
now!"}
<p>If you do not want normalized text, use {@link #wholeText()}. If you want just the text of this node (and not
children), use {@link #ownText()}
<p>Note that this method returns the textual content that would be presented to a reader. The contents of data
nodes (such as {@code <script>} tags are not considered text. Use {@link #data()} or {@link #html()} to retrieve
that content.
@return unencoded, normalized text, or empty string if none.
@see #wholeText()
@see #ownText()
@see #textNodes()
*/
public String text() {
final StringBuilder accum = StringUtil.borrowBuilder();
NodeTraversor.traverse(new NodeVisitor() {
public void head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
appendNormalisedText(accum, textNode);
} else if (node instanceof Element) {
Element element = (Element) node;
if (accum.length() > 0 &&
(element.isBlock() || element.tag.normalName().equals("br")) &&
!TextNode.lastCharIsWhitespace(accum))
accum.append(' ');
}
}
public void tail(Node node, int depth) {
// make sure there is a space between block tags and immediately following text nodes <div>One</div>Two should be "One Two".
if (node instanceof Element) {
Element element = (Element) node;
if (element.isBlock() && (node.nextSibling() instanceof TextNode) && !TextNode.lastCharIsWhitespace(accum))
accum.append(' ');
}
}
}, this);
return StringUtil.releaseBuilder(accum).trim();
}
/**
* Get the (unencoded) text of all children of this element, including any newlines and spaces present in the
* original.
*
* @return unencoded, un-normalized text
* @see #text()
*/
public String wholeText() {
final StringBuilder accum = StringUtil.borrowBuilder();
NodeTraversor.traverse(new NodeVisitor() {
public void head(Node node, int depth) {
if (node instanceof TextNode) {
TextNode textNode = (TextNode) node;
accum.append(textNode.getWholeText());
}
}
public void tail(Node node, int depth) {
}
}, this);
return StringUtil.releaseBuilder(accum);
}
/**
* Gets the (normalized) text owned by this element only; does not get the combined text of all children.
* <p>
* For example, given HTML {@code <p>Hello <b>there</b> now!</p>}, {@code p.ownText()} returns {@code "Hello now!"},
* whereas {@code p.text()} returns {@code "Hello there now!"}.
* Note that the text within the {@code b} element is not returned, as it is not a direct child of the {@code p} element.
*
* @return unencoded text, or empty string if none.
* @see #text()
* @see #textNodes()
*/
public String ownText() {
StringBuilder sb = StringUtil.borrowBuilder();
ownText(sb);
return StringUtil.releaseBuilder(sb).trim();
}
private void ownText(StringBuilder accum) {
for (int i = 0; i < childNodeSize(); i++) {
Node child = childNodes.get(i);
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
appendNormalisedText(accum, textNode);
} else if (child instanceof Element) {
appendWhitespaceIfBr((Element) child, accum);
}
}
}
private static void appendNormalisedText(StringBuilder accum, TextNode textNode) {
String text = textNode.getWholeText();
if (preserveWhitespace(textNode.parentNode) || textNode instanceof CDataNode)
accum.append(text);
else
StringUtil.appendNormalisedWhitespace(accum, text, TextNode.lastCharIsWhitespace(accum));
}
private static void appendWhitespaceIfBr(Element element, StringBuilder accum) {
if (element.tag.normalName().equals("br") && !TextNode.lastCharIsWhitespace(accum))
accum.append(" ");
}
static boolean preserveWhitespace(@Nullable Node node) {
// looks only at this element and five levels up, to prevent recursion & needless stack searches
if (node instanceof Element) {
Element el = (Element) node;
int i = 0;
do {
if (el.tag.preserveWhitespace())
return true;
el = el.parent();
i++;
} while (i < 6 && el != null);
}
return false;
}
/**
* Set the text of this element. Any existing contents (text or elements) will be cleared.
* <p>As a special case, for {@code <script>} and {@code <style>} tags, the input text will be treated as data,
* not visible text.</p>
* @param text unencoded text
* @return this element
*/
public Element text(String text) {
Validate.notNull(text);
empty();
// special case for script/style in HTML: should be data node
Document owner = ownerDocument();
// an alternate impl would be to run through the parser
if (owner != null && owner.parser().isContentForTagData(normalName()))
appendChild(new DataNode(text));
else
appendChild(new TextNode(text));
return this;
}
/**
Test if this element has any text content (that is not just whitespace).
@return true if element has non-blank text content.
*/
public boolean hasText() {
for (Node child: childNodes) {
if (child instanceof TextNode) {
TextNode textNode = (TextNode) child;
if (!textNode.isBlank())
return true;
} else if (child instanceof Element) {
Element el = (Element) child;
if (el.hasText())
return true;
}
}
return false;
}
/**
* Get the combined data of this element. Data is e.g. the inside of a {@code <script>} tag. Note that data is NOT the
* text of the element. Use {@link #text()} to get the text that would be visible to a user, and {@code data()}
* for the contents of scripts, comments, CSS styles, etc.
*
* @return the data, or empty string if none
*
* @see #dataNodes()
*/
public String data() {
StringBuilder sb = StringUtil.borrowBuilder();
for (Node childNode : childNodes) {
if (childNode instanceof DataNode) {
DataNode data = (DataNode) childNode;
sb.append(data.getWholeData());
} else if (childNode instanceof Comment) {
Comment comment = (Comment) childNode;
sb.append(comment.getData());
} else if (childNode instanceof Element) {
Element element = (Element) childNode;
String elementData = element.data();
sb.append(elementData);
} else if (childNode instanceof CDataNode) {
// this shouldn't really happen because the html parser won't see the cdata as anything special when parsing script.
// but incase another type gets through.
CDataNode cDataNode = (CDataNode) childNode;
sb.append(cDataNode.getWholeText());
}
}
return StringUtil.releaseBuilder(sb);
}
/**
* Gets the literal value of this element's "class" attribute, which may include multiple class names, space
* separated. (E.g. on <code><div class="header gray"></code> returns, "<code>header gray</code>")
* @return The literal class attribute, or <b>empty string</b> if no class attribute set.
*/
public String className() {
return attr("class").trim();
}
/**
* Get all of the element's class names. E.g. on element {@code <div class="header gray">},
* returns a set of two elements {@code "header", "gray"}. Note that modifications to this set are not pushed to
* the backing {@code class} attribute; use the {@link #classNames(java.util.Set)} method to persist them.
* @return set of classnames, empty if no class attribute
*/
public Set<String> classNames() {
String[] names = ClassSplit.split(className());
Set<String> classNames = new LinkedHashSet<>(Arrays.asList(names));
classNames.remove(""); // if classNames() was empty, would include an empty class
return classNames;
}
/**
Set the element's {@code class} attribute to the supplied class names.
@param classNames set of classes
@return this element, for chaining
*/
public Element classNames(Set<String> classNames) {
Validate.notNull(classNames);
if (classNames.isEmpty()) {
attributes().remove("class");
} else {
attributes().put("class", StringUtil.join(classNames, " "));
}
return this;
}
/**
* Tests if this element has a class. Case insensitive.
* @param className name of class to check for
* @return true if it does, false if not
*/
// performance sensitive
public boolean hasClass(String className) {
if (attributes == null)
return false;
final String classAttr = attributes.getIgnoreCase("class");
final int len = classAttr.length();
final int wantLen = className.length();
if (len == 0 || len < wantLen) {
return false;
}
// if both lengths are equal, only need compare the className with the attribute
if (len == wantLen) {
return className.equalsIgnoreCase(classAttr);
}
// otherwise, scan for whitespace and compare regions (with no string or arraylist allocations)
boolean inClass = false;
int start = 0;
for (int i = 0; i < len; i++) {
if (Character.isWhitespace(classAttr.charAt(i))) {
if (inClass) {
// white space ends a class name, compare it with the requested one, ignore case
if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) {
return true;
}
inClass = false;
}
} else {
if (!inClass) {
// we're in a class name : keep the start of the substring
inClass = true;
start = i;
}
}
}
// check the last entry
if (inClass && len - start == wantLen) {
return classAttr.regionMatches(true, start, className, 0, wantLen);
}
return false;
}
/**
Add a class name to this element's {@code class} attribute.
@param className class name to add
@return this element
*/
public Element addClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.add(className);
classNames(classes);
return this;
}
/**
Remove a class name from this element's {@code class} attribute.
@param className class name to remove
@return this element
*/
public Element removeClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
classes.remove(className);
classNames(classes);
return this;
}
/**
Toggle a class name on this element's {@code class} attribute: if present, remove it; otherwise add it.
@param className class name to toggle
@return this element
*/
public Element toggleClass(String className) {
Validate.notNull(className);
Set<String> classes = classNames();
if (classes.contains(className))
classes.remove(className);
else
classes.add(className);
classNames(classes);
return this;
}
/**
* Get the value of a form element (input, textarea, etc).
* @return the value of the form element, or empty string if not set.
*/
public String val() {
if (normalName().equals("textarea"))
return text();
else
return attr("value");
}
/**
* Set the value of a form element (input, textarea, etc).
* @param value value to set
* @return this element (for chaining)
*/
public Element val(String value) {
if (normalName().equals("textarea"))
text(value);
else
attr("value", value);
return this;
}
void outerHtmlHead(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException {
if (out.prettyPrint() && isFormatAsBlock(out) && !isInlineable(out)) {
if (accum instanceof StringBuilder) {
if (((StringBuilder) accum).length() > 0)
indent(accum, depth, out);
} else {
indent(accum, depth, out);
}
}
accum.append('<').append(tagName());
if (attributes != null) attributes.html(accum, out);
// selfclosing includes unknown tags, isEmpty defines tags that are always empty
if (childNodes.isEmpty() && tag.isSelfClosing()) {
if (out.syntax() == Document.OutputSettings.Syntax.html && tag.isEmpty())
accum.append('>');
else
accum.append(" />"); // <img> in html, <img /> in xml
}
else
accum.append('>');
}
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
if (!(childNodes.isEmpty() && tag.isSelfClosing())) {
if (out.prettyPrint() && (!childNodes.isEmpty() && (
tag.formatAsBlock() || (out.outline() && (childNodes.size()>1 || (childNodes.size()==1 && !(childNodes.get(0) instanceof TextNode))))
)))
indent(accum, depth, out);
accum.append("</").append(tagName()).append('>');
}
}
/**
* Retrieves the element's inner HTML. E.g. on a {@code <div>} with one empty {@code <p>}, would return
* {@code <p></p>}. (Whereas {@link #outerHtml()} would return {@code <div><p></p></div>}.)
*
* @return String of HTML.
* @see #outerHtml()
*/
public String html() {
StringBuilder accum = StringUtil.borrowBuilder();
html(accum);
String html = StringUtil.releaseBuilder(accum);
return NodeUtils.outputSettings(this).prettyPrint() ? html.trim() : html;
}
@Override
public <T extends Appendable> T html(T appendable) {
final int size = childNodes.size();
for (int i = 0; i < size; i++)
childNodes.get(i).outerHtml(appendable);
return appendable;
}
/**
* Set this element's inner HTML. Clears the existing HTML first.
* @param html HTML to parse and set into this element
* @return this element
* @see #append(String)
*/
public Element html(String html) {
empty();
append(html);
return this;
}
@Override
public Element clone() {
return (Element) super.clone();
}
@Override
public Element shallowClone() {
// simpler than implementing a clone version with no child copy
return new Element(tag, baseUri(), attributes == null ? null : attributes.clone());
}
@Override
protected Element doClone(@Nullable Node parent) {
Element clone = (Element) super.doClone(parent);
clone.attributes = attributes != null ? attributes.clone() : null;
clone.childNodes = new NodeList(clone, childNodes.size());
clone.childNodes.addAll(childNodes); // the children then get iterated and cloned in Node.clone
return clone;
}
// overrides of Node for call chaining
@Override
public Element clearAttributes() {
if (attributes != null) {
super.clearAttributes();
attributes = null;
}
return this;
}
@Override
public Element removeAttr(String attributeKey) {
return (Element) super.removeAttr(attributeKey);
}
@Override
public Element root() {
return (Element) super.root(); // probably a document, but always at least an element
}
@Override
public Element traverse(NodeVisitor nodeVisitor) {
return (Element) super.traverse(nodeVisitor);
}
@Override
public Element filter(NodeFilter nodeFilter) {
return (Element) super.filter(nodeFilter);
}
private static final class NodeList extends ChangeNotifyingArrayList<Node> {
private final Element owner;
NodeList(Element owner, int initialCapacity) {
super(initialCapacity);
this.owner = owner;
}
public void onContentsChanged() {
owner.nodelistChanged();
}
}
private boolean isFormatAsBlock(Document.OutputSettings out) {
return tag.formatAsBlock() || (parent() != null && parent().tag().formatAsBlock()) || out.outline();
}
private boolean isInlineable(Document.OutputSettings out) {
return tag().isInline()
&& !tag().isEmpty()
&& (parent() == null || parent().isBlock())
&& previousSibling() != null
&& !out.outline();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Entities.java
|
package org.jsoup.nodes;
import org.jsoup.SerializationException;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document.OutputSettings;
import org.jsoup.parser.CharacterReader;
import org.jsoup.parser.Parser;
import java.io.IOException;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import java.util.HashMap;
import static org.jsoup.nodes.Document.OutputSettings.*;
import static org.jsoup.nodes.Entities.EscapeMode.base;
import static org.jsoup.nodes.Entities.EscapeMode.extended;
/**
* HTML entities, and escape routines. Source: <a href="http://www.w3.org/TR/html5/named-character-references.html#named-character-references">W3C
* HTML named character references</a>.
*/
public class Entities {
private static final int empty = -1;
private static final String emptyName = "";
static final int codepointRadix = 36;
private static final char[] codeDelims = {',', ';'};
private static final HashMap<String, String> multipoints = new HashMap<>(); // name -> multiple character references
private static final OutputSettings DefaultOutput = new OutputSettings();
public enum EscapeMode {
/**
* Restricted entities suitable for XHTML output: lt, gt, amp, and quot only.
*/
xhtml(EntitiesData.xmlPoints, 4),
/**
* Default HTML output entities.
*/
base(EntitiesData.basePoints, 106),
/**
* Complete HTML entities.
*/
extended(EntitiesData.fullPoints, 2125);
// table of named references to their codepoints. sorted so we can binary search. built by BuildEntities.
private String[] nameKeys;
private int[] codeVals; // limitation is the few references with multiple characters; those go into multipoints.
// table of codepoints to named entities.
private int[] codeKeys; // we don't support multicodepoints to single named value currently
private String[] nameVals;
EscapeMode(String file, int size) {
load(this, file, size);
}
int codepointForName(final String name) {
int index = Arrays.binarySearch(nameKeys, name);
return index >= 0 ? codeVals[index] : empty;
}
String nameForCodepoint(final int codepoint) {
final int index = Arrays.binarySearch(codeKeys, codepoint);
if (index >= 0) {
// the results are ordered so lower case versions of same codepoint come after uppercase, and we prefer to emit lower
// (and binary search for same item with multi results is undefined
return (index < nameVals.length - 1 && codeKeys[index + 1] == codepoint) ?
nameVals[index + 1] : nameVals[index];
}
return emptyName;
}
private int size() {
return nameKeys.length;
}
}
private Entities() {
}
/**
* Check if the input is a known named entity
*
* @param name the possible entity name (e.g. "lt" or "amp")
* @return true if a known named entity
*/
public static boolean isNamedEntity(final String name) {
return extended.codepointForName(name) != empty;
}
/**
* Check if the input is a known named entity in the base entity set.
*
* @param name the possible entity name (e.g. "lt" or "amp")
* @return true if a known named entity in the base set
* @see #isNamedEntity(String)
*/
public static boolean isBaseNamedEntity(final String name) {
return base.codepointForName(name) != empty;
}
/**
* Get the character(s) represented by the named entity
*
* @param name entity (e.g. "lt" or "amp")
* @return the string value of the character(s) represented by this entity, or "" if not defined
*/
public static String getByName(String name) {
String val = multipoints.get(name);
if (val != null)
return val;
int codepoint = extended.codepointForName(name);
if (codepoint != empty)
return new String(new int[]{codepoint}, 0, 1);
return emptyName;
}
public static int codepointsForName(final String name, final int[] codepoints) {
String val = multipoints.get(name);
if (val != null) {
codepoints[0] = val.codePointAt(0);
codepoints[1] = val.codePointAt(1);
return 2;
}
int codepoint = extended.codepointForName(name);
if (codepoint != empty) {
codepoints[0] = codepoint;
return 1;
}
return 0;
}
/**
* HTML escape an input string. That is, {@code <} is returned as {@code <}
*
* @param string the un-escaped string to escape
* @param out the output settings to use
* @return the escaped string
*/
public static String escape(String string, OutputSettings out) {
if (string == null)
return "";
StringBuilder accum = StringUtil.borrowBuilder();
try {
escape(accum, string, out, false, false, false);
} catch (IOException e) {
throw new SerializationException(e); // doesn't happen
}
return StringUtil.releaseBuilder(accum);
}
/**
* HTML escape an input string, using the default settings (UTF-8, base entities). That is, {@code <} is returned as
* {@code <}
*
* @param string the un-escaped string to escape
* @return the escaped string
*/
public static String escape(String string) {
return escape(string, DefaultOutput);
}
// this method is ugly, and does a lot. but other breakups cause rescanning and stringbuilder generations
static void escape(Appendable accum, String string, OutputSettings out,
boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) throws IOException {
boolean lastWasWhite = false;
boolean reachedNonWhite = false;
final EscapeMode escapeMode = out.escapeMode();
final CharsetEncoder encoder = out.encoder();
final CoreCharset coreCharset = out.coreCharset; // init in out.prepareEncoder()
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 '<':
// escape when in character data or when in a xml attribute val or XML syntax; not needed in html attr val
if (!inAttribute || escapeMode == EscapeMode.xhtml || out.syntax() == Syntax.xml)
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;
// we escape ascii control <x20 (other than tab, line-feed, carriage return) for XML compliance (required) and HTML ease of reading (not required) - https://www.w3.org/TR/xml/#charsets
case 0x9:
case 0xA:
case 0xD:
accum.append(c);
break;
default:
if (c < 0x20 || !canEncode(coreCharset, c, encoder))
appendEncoded(accum, escapeMode, codePoint);
else
accum.append(c);
}
} else {
final String c = new String(Character.toChars(codePoint));
if (encoder.canEncode(c)) // uses fallback encoder for simplicity
accum.append(c);
else
appendEncoded(accum, escapeMode, codePoint);
}
}
}
private static void appendEncoded(Appendable accum, EscapeMode escapeMode, int codePoint) throws IOException {
final String name = escapeMode.nameForCodepoint(codePoint);
if (!emptyName.equals(name)) // ok for identity check
accum.append('&').append(name).append(';');
else
accum.append("&#x").append(Integer.toHexString(codePoint)).append(';');
}
/**
* Un-escape an HTML escaped string. That is, {@code <} is returned as {@code <}.
*
* @param string the HTML string to un-escape
* @return the unescaped string
*/
public static String unescape(String string) {
return unescape(string, false);
}
/**
* Unescape the input string.
*
* @param string to un-HTML-escape
* @param strict if "strict" (that is, requires trailing ';' char, otherwise that's optional)
* @return unescaped string
*/
static String unescape(String string, boolean strict) {
return Parser.unescapeEntities(string, strict);
}
/*
* Provides a fast-path for Encoder.canEncode, which drastically improves performance on Android post JellyBean.
* After KitKat, the implementation of canEncode degrades to the point of being useless. For non ASCII or UTF,
* performance may be bad. We can add more encoders for common character sets that are impacted by performance
* issues on Android if required.
*
* Benchmarks: *
* OLD toHtml() impl v New (fastpath) in millis
* Wiki: 1895, 16
* CNN: 6378, 55
* Alterslash: 3013, 28
* Jsoup: 167, 2
*/
private static boolean canEncode(final CoreCharset charset, final char c, final CharsetEncoder fallback) {
// todo add more charset tests if impacted by Android's bad perf in canEncode
switch (charset) {
case ascii:
return c < 0x80;
case utf:
return true; // real is:!(Character.isLowSurrogate(c) || Character.isHighSurrogate(c)); - but already check above
default:
return fallback.canEncode(c);
}
}
enum CoreCharset {
ascii, utf, fallback;
static CoreCharset byName(final String name) {
if (name.equals("US-ASCII"))
return ascii;
if (name.startsWith("UTF-")) // covers UTF-8, UTF-16, et al
return utf;
return fallback;
}
}
private static void load(EscapeMode e, String pointsData, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
int i = 0;
CharacterReader reader = new CharacterReader(pointsData);
try {
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887&
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
final String indexS = reader.consumeTo('&');
final int index = Integer.parseInt(indexS, codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
Validate.isTrue(i == size, "Unexpected count of entities loaded");
} finally {
reader.close();
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/EntitiesData.java
|
package org.jsoup.nodes;
/**
* Holds packed data that represents Entity name=value pairs. Parsed by Entities, created by BuildEntities.
*/
class EntitiesData {
static final String xmlPoints;
static final String basePoints;
static final String fullPoints;
// https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6447475
// allocated in static here so not inlined in users; saves 16K from .jar (!)
static {
xmlPoints = "amp=12;1>=1q;3<=1o;2"=y;0&";
basePoints = "AElig=5i;1c&=12;2Á=5d;17Â=5e;18À=5c;16Å=5h;1bÃ=5f;19Ä=5g;1a©=4p;hÇ=5j;1dÐ=5s;1mÉ=5l;1fÊ=5m;1gÈ=5k;1eË=5n;1h>=1q;6Í=5p;1jÎ=5q;1kÌ=5o;1iÏ=5r;1l<=1o;4Ñ=5t;1nÓ=5v;1pÔ=5w;1qÒ=5u;1oØ=60;1uÕ=5x;1rÖ=5y;1s"=y;0®=4u;nÞ=66;20Ú=62;1wÛ=63;1xÙ=61;1vÜ=64;1yÝ=65;1zá=69;23â=6a;24´=50;uæ=6e;28à=68;22&=12;3å=6d;27ã=6b;25ä=6c;26¦=4m;eç=6f;29¸=54;y¢=4i;a©=4p;i¤=4k;c°=4w;q÷=6v;2pé=6h;2bê=6i;2cè=6g;2að=6o;2ië=6j;2d½=59;13¼=58;12¾=5a;14>=1q;7í=6l;2fî=6m;2g¡=4h;9ì=6k;2e¿=5b;15ï=6n;2h«=4r;k<=1o;5¯=4v;pµ=51;v·=53;x =4g;8¬=4s;lñ=6p;2jó=6r;2lô=6s;2mò=6q;2kª=4q;jº=56;10ø=6w;2qõ=6t;2nö=6u;2o¶=52;w±=4x;r£=4j;b"=y;1»=57;11®=4u;o§=4n;f­=4t;m¹=55;z²=4y;s³=4z;tß=67;21þ=72;2w×=5z;1tú=6y;2sû=6z;2tù=6x;2r¨=4o;gü=70;2uý=71;2v¥=4l;dÿ=73;2x&";
fullPoints = "AElig=5i;2v&=12;8Á=5d;2p&Abreve=76;4kÂ=5e;2q&Acy=sw;av&Afr=2kn8;1khÀ=5c;2o&Alpha=pd;8d&Amacr=74;4i&And=8cz;1e1&Aogon=78;4m&Aopf=2koo;1ls&ApplyFunction=6e9;ewÅ=5h;2t&Ascr=2kkc;1jc&Assign=6s4;s6Ã=5f;2rÄ=5g;2s&Backslash=6qe;o1&Barv=8h3;1it&Barwed=6x2;120&Bcy=sx;aw&Because=6r9;pw&Bernoullis=6jw;gn&Beta=pe;8e&Bfr=2kn9;1ki&Bopf=2kop;1lt&Breve=k8;82&Bscr=6jw;gp&Bumpeq=6ry;ro&CHcy=tj;bi©=4p;1q&Cacute=7a;4o&Cap=6vm;zz&CapitalDifferentialD=6kl;h8&Cayleys=6jx;gq&Ccaron=7g;4uÇ=5j;2w&Ccirc=7c;4q&Cconint=6r4;pn&Cdot=7e;4s&Cedilla=54;2e&CenterDot=53;2b&Cfr=6jx;gr&Chi=pz;8y&CircleDot=6u1;x8&CircleMinus=6ty;x3&CirclePlus=6tx;x1&CircleTimes=6tz;x5&ClockwiseContourIntegral=6r6;pp&CloseCurlyDoubleQuote=6cd;e0&CloseCurlyQuote=6c9;dt&Colon=6rb;q1&Colone=8dw;1en&Congruent=6sh;sn&Conint=6r3;pm&ContourIntegral=6r2;pi&Copf=6iq;f7&Coproduct=6q8;nq&CounterClockwiseContourIntegral=6r7;pr&Cross=8bz;1d8&Cscr=2kke;1jd&Cup=6vn;100&CupCap=6rx;rk&DD=6kl;h9&DDotrahd=841;184&DJcy=si;ai&DScy=sl;al&DZcy=sv;au&Dagger=6ch;e7&Darr=6n5;j5&Dashv=8h0;1ir&Dcaron=7i;4w&Dcy=t0;az&Del=6pz;n9&Delta=pg;8g&Dfr=2knb;1kj&DiacriticalAcute=50;27&DiacriticalDot=k9;84&DiacriticalDoubleAcute=kd;8a&DiacriticalGrave=2o;13&DiacriticalTilde=kc;88&Diamond=6v8;za&DifferentialD=6km;ha&Dopf=2kor;1lu&Dot=4o;1n&DotDot=6ho;f5&DotEqual=6s0;rw&DoubleContourIntegral=6r3;pl&DoubleDot=4o;1m&DoubleDownArrow=6oj;m0&DoubleLeftArrow=6og;lq&DoubleLeftRightArrow=6ok;m3&DoubleLeftTee=8h0;1iq&DoubleLongLeftArrow=7w8;17g&DoubleLongLeftRightArrow=7wa;17m&DoubleLongRightArrow=7w9;17j&DoubleRightArrow=6oi;lw&DoubleRightTee=6ug;xz&DoubleUpArrow=6oh;lt&DoubleUpDownArrow=6ol;m7&DoubleVerticalBar=6qt;ov&DownArrow=6mr;i8&DownArrowBar=843;186&DownArrowUpArrow=6ph;mn&DownBreve=lt;8c&DownLeftRightVector=85s;198&DownLeftTeeVector=866;19m&DownLeftVector=6nx;ke&DownLeftVectorBar=85y;19e&DownRightTeeVector=867;19n&DownRightVector=6o1;kq&DownRightVectorBar=85z;19f&DownTee=6uc;xs&DownTeeArrow=6nb;jh&Downarrow=6oj;m1&Dscr=2kkf;1je&Dstrok=7k;4y&ENG=96;6gÐ=5s;35É=5l;2y&Ecaron=7u;56Ê=5m;2z&Ecy=tp;bo&Edot=7q;52&Efr=2knc;1kkÈ=5k;2x&Element=6q0;na&Emacr=7m;50&EmptySmallSquare=7i3;15x&EmptyVerySmallSquare=7fv;150&Eogon=7s;54&Eopf=2kos;1lv&Epsilon=ph;8h&Equal=8dx;1eo&EqualTilde=6rm;qp&Equilibrium=6oc;li&Escr=6k0;gu&Esim=8dv;1em&Eta=pj;8jË=5n;30&Exists=6pv;mz&ExponentialE=6kn;hc&Fcy=tg;bf&Ffr=2knd;1kl&FilledSmallSquare=7i4;15y&FilledVerySmallSquare=7fu;14w&Fopf=2kot;1lw&ForAll=6ps;ms&Fouriertrf=6k1;gv&Fscr=6k1;gw&GJcy=sj;aj>=1q;r&Gamma=pf;8f&Gammad=rg;a5&Gbreve=7y;5a&Gcedil=82;5e&Gcirc=7w;58&Gcy=sz;ay&Gdot=80;5c&Gfr=2kne;1km&Gg=6vt;10c&Gopf=2kou;1lx&GreaterEqual=6sl;sv&GreaterEqualLess=6vv;10i&GreaterFullEqual=6sn;t6&GreaterGreater=8f6;1gh&GreaterLess=6t3;ul&GreaterSlantEqual=8e6;1f5&GreaterTilde=6sz;ub&Gscr=2kki;1jf&Gt=6sr;tr&HARDcy=tm;bl&Hacek=jr;80&Hat=2m;10&Hcirc=84;5f&Hfr=6j0;fe&HilbertSpace=6iz;fa&Hopf=6j1;fg&HorizontalLine=7b4;13i&Hscr=6iz;fc&Hstrok=86;5h&HumpDownHump=6ry;rn&HumpEqual=6rz;rs&IEcy=t1;b0&IJlig=8i;5s&IOcy=sh;ahÍ=5p;32Î=5q;33&Icy=t4;b3&Idot=8g;5p&Ifr=6j5;fqÌ=5o;31&Im=6j5;fr&Imacr=8a;5l&ImaginaryI=6ko;hf&Implies=6oi;ly&Int=6r0;pf&Integral=6qz;pd&Intersection=6v6;z4&InvisibleComma=6eb;f0&InvisibleTimes=6ea;ey&Iogon=8e;5n&Iopf=2kow;1ly&Iota=pl;8l&Iscr=6j4;fn&Itilde=88;5j&Iukcy=sm;amÏ=5r;34&Jcirc=8k;5u&Jcy=t5;b4&Jfr=2knh;1kn&Jopf=2kox;1lz&Jscr=2kkl;1jg&Jsercy=so;ao&Jukcy=sk;ak&KHcy=th;bg&KJcy=ss;as&Kappa=pm;8m&Kcedil=8m;5w&Kcy=t6;b5&Kfr=2kni;1ko&Kopf=2koy;1m0&Kscr=2kkm;1jh&LJcy=sp;ap<=1o;m&Lacute=8p;5z&Lambda=pn;8n&Lang=7vu;173&Laplacetrf=6j6;fs&Larr=6n2;j1&Lcaron=8t;63&Lcedil=8r;61&Lcy=t7;b6&LeftAngleBracket=7vs;16x&LeftArrow=6mo;hu&LeftArrowBar=6p0;mj&LeftArrowRightArrow=6o6;l3&LeftCeiling=6x4;121&LeftDoubleBracket=7vq;16t&LeftDownTeeVector=869;19p&LeftDownVector=6o3;kw&LeftDownVectorBar=861;19h&LeftFloor=6x6;125&LeftRightArrow=6ms;ib&LeftRightVector=85q;196&LeftTee=6ub;xq&LeftTeeArrow=6n8;ja&LeftTeeVector=862;19i&LeftTriangle=6uq;ya&LeftTriangleBar=89b;1c0&LeftTriangleEqual=6us;yg&LeftUpDownVector=85t;199&LeftUpTeeVector=868;19o&LeftUpVector=6nz;kk&LeftUpVectorBar=860;19g&LeftVector=6nw;kb&LeftVectorBar=85u;19a&Leftarrow=6og;lr&Leftrightarrow=6ok;m4&LessEqualGreater=6vu;10e&LessFullEqual=6sm;t0&LessGreater=6t2;ui&LessLess=8f5;1gf&LessSlantEqual=8e5;1ez&LessTilde=6sy;u8&Lfr=2knj;1kp&Ll=6vs;109&Lleftarrow=6oq;me&Lmidot=8v;65&LongLeftArrow=7w5;177&LongLeftRightArrow=7w7;17d&LongRightArrow=7w6;17a&Longleftarrow=7w8;17h&Longleftrightarrow=7wa;17n&Longrightarrow=7w9;17k&Lopf=2koz;1m1&LowerLeftArrow=6mx;iq&LowerRightArrow=6mw;in&Lscr=6j6;fu&Lsh=6nk;jv&Lstrok=8x;67&Lt=6sq;tl&Map=83p;17v&Mcy=t8;b7&MediumSpace=6e7;eu&Mellintrf=6k3;gx&Mfr=2knk;1kq&MinusPlus=6qb;nv&Mopf=2kp0;1m2&Mscr=6k3;gz&Mu=po;8o&NJcy=sq;aq&Nacute=8z;69&Ncaron=93;6d&Ncedil=91;6b&Ncy=t9;b8&NegativeMediumSpace=6bv;dc&NegativeThickSpace=6bv;dd&NegativeThinSpace=6bv;de&NegativeVeryThinSpace=6bv;db&NestedGreaterGreater=6sr;tq&NestedLessLess=6sq;tk&NewLine=a;1&Nfr=2knl;1kr&NoBreak=6e8;ev&NonBreakingSpace=4g;1d&Nopf=6j9;fx&Not=8h8;1ix&NotCongruent=6si;sp&NotCupCap=6st;tv&NotDoubleVerticalBar=6qu;p0&NotElement=6q1;ne&NotEqual=6sg;sk&NotEqualTilde=6rm,mw;qn&NotExists=6pw;n1&NotGreater=6sv;tz&NotGreaterEqual=6sx;u5&NotGreaterFullEqual=6sn,mw;t3&NotGreaterGreater=6sr,mw;tn&NotGreaterLess=6t5;uq&NotGreaterSlantEqual=8e6,mw;1f2&NotGreaterTilde=6t1;ug&NotHumpDownHump=6ry,mw;rl&NotHumpEqual=6rz,mw;rq&NotLeftTriangle=6wa;113&NotLeftTriangleBar=89b,mw;1bz&NotLeftTriangleEqual=6wc;119&NotLess=6su;tw&NotLessEqual=6sw;u2&NotLessGreater=6t4;uo&NotLessLess=6sq,mw;th&NotLessSlantEqual=8e5,mw;1ew&NotLessTilde=6t0;ue&NotNestedGreaterGreater=8f6,mw;1gg&NotNestedLessLess=8f5,mw;1ge&NotPrecedes=6tc;vb&NotPrecedesEqual=8fj,mw;1gv&NotPrecedesSlantEqual=6w0;10p&NotReverseElement=6q4;nl&NotRightTriangle=6wb;116&NotRightTriangleBar=89c,mw;1c1&NotRightTriangleEqual=6wd;11c&NotSquareSubset=6tr,mw;wh&NotSquareSubsetEqual=6w2;10t&NotSquareSuperset=6ts,mw;wl&NotSquareSupersetEqual=6w3;10v&NotSubset=6te,6he;vh&NotSubsetEqual=6tk;w0&NotSucceeds=6td;ve&NotSucceedsEqual=8fk,mw;1h1&NotSucceedsSlantEqual=6w1;10r&NotSucceedsTilde=6tb,mw;v7&NotSuperset=6tf,6he;vm&NotSupersetEqual=6tl;w3&NotTilde=6rl;ql&NotTildeEqual=6ro;qv&NotTildeFullEqual=6rr;r1&NotTildeTilde=6rt;r9&NotVerticalBar=6qs;or&Nscr=2kkp;1jiÑ=5t;36&Nu=pp;8p&OElig=9e;6mÓ=5v;38Ô=5w;39&Ocy=ta;b9&Odblac=9c;6k&Ofr=2knm;1ksÒ=5u;37&Omacr=98;6i&Omega=q1;90&Omicron=pr;8r&Oopf=2kp2;1m3&OpenCurlyDoubleQuote=6cc;dy&OpenCurlyQuote=6c8;dr&Or=8d0;1e2&Oscr=2kkq;1jjØ=60;3dÕ=5x;3a&Otimes=8c7;1dfÖ=5y;3b&OverBar=6da;em&OverBrace=732;13b&OverBracket=71w;134&OverParenthesis=730;139&PartialD=6pu;mx&Pcy=tb;ba&Pfr=2knn;1kt&Phi=py;8x&Pi=ps;8s&PlusMinus=4x;22&Poincareplane=6j0;fd&Popf=6jd;g3&Pr=8fv;1hl&Precedes=6t6;us&PrecedesEqual=8fj;1gy&PrecedesSlantEqual=6t8;uy&PrecedesTilde=6ta;v4&Prime=6cz;eg&Product=6q7;no&Proportion=6rb;q0&Proportional=6ql;oa&Pscr=2kkr;1jk&Psi=q0;8z"=y;3&Qfr=2kno;1ku&Qopf=6je;g5&Qscr=2kks;1jl&RBarr=840;183®=4u;1x&Racute=9g;6o&Rang=7vv;174&Rarr=6n4;j4&Rarrtl=846;187&Rcaron=9k;6s&Rcedil=9i;6q&Rcy=tc;bb&Re=6jg;gb&ReverseElement=6q3;nh&ReverseEquilibrium=6ob;le&ReverseUpEquilibrium=86n;1a4&Rfr=6jg;ga&Rho=pt;8t&RightAngleBracket=7vt;170&RightArrow=6mq;i3&RightArrowBar=6p1;ml&RightArrowLeftArrow=6o4;ky&RightCeiling=6x5;123&RightDoubleBracket=7vr;16v&RightDownTeeVector=865;19l&RightDownVector=6o2;kt&RightDownVectorBar=85x;19d&RightFloor=6x7;127&RightTee=6ua;xo&RightTeeArrow=6na;je&RightTeeVector=863;19j&RightTriangle=6ur;yd&RightTriangleBar=89c;1c2&RightTriangleEqual=6ut;yk&RightUpDownVector=85r;197&RightUpTeeVector=864;19k&RightUpVector=6ny;kh&RightUpVectorBar=85w;19c&RightVector=6o0;kn&RightVectorBar=85v;19b&Rightarrow=6oi;lx&Ropf=6jh;gd&RoundImplies=86o;1a6&Rrightarrow=6or;mg&Rscr=6jf;g7&Rsh=6nl;jx&RuleDelayed=8ac;1cb&SHCHcy=tl;bk&SHcy=tk;bj&SOFTcy=to;bn&Sacute=9m;6u&Sc=8fw;1hm&Scaron=9s;70&Scedil=9q;6y&Scirc=9o;6w&Scy=td;bc&Sfr=2knq;1kv&ShortDownArrow=6mr;i7&ShortLeftArrow=6mo;ht&ShortRightArrow=6mq;i2&ShortUpArrow=6mp;hy&Sigma=pv;8u&SmallCircle=6qg;o6&Sopf=2kp6;1m4&Sqrt=6qi;o9&Square=7fl;14t&SquareIntersection=6tv;ww&SquareSubset=6tr;wi&SquareSubsetEqual=6tt;wp&SquareSuperset=6ts;wm&SquareSupersetEqual=6tu;ws&SquareUnion=6tw;wz&Sscr=2kku;1jm&Star=6va;zf&Sub=6vk;zw&Subset=6vk;zv&SubsetEqual=6ti;vu&Succeeds=6t7;uv&SucceedsEqual=8fk;1h4&SucceedsSlantEqual=6t9;v1&SucceedsTilde=6tb;v8&SuchThat=6q3;ni&Sum=6q9;ns&Sup=6vl;zy&Superset=6tf;vp&SupersetEqual=6tj;vx&Supset=6vl;zxÞ=66;3j&TRADE=6jm;gf&TSHcy=sr;ar&TScy=ti;bh&Tab=9;0&Tau=pw;8v&Tcaron=9w;74&Tcedil=9u;72&Tcy=te;bd&Tfr=2knr;1kw&Therefore=6r8;pt&Theta=pk;8k&ThickSpace=6e7,6bu;et&ThinSpace=6bt;d7&Tilde=6rg;q9&TildeEqual=6rn;qs&TildeFullEqual=6rp;qy&TildeTilde=6rs;r4&Topf=2kp7;1m5&TripleDot=6hn;f3&Tscr=2kkv;1jn&Tstrok=9y;76Ú=62;3f&Uarr=6n3;j2&Uarrocir=85l;193&Ubrcy=su;at&Ubreve=a4;7cÛ=63;3g&Ucy=tf;be&Udblac=a8;7g&Ufr=2kns;1kxÙ=61;3e&Umacr=a2;7a&UnderBar=2n;11&UnderBrace=733;13c&UnderBracket=71x;136&UnderParenthesis=731;13a&Union=6v7;z8&UnionPlus=6tq;wf&Uogon=aa;7i&Uopf=2kp8;1m6&UpArrow=6mp;hz&UpArrowBar=842;185&UpArrowDownArrow=6o5;l1&UpDownArrow=6mt;ie&UpEquilibrium=86m;1a2&UpTee=6ud;xv&UpTeeArrow=6n9;jc&Uparrow=6oh;lu&Updownarrow=6ol;m8&UpperLeftArrow=6mu;ih&UpperRightArrow=6mv;ik&Upsi=r6;9z&Upsilon=px;8w&Uring=a6;7e&Uscr=2kkw;1jo&Utilde=a0;78Ü=64;3h&VDash=6uj;y3&Vbar=8h7;1iw&Vcy=sy;ax&Vdash=6uh;y1&Vdashl=8h2;1is&Vee=6v5;z3&Verbar=6c6;dp&Vert=6c6;dq&VerticalBar=6qr;on&VerticalLine=3g;18&VerticalSeparator=7rs;16o&VerticalTilde=6rk;qi&VeryThinSpace=6bu;d9&Vfr=2knt;1ky&Vopf=2kp9;1m7&Vscr=2kkx;1jp&Vvdash=6ui;y2&Wcirc=ac;7k&Wedge=6v4;z0&Wfr=2knu;1kz&Wopf=2kpa;1m8&Wscr=2kky;1jq&Xfr=2knv;1l0&Xi=pq;8q&Xopf=2kpb;1m9&Xscr=2kkz;1jr&YAcy=tr;bq&YIcy=sn;an&YUcy=tq;bpÝ=65;3i&Ycirc=ae;7m&Ycy=tn;bm&Yfr=2knw;1l1&Yopf=2kpc;1ma&Yscr=2kl0;1js&Yuml=ag;7o&ZHcy=t2;b1&Zacute=ah;7p&Zcaron=al;7t&Zcy=t3;b2&Zdot=aj;7r&ZeroWidthSpace=6bv;df&Zeta=pi;8i&Zfr=6js;gl&Zopf=6jo;gi&Zscr=2kl1;1jtá=69;3m&abreve=77;4l&ac=6ri;qg&acE=6ri,mr;qe&acd=6rj;qhâ=6a;3n´=50;28&acy=ts;bræ=6e;3r&af=6e9;ex&afr=2kny;1l2à=68;3l&alefsym=6k5;h3&aleph=6k5;h4&alpha=q9;92&amacr=75;4j&amalg=8cf;1dm&=12;9&and=6qv;p6&andand=8d1;1e3&andd=8d8;1e9&andslope=8d4;1e6&andv=8d6;1e7&ang=6qo;oj&ange=884;1b1&angle=6qo;oi&angmsd=6qp;ol&angmsdaa=888;1b5&angmsdab=889;1b6&angmsdac=88a;1b7&angmsdad=88b;1b8&angmsdae=88c;1b9&angmsdaf=88d;1ba&angmsdag=88e;1bb&angmsdah=88f;1bc&angrt=6qn;og&angrtvb=6v2;yw&angrtvbd=87x;1b0&angsph=6qq;om&angst=5h;2u&angzarr=70c;12z&aogon=79;4n&aopf=2kpe;1mb&ap=6rs;r8&apE=8ds;1ej&apacir=8dr;1eh&ape=6ru;rd&apid=6rv;rf&apos=13;a&approx=6rs;r5&approxeq=6ru;rcå=6d;3q&ascr=2kl2;1ju&ast=16;e&asymp=6rs;r6&asympeq=6rx;rjã=6b;3oä=6c;3p&awconint=6r7;ps&awint=8b5;1cr&bNot=8h9;1iy&backcong=6rw;rg&backepsilon=s6;af&backprime=6d1;ei&backsim=6rh;qc&backsimeq=6vh;zp&barvee=6v1;yv&barwed=6x1;11y&barwedge=6x1;11x&bbrk=71x;137&bbrktbrk=71y;138&bcong=6rw;rh&bcy=tt;bs&bdquo=6ce;e4&becaus=6r9;py&because=6r9;px&bemptyv=88g;1bd&bepsi=s6;ag&bernou=6jw;go&beta=qa;93&beth=6k6;h5&between=6ss;tt&bfr=2knz;1l3&bigcap=6v6;z5&bigcirc=7hr;15s&bigcup=6v7;z7&bigodot=8ao;1cd&bigoplus=8ap;1cf&bigotimes=8aq;1ch&bigsqcup=8au;1cl&bigstar=7id;15z&bigtriangledown=7gd;15e&bigtriangleup=7g3;154&biguplus=8as;1cj&bigvee=6v5;z1&bigwedge=6v4;yy&bkarow=83x;17x&blacklozenge=8a3;1c9&blacksquare=7fu;14x&blacktriangle=7g4;156&blacktriangledown=7ge;15g&blacktriangleleft=7gi;15k&blacktriangleright=7g8;15a&blank=74z;13f&blk12=7f6;14r&blk14=7f5;14q&blk34=7f7;14s&block=7ew;14p&bne=1p,6hx;o&bnequiv=6sh,6hx;sm&bnot=6xc;12d&bopf=2kpf;1mc&bot=6ud;xx&bottom=6ud;xu&bowtie=6vc;zi&boxDL=7dj;141&boxDR=7dg;13y&boxDl=7di;140&boxDr=7df;13x&boxH=7dc;13u&boxHD=7dy;14g&boxHU=7e1;14j&boxHd=7dw;14e&boxHu=7dz;14h&boxUL=7dp;147&boxUR=7dm;144&boxUl=7do;146&boxUr=7dl;143&boxV=7dd;13v&boxVH=7e4;14m&boxVL=7dv;14d&boxVR=7ds;14a&boxVh=7e3;14l&boxVl=7du;14c&boxVr=7dr;149&boxbox=895;1bw&boxdL=7dh;13z&boxdR=7de;13w&boxdl=7bk;13m&boxdr=7bg;13l&boxh=7b4;13j&boxhD=7dx;14f&boxhU=7e0;14i&boxhd=7cc;13r&boxhu=7ck;13s&boxminus=6u7;xi&boxplus=6u6;xg&boxtimes=6u8;xk&boxuL=7dn;145&boxuR=7dk;142&boxul=7bs;13o&boxur=7bo;13n&boxv=7b6;13k&boxvH=7e2;14k&boxvL=7dt;14b&boxvR=7dq;148&boxvh=7cs;13t&boxvl=7c4;13q&boxvr=7bw;13p&bprime=6d1;ej&breve=k8;83¦=4m;1k&bscr=2kl3;1jv&bsemi=6dr;er&bsim=6rh;qd&bsime=6vh;zq&bsol=2k;x&bsolb=891;1bv&bsolhsub=7uw;16r&bull=6ci;e9&bullet=6ci;e8&bump=6ry;rp&bumpE=8fi;1gu&bumpe=6rz;ru&bumpeq=6rz;rt&cacute=7b;4p&cap=6qx;pa&capand=8ck;1dq&capbrcup=8cp;1dv&capcap=8cr;1dx&capcup=8cn;1dt&capdot=8cg;1dn&caps=6qx,1e68;p9&caret=6dd;eo&caron=jr;81&ccaps=8ct;1dz&ccaron=7h;4vç=6f;3s&ccirc=7d;4r&ccups=8cs;1dy&ccupssm=8cw;1e0&cdot=7f;4t¸=54;2f&cemptyv=88i;1bf¢=4i;1g¢erdot=53;2c&cfr=2ko0;1l4&chcy=uf;ce&check=7pv;16j&checkmark=7pv;16i&chi=qv;9s&cir=7gr;15q&cirE=88z;1bt&circ=jq;7z&circeq=6s7;sc&circlearrowleft=6nu;k6&circlearrowright=6nv;k8&circledR=4u;1w&circledS=79k;13g&circledast=6u3;xc&circledcirc=6u2;xa&circleddash=6u5;xe&cire=6s7;sd&cirfnint=8b4;1cq&cirmid=8hb;1j0&cirscir=88y;1bs&clubs=7kz;168&clubsuit=7kz;167&colon=1m;j&colone=6s4;s7&coloneq=6s4;s5&comma=18;g&commat=1s;u&comp=6pt;mv&compfn=6qg;o7&complement=6pt;mu&complexes=6iq;f6&cong=6rp;qz&congdot=8dp;1ef&conint=6r2;pj&copf=2kpg;1md&coprod=6q8;nr©=4p;1r©sr=6jb;fz&crarr=6np;k1&cross=7pz;16k&cscr=2kl4;1jw&csub=8gf;1id&csube=8gh;1if&csup=8gg;1ie&csupe=8gi;1ig&ctdot=6wf;11g&cudarrl=854;18x&cudarrr=851;18u&cuepr=6vy;10m&cuesc=6vz;10o&cularr=6nq;k3&cularrp=859;190&cup=6qy;pc&cupbrcap=8co;1du&cupcap=8cm;1ds&cupcup=8cq;1dw&cupdot=6tp;we&cupor=8cl;1dr&cups=6qy,1e68;pb&curarr=6nr;k5&curarrm=858;18z&curlyeqprec=6vy;10l&curlyeqsucc=6vz;10n&curlyvee=6vi;zr&curlywedge=6vj;zt¤=4k;1i&curvearrowleft=6nq;k2&curvearrowright=6nr;k4&cuvee=6vi;zs&cuwed=6vj;zu&cwconint=6r6;pq&cwint=6r5;po&cylcty=6y5;12u&dArr=6oj;m2&dHar=86d;19t&dagger=6cg;e5&daleth=6k8;h7&darr=6mr;ia&dash=6c0;dl&dashv=6ub;xr&dbkarow=83z;180&dblac=kd;8b&dcaron=7j;4x&dcy=tw;bv&dd=6km;hb&ddagger=6ch;e6&ddarr=6oa;ld&ddotseq=8dz;1ep°=4w;21&delta=qc;95&demptyv=88h;1be&dfisht=873;1aj&dfr=2ko1;1l5&dharl=6o3;kx&dharr=6o2;ku&diam=6v8;zc&diamond=6v8;zb&diamondsuit=7l2;16b&diams=7l2;16c&die=4o;1o&digamma=rh;a6&disin=6wi;11j&div=6v;49÷=6v;48÷ontimes=6vb;zg&divonx=6vb;zh&djcy=uq;co&dlcorn=6xq;12n&dlcrop=6x9;12a&dollar=10;6&dopf=2kph;1me&dot=k9;85&doteq=6s0;rx&doteqdot=6s1;rz&dotminus=6rc;q2&dotplus=6qc;ny&dotsquare=6u9;xm&doublebarwedge=6x2;11z&downarrow=6mr;i9&downdownarrows=6oa;lc&downharpoonleft=6o3;kv&downharpoonright=6o2;ks&drbkarow=840;182&drcorn=6xr;12p&drcrop=6x8;129&dscr=2kl5;1jx&dscy=ut;cr&dsol=8ae;1cc&dstrok=7l;4z&dtdot=6wh;11i&dtri=7gf;15j&dtrif=7ge;15h&duarr=6ph;mo&duhar=86n;1a5&dwangle=886;1b3&dzcy=v3;d0&dzigrarr=7wf;17r&eDDot=8dz;1eq&eDot=6s1;s0é=6h;3u&easter=8dq;1eg&ecaron=7v;57&ecir=6s6;sbê=6i;3v&ecolon=6s5;s9&ecy=ul;ck&edot=7r;53&ee=6kn;he&efDot=6s2;s2&efr=2ko2;1l6&eg=8ey;1g9è=6g;3t&egs=8eu;1g5&egsdot=8ew;1g7&el=8ex;1g8&elinters=73b;13e&ell=6j7;fv&els=8et;1g3&elsdot=8ev;1g6&emacr=7n;51&empty=6px;n7&emptyset=6px;n5&emptyv=6px;n6&emsp=6bn;d2&emsp13=6bo;d3&emsp14=6bp;d4&eng=97;6h&ensp=6bm;d1&eogon=7t;55&eopf=2kpi;1mf&epar=6vp;103&eparsl=89v;1c6&eplus=8dt;1ek&epsi=qd;97&epsilon=qd;96&epsiv=s5;ae&eqcirc=6s6;sa&eqcolon=6s5;s8&eqsim=6rm;qq&eqslantgtr=8eu;1g4&eqslantless=8et;1g2&equals=1p;p&equest=6sf;sj&equiv=6sh;so&equivDD=8e0;1er&eqvparsl=89x;1c8&erDot=6s3;s4&erarr=86p;1a7&escr=6jz;gs&esdot=6s0;ry&esim=6rm;qr&eta=qf;99ð=6o;41ë=6j;3w&euro=6gc;f2&excl=x;2&exist=6pv;n0&expectation=6k0;gt&exponentiale=6kn;hd&fallingdotseq=6s2;s1&fcy=uc;cb&female=7k0;163&ffilig=1dkz;1ja&fflig=1dkw;1j7&ffllig=1dl0;1jb&ffr=2ko3;1l7&filig=1dkx;1j8&fjlig=2u,2y;15&flat=7l9;16e&fllig=1dky;1j9&fltns=7g1;153&fnof=b6;7v&fopf=2kpj;1mg&forall=6ps;mt&fork=6vo;102&forkv=8gp;1in&fpartint=8b1;1cp½=59;2k&frac13=6kz;hh¼=58;2j&frac15=6l1;hj&frac16=6l5;hn&frac18=6l7;hp&frac23=6l0;hi&frac25=6l2;hk¾=5a;2m&frac35=6l3;hl&frac38=6l8;hq&frac45=6l4;hm&frac56=6l6;ho&frac58=6l9;hr&frac78=6la;hs&frasl=6dg;eq&frown=6xu;12r&fscr=2kl7;1jy&gE=6sn;t8&gEl=8ek;1ft&gacute=dx;7x&gamma=qb;94&gammad=rh;a7&gap=8ee;1fh&gbreve=7z;5b&gcirc=7x;59&gcy=tv;bu&gdot=81;5d&ge=6sl;sx&gel=6vv;10k&geq=6sl;sw&geqq=6sn;t7&geqslant=8e6;1f6&ges=8e6;1f7&gescc=8fd;1gn&gesdot=8e8;1f9&gesdoto=8ea;1fb&gesdotol=8ec;1fd&gesl=6vv,1e68;10h&gesles=8es;1g1&gfr=2ko4;1l8&gg=6sr;ts&ggg=6vt;10b&gimel=6k7;h6&gjcy=ur;cp&gl=6t3;un&glE=8eq;1fz&gla=8f9;1gj&glj=8f8;1gi&gnE=6sp;tg&gnap=8ei;1fp&gnapprox=8ei;1fo&gne=8eg;1fl&gneq=8eg;1fk&gneqq=6sp;tf&gnsim=6w7;10y&gopf=2kpk;1mh&grave=2o;14&gscr=6iy;f9&gsim=6sz;ud&gsime=8em;1fv&gsiml=8eo;1fx>=1q;s>cc=8fb;1gl>cir=8e2;1et>dot=6vr;107>lPar=87p;1aw>quest=8e4;1ev>rapprox=8ee;1fg>rarr=86w;1ad>rdot=6vr;106>reqless=6vv;10j>reqqless=8ek;1fs>rless=6t3;um>rsim=6sz;uc&gvertneqq=6sp,1e68;td&gvnE=6sp,1e68;te&hArr=6ok;m5&hairsp=6bu;da&half=59;2l&hamilt=6iz;fb&hardcy=ui;ch&harr=6ms;id&harrcir=85k;192&harrw=6nh;js&hbar=6j3;fl&hcirc=85;5g&hearts=7l1;16a&heartsuit=7l1;169&hellip=6cm;eb&hercon=6ux;yr&hfr=2ko5;1l9&hksearow=84l;18i&hkswarow=84m;18k&hoarr=6pr;mr&homtht=6rf;q5&hookleftarrow=6nd;jj&hookrightarrow=6ne;jl&hopf=2kpl;1mi&horbar=6c5;do&hscr=2kl9;1jz&hslash=6j3;fi&hstrok=87;5i&hybull=6df;ep&hyphen=6c0;dkí=6l;3y&ic=6eb;f1î=6m;3z&icy=u0;bz&iecy=tx;bw¡=4h;1f&iff=6ok;m6&ifr=2ko6;1laì=6k;3x&ii=6ko;hg&iiiint=8b0;1cn&iiint=6r1;pg&iinfin=89o;1c3&iiota=6jt;gm&ijlig=8j;5t&imacr=8b;5m&image=6j5;fp&imagline=6j4;fm&imagpart=6j5;fo&imath=8h;5r&imof=6uv;yo&imped=c5;7w&in=6q0;nd&incare=6it;f8&infin=6qm;of&infintie=89p;1c4&inodot=8h;5q&int=6qz;pe&intcal=6uy;yt&integers=6jo;gh&intercal=6uy;ys&intlarhk=8bb;1cx&intprod=8cc;1dk&iocy=up;cn&iogon=8f;5o&iopf=2kpm;1mj&iota=qh;9b&iprod=8cc;1dl¿=5b;2n&iscr=2kla;1k0&isin=6q0;nc&isinE=6wp;11r&isindot=6wl;11n&isins=6wk;11l&isinsv=6wj;11k&isinv=6q0;nb&it=6ea;ez&itilde=89;5k&iukcy=uu;csï=6n;40&jcirc=8l;5v&jcy=u1;c0&jfr=2ko7;1lb&jmath=fr;7y&jopf=2kpn;1mk&jscr=2klb;1k1&jsercy=uw;cu&jukcy=us;cq&kappa=qi;9c&kappav=s0;a9&kcedil=8n;5x&kcy=u2;c1&kfr=2ko8;1lc&kgreen=8o;5y&khcy=ud;cc&kjcy=v0;cy&kopf=2kpo;1ml&kscr=2klc;1k2&lAarr=6oq;mf&lArr=6og;ls&lAtail=84b;18a&lBarr=83y;17z&lE=6sm;t2&lEg=8ej;1fr&lHar=86a;19q&lacute=8q;60&laemptyv=88k;1bh&lagran=6j6;ft&lambda=qj;9d&lang=7vs;16z&langd=87l;1as&langle=7vs;16y&lap=8ed;1ff«=4r;1t&larr=6mo;hx&larrb=6p0;mk&larrbfs=84f;18e&larrfs=84d;18c&larrhk=6nd;jk&larrlp=6nf;jo&larrpl=855;18y&larrsim=86r;1a9&larrtl=6n6;j7&lat=8ff;1gp&latail=849;188&late=8fh;1gt&lates=8fh,1e68;1gs&lbarr=83w;17w&lbbrk=7si;16p&lbrace=3f;16&lbrack=2j;v&lbrke=87f;1am&lbrksld=87j;1aq&lbrkslu=87h;1ao&lcaron=8u;64&lcedil=8s;62&lceil=6x4;122&lcub=3f;17&lcy=u3;c2&ldca=852;18v&ldquo=6cc;dz&ldquor=6ce;e3&ldrdhar=86f;19v&ldrushar=85n;195&ldsh=6nm;jz&le=6sk;st&leftarrow=6mo;hv&leftarrowtail=6n6;j6&leftharpoondown=6nx;kd&leftharpoonup=6nw;ka&leftleftarrows=6o7;l6&leftrightarrow=6ms;ic&leftrightarrows=6o6;l4&leftrightharpoons=6ob;lf&leftrightsquigarrow=6nh;jr&leftthreetimes=6vf;zl&leg=6vu;10g&leq=6sk;ss&leqq=6sm;t1&leqslant=8e5;1f0&les=8e5;1f1&lescc=8fc;1gm&lesdot=8e7;1f8&lesdoto=8e9;1fa&lesdotor=8eb;1fc&lesg=6vu,1e68;10d&lesges=8er;1g0&lessapprox=8ed;1fe&lessdot=6vq;104&lesseqgtr=6vu;10f&lesseqqgtr=8ej;1fq&lessgtr=6t2;uj&lesssim=6sy;u9&lfisht=870;1ag&lfloor=6x6;126&lfr=2ko9;1ld&lg=6t2;uk&lgE=8ep;1fy&lhard=6nx;kf&lharu=6nw;kc&lharul=86i;19y&lhblk=7es;14o&ljcy=ux;cv&ll=6sq;tm&llarr=6o7;l7&llcorner=6xq;12m&llhard=86j;19z&lltri=7i2;15w&lmidot=8w;66&lmoust=71s;131&lmoustache=71s;130&lnE=6so;tc&lnap=8eh;1fn&lnapprox=8eh;1fm&lne=8ef;1fj&lneq=8ef;1fi&lneqq=6so;tb&lnsim=6w6;10x&loang=7vw;175&loarr=6pp;mp&lobrk=7vq;16u&longleftarrow=7w5;178&longleftrightarrow=7w7;17e&longmapsto=7wc;17p&longrightarrow=7w6;17b&looparrowleft=6nf;jn&looparrowright=6ng;jp&lopar=879;1ak&lopf=2kpp;1mm&loplus=8bx;1d6&lotimes=8c4;1dc&lowast=6qf;o5&lowbar=2n;12&loz=7gq;15p&lozenge=7gq;15o&lozf=8a3;1ca&lpar=14;b&lparlt=87n;1au&lrarr=6o6;l5&lrcorner=6xr;12o&lrhar=6ob;lg&lrhard=86l;1a1&lrm=6by;di&lrtri=6v3;yx&lsaquo=6d5;ek&lscr=2kld;1k3&lsh=6nk;jw&lsim=6sy;ua&lsime=8el;1fu&lsimg=8en;1fw&lsqb=2j;w&lsquo=6c8;ds&lsquor=6ca;dw&lstrok=8y;68<=1o;n<cc=8fa;1gk<cir=8e1;1es<dot=6vq;105<hree=6vf;zm<imes=6vd;zj<larr=86u;1ac<quest=8e3;1eu<rPar=87q;1ax<ri=7gj;15n<rie=6us;yi<rif=7gi;15l&lurdshar=85m;194&luruhar=86e;19u&lvertneqq=6so,1e68;t9&lvnE=6so,1e68;ta&mDDot=6re;q4¯=4v;20&male=7k2;164&malt=7q8;16m&maltese=7q8;16l&map=6na;jg&mapsto=6na;jf&mapstodown=6nb;ji&mapstoleft=6n8;jb&mapstoup=6n9;jd&marker=7fy;152&mcomma=8bt;1d4&mcy=u4;c3&mdash=6c4;dn&measuredangle=6qp;ok&mfr=2koa;1le&mho=6jr;gjµ=51;29&mid=6qr;oq&midast=16;d&midcir=8hc;1j1·=53;2d&minus=6qa;nu&minusb=6u7;xj&minusd=6rc;q3&minusdu=8bu;1d5&mlcp=8gr;1ip&mldr=6cm;ec&mnplus=6qb;nw&models=6uf;xy&mopf=2kpq;1mn&mp=6qb;nx&mscr=2kle;1k4&mstpos=6ri;qf&mu=qk;9e&multimap=6uw;yp&mumap=6uw;yq&nGg=6vt,mw;10a&nGt=6sr,6he;tp&nGtv=6sr,mw;to&nLeftarrow=6od;lk&nLeftrightarrow=6oe;lm&nLl=6vs,mw;108&nLt=6sq,6he;tj&nLtv=6sq,mw;ti&nRightarrow=6of;lo&nVDash=6un;y7&nVdash=6um;y6&nabla=6pz;n8&nacute=90;6a&nang=6qo,6he;oh&nap=6rt;rb&napE=8ds,mw;1ei&napid=6rv,mw;re&napos=95;6f&napprox=6rt;ra&natur=7la;16g&natural=7la;16f&naturals=6j9;fw =4g;1e&nbump=6ry,mw;rm&nbumpe=6rz,mw;rr&ncap=8cj;1dp&ncaron=94;6e&ncedil=92;6c&ncong=6rr;r2&ncongdot=8dp,mw;1ee&ncup=8ci;1do&ncy=u5;c4&ndash=6c3;dm&ne=6sg;sl&neArr=6on;mb&nearhk=84k;18h&nearr=6mv;im&nearrow=6mv;il&nedot=6s0,mw;rv&nequiv=6si;sq&nesear=84o;18n&nesim=6rm,mw;qo&nexist=6pw;n3&nexists=6pw;n2&nfr=2kob;1lf&ngE=6sn,mw;t4&nge=6sx;u7&ngeq=6sx;u6&ngeqq=6sn,mw;t5&ngeqslant=8e6,mw;1f3&nges=8e6,mw;1f4&ngsim=6t1;uh&ngt=6sv;u1&ngtr=6sv;u0&nhArr=6oe;ln&nharr=6ni;ju&nhpar=8he;1j3&ni=6q3;nk&nis=6ws;11u&nisd=6wq;11s&niv=6q3;nj&njcy=uy;cw&nlArr=6od;ll&nlE=6sm,mw;sy&nlarr=6my;iu&nldr=6cl;ea&nle=6sw;u4&nleftarrow=6my;it&nleftrightarrow=6ni;jt&nleq=6sw;u3&nleqq=6sm,mw;sz&nleqslant=8e5,mw;1ex&nles=8e5,mw;1ey&nless=6su;tx&nlsim=6t0;uf&nlt=6su;ty&nltri=6wa;115&nltrie=6wc;11b&nmid=6qs;ou&nopf=2kpr;1mo¬=4s;1u¬in=6q1;ng¬inE=6wp,mw;11q¬indot=6wl,mw;11m¬inva=6q1;nf¬invb=6wn;11p¬invc=6wm;11o¬ni=6q4;nn¬niva=6q4;nm¬nivb=6wu;11w¬nivc=6wt;11v&npar=6qu;p4&nparallel=6qu;p2&nparsl=8hp,6hx;1j5&npart=6pu,mw;mw&npolint=8b8;1cu&npr=6tc;vd&nprcue=6w0;10q&npre=8fj,mw;1gw&nprec=6tc;vc&npreceq=8fj,mw;1gx&nrArr=6of;lp&nrarr=6mz;iw&nrarrc=84z,mw;18s&nrarrw=6n1,mw;ix&nrightarrow=6mz;iv&nrtri=6wb;118&nrtrie=6wd;11e&nsc=6td;vg&nsccue=6w1;10s&nsce=8fk,mw;1h2&nscr=2klf;1k5&nshortmid=6qs;os&nshortparallel=6qu;p1&nsim=6rl;qm&nsime=6ro;qx&nsimeq=6ro;qw&nsmid=6qs;ot&nspar=6qu;p3&nsqsube=6w2;10u&nsqsupe=6w3;10w&nsub=6tg;vs&nsubE=8g5,mw;1hv&nsube=6tk;w2&nsubset=6te,6he;vi&nsubseteq=6tk;w1&nsubseteqq=8g5,mw;1hw&nsucc=6td;vf&nsucceq=8fk,mw;1h3&nsup=6th;vt&nsupE=8g6,mw;1hz&nsupe=6tl;w5&nsupset=6tf,6he;vn&nsupseteq=6tl;w4&nsupseteqq=8g6,mw;1i0&ntgl=6t5;urñ=6p;42&ntlg=6t4;up&ntriangleleft=6wa;114&ntrianglelefteq=6wc;11a&ntriangleright=6wb;117&ntrianglerighteq=6wd;11d&nu=ql;9f&num=z;5&numero=6ja;fy&numsp=6br;d5&nvDash=6ul;y5&nvHarr=83o;17u&nvap=6rx,6he;ri&nvdash=6uk;y4&nvge=6sl,6he;su&nvgt=1q,6he;q&nvinfin=89q;1c5&nvlArr=83m;17s&nvle=6sk,6he;sr&nvlt=1o,6he;l&nvltrie=6us,6he;yf&nvrArr=83n;17t&nvrtrie=6ut,6he;yj&nvsim=6rg,6he;q6&nwArr=6om;ma&nwarhk=84j;18g&nwarr=6mu;ij&nwarrow=6mu;ii&nwnear=84n;18m&oS=79k;13hó=6r;44&oast=6u3;xd&ocir=6u2;xbô=6s;45&ocy=u6;c5&odash=6u5;xf&odblac=9d;6l&odiv=8c8;1dg&odot=6u1;x9&odsold=88s;1bn&oelig=9f;6n&ofcir=88v;1bp&ofr=2koc;1lg&ogon=kb;87ò=6q;43&ogt=88x;1br&ohbar=88l;1bi&ohm=q1;91&oint=6r2;pk&olarr=6nu;k7&olcir=88u;1bo&olcross=88r;1bm&oline=6da;en&olt=88w;1bq&omacr=99;6j&omega=qx;9u&omicron=qn;9h&omid=88m;1bj&ominus=6ty;x4&oopf=2kps;1mp&opar=88n;1bk&operp=88p;1bl&oplus=6tx;x2&or=6qw;p8&orarr=6nv;k9&ord=8d9;1ea&order=6k4;h1&orderof=6k4;h0ª=4q;1sº=56;2h&origof=6uu;yn&oror=8d2;1e4&orslope=8d3;1e5&orv=8d7;1e8&oscr=6k4;h2ø=6w;4a&osol=6u0;x7õ=6t;46&otimes=6tz;x6&otimesas=8c6;1deö=6u;47&ovbar=6yl;12x&par=6qt;oz¶=52;2a¶llel=6qt;ox&parsim=8hf;1j4&parsl=8hp;1j6&part=6pu;my&pcy=u7;c6&percnt=11;7&period=1a;h&permil=6cw;ed&perp=6ud;xw&pertenk=6cx;ee&pfr=2kod;1lh&phi=qu;9r&phiv=r9;a2&phmmat=6k3;gy&phone=7im;162&pi=qo;9i&pitchfork=6vo;101&piv=ra;a4&planck=6j3;fj&planckh=6j2;fh&plankv=6j3;fk&plus=17;f&plusacir=8bn;1cz&plusb=6u6;xh&pluscir=8bm;1cy&plusdo=6qc;nz&plusdu=8bp;1d1&pluse=8du;1el±=4x;23&plussim=8bq;1d2&plustwo=8br;1d3&pm=4x;24&pointint=8b9;1cv&popf=2kpt;1mq£=4j;1h&pr=6t6;uu&prE=8fn;1h7&prap=8fr;1he&prcue=6t8;v0&pre=8fj;1h0&prec=6t6;ut&precapprox=8fr;1hd&preccurlyeq=6t8;uz&preceq=8fj;1gz&precnapprox=8ft;1hh&precneqq=8fp;1h9&precnsim=6w8;10z&precsim=6ta;v5&prime=6cy;ef&primes=6jd;g2&prnE=8fp;1ha&prnap=8ft;1hi&prnsim=6w8;110&prod=6q7;np&profalar=6y6;12v&profline=6xe;12e&profsurf=6xf;12f&prop=6ql;oe&propto=6ql;oc&prsim=6ta;v6&prurel=6uo;y8&pscr=2klh;1k6&psi=qw;9t&puncsp=6bs;d6&qfr=2koe;1li&qint=8b0;1co&qopf=2kpu;1mr&qprime=6dz;es&qscr=2kli;1k7&quaternions=6j1;ff&quatint=8ba;1cw&quest=1r;t&questeq=6sf;si"=y;4&rAarr=6or;mh&rArr=6oi;lz&rAtail=84c;18b&rBarr=83z;181&rHar=86c;19s&race=6rh,mp;qb&racute=9h;6p&radic=6qi;o8&raemptyv=88j;1bg&rang=7vt;172&rangd=87m;1at&range=885;1b2&rangle=7vt;171»=57;2i&rarr=6mq;i6&rarrap=86t;1ab&rarrb=6p1;mm&rarrbfs=84g;18f&rarrc=84z;18t&rarrfs=84e;18d&rarrhk=6ne;jm&rarrlp=6ng;jq&rarrpl=85h;191&rarrsim=86s;1aa&rarrtl=6n7;j9&rarrw=6n1;iz&ratail=84a;189&ratio=6ra;pz&rationals=6je;g4&rbarr=83x;17y&rbbrk=7sj;16q&rbrace=3h;1b&rbrack=2l;y&rbrke=87g;1an&rbrksld=87i;1ap&rbrkslu=87k;1ar&rcaron=9l;6t&rcedil=9j;6r&rceil=6x5;124&rcub=3h;1c&rcy=u8;c7&rdca=853;18w&rdldhar=86h;19x&rdquo=6cd;e2&rdquor=6cd;e1&rdsh=6nn;k0&real=6jg;g9&realine=6jf;g6&realpart=6jg;g8&reals=6jh;gc&rect=7fx;151®=4u;1y&rfisht=871;1ah&rfloor=6x7;128&rfr=2kof;1lj&rhard=6o1;kr&rharu=6o0;ko&rharul=86k;1a0&rho=qp;9j&rhov=s1;ab&rightarrow=6mq;i4&rightarrowtail=6n7;j8&rightharpoondown=6o1;kp&rightharpoonup=6o0;km&rightleftarrows=6o4;kz&rightleftharpoons=6oc;lh&rightrightarrows=6o9;la&rightsquigarrow=6n1;iy&rightthreetimes=6vg;zn&ring=ka;86&risingdotseq=6s3;s3&rlarr=6o4;l0&rlhar=6oc;lj&rlm=6bz;dj&rmoust=71t;133&rmoustache=71t;132&rnmid=8ha;1iz&roang=7vx;176&roarr=6pq;mq&robrk=7vr;16w&ropar=87a;1al&ropf=2kpv;1ms&roplus=8by;1d7&rotimes=8c5;1dd&rpar=15;c&rpargt=87o;1av&rppolint=8b6;1cs&rrarr=6o9;lb&rsaquo=6d6;el&rscr=2klj;1k8&rsh=6nl;jy&rsqb=2l;z&rsquo=6c9;dv&rsquor=6c9;du&rthree=6vg;zo&rtimes=6ve;zk&rtri=7g9;15d&rtrie=6ut;ym&rtrif=7g8;15b&rtriltri=89a;1by&ruluhar=86g;19w&rx=6ji;ge&sacute=9n;6v&sbquo=6ca;dx&sc=6t7;ux&scE=8fo;1h8&scap=8fs;1hg&scaron=9t;71&sccue=6t9;v3&sce=8fk;1h6&scedil=9r;6z&scirc=9p;6x&scnE=8fq;1hc&scnap=8fu;1hk&scnsim=6w9;112&scpolint=8b7;1ct&scsim=6tb;va&scy=u9;c8&sdot=6v9;zd&sdotb=6u9;xn&sdote=8di;1ec&seArr=6oo;mc&searhk=84l;18j&searr=6mw;ip&searrow=6mw;io§=4n;1l&semi=1n;k&seswar=84p;18p&setminus=6qe;o2&setmn=6qe;o4&sext=7qu;16n&sfr=2kog;1lk&sfrown=6xu;12q&sharp=7lb;16h&shchcy=uh;cg&shcy=ug;cf&shortmid=6qr;oo&shortparallel=6qt;ow­=4t;1v&sigma=qr;9n&sigmaf=qq;9l&sigmav=qq;9m&sim=6rg;qa&simdot=8dm;1ed&sime=6rn;qu&simeq=6rn;qt&simg=8f2;1gb&simgE=8f4;1gd&siml=8f1;1ga&simlE=8f3;1gc&simne=6rq;r0&simplus=8bo;1d0&simrarr=86q;1a8&slarr=6mo;hw&smallsetminus=6qe;o0&smashp=8c3;1db&smeparsl=89w;1c7&smid=6qr;op&smile=6xv;12t&smt=8fe;1go&smte=8fg;1gr&smtes=8fg,1e68;1gq&softcy=uk;cj&sol=1b;i&solb=890;1bu&solbar=6yn;12y&sopf=2kpw;1mt&spades=7kw;166&spadesuit=7kw;165&spar=6qt;oy&sqcap=6tv;wx&sqcaps=6tv,1e68;wv&sqcup=6tw;x0&sqcups=6tw,1e68;wy&sqsub=6tr;wk&sqsube=6tt;wr&sqsubset=6tr;wj&sqsubseteq=6tt;wq&sqsup=6ts;wo&sqsupe=6tu;wu&sqsupset=6ts;wn&sqsupseteq=6tu;wt&squ=7fl;14v&square=7fl;14u&squarf=7fu;14y&squf=7fu;14z&srarr=6mq;i5&sscr=2klk;1k9&ssetmn=6qe;o3&ssmile=6xv;12s&sstarf=6va;ze&star=7ie;161&starf=7id;160&straightepsilon=s5;ac&straightphi=r9;a0&strns=4v;1z&sub=6te;vl&subE=8g5;1hy&subdot=8fx;1hn&sube=6ti;vw&subedot=8g3;1ht&submult=8g1;1hr&subnE=8gb;1i8&subne=6tm;w9&subplus=8fz;1hp&subrarr=86x;1ae&subset=6te;vk&subseteq=6ti;vv&subseteqq=8g5;1hx&subsetneq=6tm;w8&subsetneqq=8gb;1i7&subsim=8g7;1i3&subsub=8gl;1ij&subsup=8gj;1ih&succ=6t7;uw&succapprox=8fs;1hf&succcurlyeq=6t9;v2&succeq=8fk;1h5&succnapprox=8fu;1hj&succneqq=8fq;1hb&succnsim=6w9;111&succsim=6tb;v9&sum=6q9;nt&sung=7l6;16d&sup=6tf;vr¹=55;2g²=4y;25³=4z;26&supE=8g6;1i2&supdot=8fy;1ho&supdsub=8go;1im&supe=6tj;vz&supedot=8g4;1hu&suphsol=7ux;16s&suphsub=8gn;1il&suplarr=86z;1af&supmult=8g2;1hs&supnE=8gc;1ic&supne=6tn;wd&supplus=8g0;1hq&supset=6tf;vq&supseteq=6tj;vy&supseteqq=8g6;1i1&supsetneq=6tn;wc&supsetneqq=8gc;1ib&supsim=8g8;1i4&supsub=8gk;1ii&supsup=8gm;1ik&swArr=6op;md&swarhk=84m;18l&swarr=6mx;is&swarrow=6mx;ir&swnwar=84q;18rß=67;3k&target=6xi;12h&tau=qs;9o&tbrk=71w;135&tcaron=9x;75&tcedil=9v;73&tcy=ua;c9&tdot=6hn;f4&telrec=6xh;12g&tfr=2koh;1ll&there4=6r8;pv&therefore=6r8;pu&theta=qg;9a&thetasym=r5;9v&thetav=r5;9x&thickapprox=6rs;r3&thicksim=6rg;q7&thinsp=6bt;d8&thkap=6rs;r7&thksim=6rg;q8þ=72;4g&tilde=kc;89×=5z;3c×b=6u8;xl×bar=8c1;1da×d=8c0;1d9&tint=6r1;ph&toea=84o;18o&top=6uc;xt&topbot=6ye;12w&topcir=8hd;1j2&topf=2kpx;1mu&topfork=8gq;1io&tosa=84p;18q&tprime=6d0;eh&trade=6jm;gg&triangle=7g5;158&triangledown=7gf;15i&triangleleft=7gj;15m&trianglelefteq=6us;yh&triangleq=6sc;sg&triangleright=7g9;15c&trianglerighteq=6ut;yl&tridot=7ho;15r&trie=6sc;sh&triminus=8ca;1di&triplus=8c9;1dh&trisb=899;1bx&tritime=8cb;1dj&trpezium=736;13d&tscr=2kll;1ka&tscy=ue;cd&tshcy=uz;cx&tstrok=9z;77&twixt=6ss;tu&twoheadleftarrow=6n2;j0&twoheadrightarrow=6n4;j3&uArr=6oh;lv&uHar=86b;19rú=6y;4c&uarr=6mp;i1&ubrcy=v2;cz&ubreve=a5;7dû=6z;4d&ucy=ub;ca&udarr=6o5;l2&udblac=a9;7h&udhar=86m;1a3&ufisht=872;1ai&ufr=2koi;1lmù=6x;4b&uharl=6nz;kl&uharr=6ny;ki&uhblk=7eo;14n&ulcorn=6xo;12j&ulcorner=6xo;12i&ulcrop=6xb;12c&ultri=7i0;15u&umacr=a3;7b¨=4o;1p&uogon=ab;7j&uopf=2kpy;1mv&uparrow=6mp;i0&updownarrow=6mt;if&upharpoonleft=6nz;kj&upharpoonright=6ny;kg&uplus=6tq;wg&upsi=qt;9q&upsih=r6;9y&upsilon=qt;9p&upuparrows=6o8;l8&urcorn=6xp;12l&urcorner=6xp;12k&urcrop=6xa;12b&uring=a7;7f&urtri=7i1;15v&uscr=2klm;1kb&utdot=6wg;11h&utilde=a1;79&utri=7g5;159&utrif=7g4;157&uuarr=6o8;l9ü=70;4e&uwangle=887;1b4&vArr=6ol;m9&vBar=8h4;1iu&vBarv=8h5;1iv&vDash=6ug;y0&vangrt=87w;1az&varepsilon=s5;ad&varkappa=s0;a8&varnothing=6px;n4&varphi=r9;a1&varpi=ra;a3&varpropto=6ql;ob&varr=6mt;ig&varrho=s1;aa&varsigma=qq;9k&varsubsetneq=6tm,1e68;w6&varsubsetneqq=8gb,1e68;1i5&varsupsetneq=6tn,1e68;wa&varsupsetneqq=8gc,1e68;1i9&vartheta=r5;9w&vartriangleleft=6uq;y9&vartriangleright=6ur;yc&vcy=tu;bt&vdash=6ua;xp&vee=6qw;p7&veebar=6uz;yu&veeeq=6sa;sf&vellip=6we;11f&verbar=3g;19&vert=3g;1a&vfr=2koj;1ln&vltri=6uq;yb&vnsub=6te,6he;vj&vnsup=6tf,6he;vo&vopf=2kpz;1mw&vprop=6ql;od&vrtri=6ur;ye&vscr=2kln;1kc&vsubnE=8gb,1e68;1i6&vsubne=6tm,1e68;w7&vsupnE=8gc,1e68;1ia&vsupne=6tn,1e68;wb&vzigzag=87u;1ay&wcirc=ad;7l&wedbar=8db;1eb&wedge=6qv;p5&wedgeq=6s9;se&weierp=6jc;g0&wfr=2kok;1lo&wopf=2kq0;1mx&wp=6jc;g1&wr=6rk;qk&wreath=6rk;qj&wscr=2klo;1kd&xcap=6v6;z6&xcirc=7hr;15t&xcup=6v7;z9&xdtri=7gd;15f&xfr=2kol;1lp&xhArr=7wa;17o&xharr=7w7;17f&xi=qm;9g&xlArr=7w8;17i&xlarr=7w5;179&xmap=7wc;17q&xnis=6wr;11t&xodot=8ao;1ce&xopf=2kq1;1my&xoplus=8ap;1cg&xotime=8aq;1ci&xrArr=7w9;17l&xrarr=7w6;17c&xscr=2klp;1ke&xsqcup=8au;1cm&xuplus=8as;1ck&xutri=7g3;155&xvee=6v5;z2&xwedge=6v4;yzý=71;4f&yacy=un;cm&ycirc=af;7n&ycy=uj;ci¥=4l;1j&yfr=2kom;1lq&yicy=uv;ct&yopf=2kq2;1mz&yscr=2klq;1kf&yucy=um;clÿ=73;4h&zacute=ai;7q&zcaron=am;7u&zcy=tz;by&zdot=ak;7s&zeetrf=6js;gk&zeta=qe;98&zfr=2kon;1lr&zhcy=ty;bx&zigrarr=6ot;mi&zopf=2kq3;1n0&zscr=2klr;1kg&zwj=6bx;dh&zwnj=6bw;dg&";
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/FormElement.java
|
package org.jsoup.nodes;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.HttpConnection;
import org.jsoup.helper.Validate;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
/**
* A HTML Form Element provides ready access to the form fields/controls that are associated with it. It also allows a
* form to easily be submitted.
*/
public class FormElement extends Element {
private final Elements elements = new Elements();
/**
* Create a new, standalone form element.
*
* @param tag tag of this element
* @param baseUri the base URI
* @param attributes initial attributes
*/
public FormElement(Tag tag, String baseUri, Attributes attributes) {
super(tag, baseUri, attributes);
}
/**
* Get the list of form control elements associated with this form.
* @return form controls associated with this element.
*/
public Elements elements() {
return elements;
}
/**
* Add a form control element to this form.
* @param element form control to add
* @return this form element, for chaining
*/
public FormElement addElement(Element element) {
elements.add(element);
return this;
}
@Override
protected void removeChild(Node out) {
super.removeChild(out);
elements.remove(out);
}
/**
Prepare to submit this form. A Connection object is created with the request set up from the form values. This
Connection will inherit the settings and the cookies (etc) of the connection/session used to request this Document
(if any), as available in {@link Document#connection()}
<p>You can then set up other options (like user-agent, timeout, cookies), then execute it.</p>
@return a connection prepared from the values of this form, in the same session as the one used to request it
@throws IllegalArgumentException if the form's absolute action URL cannot be determined. Make sure you pass the
document's base URI when parsing.
*/
public Connection submit() {
String action = hasAttr("action") ? absUrl("action") : baseUri();
Validate.notEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing.");
Connection.Method method = attr("method").equalsIgnoreCase("POST") ?
Connection.Method.POST : Connection.Method.GET;
Document owner = ownerDocument();
Connection connection = owner != null? owner.connection().newRequest() : Jsoup.newSession();
return connection.url(action)
.data(formData())
.method(method);
}
/**
* Get the data that this form submits. The returned list is a copy of the data, and changes to the contents of the
* list will not be reflected in the DOM.
* @return a list of key vals
*/
public List<Connection.KeyVal> formData() {
ArrayList<Connection.KeyVal> data = new ArrayList<>();
// 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 (type.equalsIgnoreCase("button")) continue; // browsers don't submit these
if ("select".equals(el.normalName())) {
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.selectFirst("option");
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;
}
@Override
public FormElement clone() {
return (FormElement) super.clone();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/LeafNode.java
|
package org.jsoup.nodes;
import org.jsoup.helper.Validate;
import java.util.Collections;
import java.util.List;
abstract class LeafNode extends Node {
Object value; // either a string value, or an attribute map (in the rare case multiple attributes are set)
protected final boolean hasAttributes() {
return value instanceof Attributes;
}
@Override
public final Attributes attributes() {
ensureAttributes();
return (Attributes) value;
}
private void ensureAttributes() {
if (!hasAttributes()) {
Object coreValue = value;
Attributes attributes = new Attributes();
value = attributes;
if (coreValue != null)
attributes.put(nodeName(), (String) coreValue);
}
}
String coreValue() {
return attr(nodeName());
}
void coreValue(String value) {
attr(nodeName(), value);
}
@Override
public String attr(String key) {
Validate.notNull(key);
if (!hasAttributes()) {
return key.equals(nodeName()) ? (String) value : EmptyString;
}
return super.attr(key);
}
@Override
public Node attr(String key, String value) {
if (!hasAttributes() && key.equals(nodeName())) {
this.value = value;
} else {
ensureAttributes();
super.attr(key, value);
}
return this;
}
@Override
public boolean hasAttr(String key) {
ensureAttributes();
return super.hasAttr(key);
}
@Override
public Node removeAttr(String key) {
ensureAttributes();
return super.removeAttr(key);
}
@Override
public String absUrl(String key) {
ensureAttributes();
return super.absUrl(key);
}
@Override
public String baseUri() {
return hasParent() ? parent().baseUri() : "";
}
@Override
protected void doSetBaseUri(String baseUri) {
// noop
}
@Override
public int childNodeSize() {
return 0;
}
@Override
public Node empty() {
return this;
}
@Override
protected List<Node> ensureChildNodes() {
return EmptyNodes;
}
@Override
protected LeafNode doClone(Node parent) {
LeafNode clone = (LeafNode) super.doClone(parent);
// Object value could be plain string or attributes - need to clone
if (hasAttributes())
clone.value = ((Attributes) value).clone();
return clone;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/Node.java
|
package org.jsoup.nodes;
import org.jsoup.SerializationException;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import ai.platon.pulsar.jsoup.ext.NodeExt;
import org.jsoup.select.NodeFilter;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
The base, abstract Node model. Elements, Documents, Comments etc are all Node instances.
@author Jonathan Hedley, jonathan@hedley.net */
public abstract class Node implements Cloneable {
static final List<Node> EmptyNodes = Collections.emptyList();
static final String EmptyString = "";
@Nullable Node parentNode; // Nodes don't always have parents
int siblingIndex;
private final NodeExt extension = new NodeExt(this);
/**
* Default constructor. Doesn't setup base uri, children, or attributes; use with caution.
*/
protected Node() {
}
public NodeExt getExtension() {
return extension;
}
/**
Get the node name of this node. Use for debugging purposes and not logic switching (for that, use instanceof).
@return node name
*/
public abstract String nodeName();
/**
* Check if this Node has an actual Attributes object.
*/
protected abstract boolean hasAttributes();
/**
Checks if this node has a parent. Nodes won't have parents if (e.g.) they are newly created and not added as a child
to an existing node, or if they are a {@link #shallowClone()}. In such cases, {@link #parent()} will return {@code null}.
@return if this node has a parent.
*/
public boolean hasParent() {
return parentNode != null;
}
/**
* Get an attribute's value by its key. <b>Case insensitive</b>
* <p>
* To get an absolute URL from an attribute that may be a relative URL, prefix the key with <code><b>abs</b></code>,
* which is a shortcut to the {@link #absUrl} method.
* </p>
* E.g.:
* <blockquote><code>String url = a.attr("abs:href");</code></blockquote>
*
* @param attributeKey The attribute key.
* @return The attribute, or empty string if not present (to avoid nulls).
* @see #attributes()
* @see #hasAttr(String)
* @see #absUrl(String)
*/
public String attr(String attributeKey) {
Validate.notNull(attributeKey);
if (!hasAttributes())
return EmptyString;
String val = attributes().getIgnoreCase(attributeKey);
if (val.length() > 0)
return val;
else if (attributeKey.startsWith("abs:"))
return absUrl(attributeKey.substring("abs:".length()));
else return "";
}
/**
* Get all of the element's attributes.
* @return attributes (which implements iterable, in same order as presented in original HTML).
*/
public abstract Attributes attributes();
/**
Get the number of attributes that this Node has.
@return the number of attributes
@since 1.14.2
*/
public int attributesSize() {
// added so that we can test how many attributes exist without implicitly creating the Attributes object
return hasAttributes() ? attributes().size() : 0;
}
/**
* Set an attribute (key=value). If the attribute already exists, it is replaced. The attribute key comparison is
* <b>case insensitive</b>. The key will be set with case sensitivity as set in the parser settings.
* @param attributeKey The attribute key.
* @param attributeValue The attribute value.
* @return this (for chaining)
*/
public Node attr(String attributeKey, String attributeValue) {
attributeKey = NodeUtils.parser(this).settings().normalizeAttribute(attributeKey);
attributes().putIgnoreCase(attributeKey, attributeValue);
return this;
}
/**
* Test if this Node has an attribute. <b>Case insensitive</b>.
* @param attributeKey The attribute key to check.
* @return true if the attribute exists, false if not.
*/
public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
if (!hasAttributes())
return false;
if (attributeKey.startsWith("abs:")) {
String key = attributeKey.substring("abs:".length());
if (attributes().hasKeyIgnoreCase(key) && !absUrl(key).isEmpty())
return true;
}
return attributes().hasKeyIgnoreCase(attributeKey);
}
/**
* Remove an attribute from this node.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
public Node removeAttr(String attributeKey) {
Validate.notNull(attributeKey);
if (hasAttributes())
attributes().removeIgnoreCase(attributeKey);
return this;
}
/**
* Clear (remove) all of the attributes in this node.
* @return this, for chaining
*/
public Node clearAttributes() {
if (hasAttributes()) {
Iterator<Attribute> it = attributes().iterator();
while (it.hasNext()) {
it.next();
it.remove();
}
}
return this;
}
/**
Get the base URI that applies to this node. Will return an empty string if not defined. Used to make relative links
absolute.
@return base URI
@see #absUrl
*/
public abstract String baseUri();
/**
* Set the baseUri for just this node (not its descendants), if this Node tracks base URIs.
* @param baseUri new URI
*/
protected abstract void doSetBaseUri(String baseUri);
/**
Update the base URI of this node and all of its descendants.
@param baseUri base URI to set
*/
public void setBaseUri(final String baseUri) {
Validate.notNull(baseUri);
doSetBaseUri(baseUri);
}
/**
* Get an absolute URL from a URL attribute that may be relative (such as an <code><a href></code> or
* <code><img src></code>).
* <p>
* E.g.: <code>String absUrl = linkEl.absUrl("href");</code>
* </p>
* <p>
* If the attribute value is already absolute (i.e. it starts with a protocol, like
* <code>http://</code> or <code>https://</code> etc), and it successfully parses as a URL, the attribute is
* returned directly. Otherwise, it is treated as a URL relative to the element's {@link #baseUri}, and made
* absolute using that.
* </p>
* <p>
* As an alternate, you can use the {@link #attr} method with the <code>abs:</code> prefix, e.g.:
* <code>String absUrl = linkEl.attr("abs:href");</code>
* </p>
*
* @param attributeKey The attribute key
* @return An absolute URL if one could be made, or an empty string (not null) if the attribute was missing or
* could not be made successfully into a URL.
* @see #attr
* @see java.net.URL#URL(java.net.URL, String)
*/
public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
if (!(hasAttributes() && attributes().hasKeyIgnoreCase(attributeKey))) // not using hasAttr, so that we don't recurse down hasAttr->absUrl
return "";
return StringUtil.resolve(baseUri(), attributes().getIgnoreCase(attributeKey));
}
protected abstract List<Node> ensureChildNodes();
/**
Get a child node by its 0-based index.
@param index index of child node
@return the child node at this index. Throws a {@code IndexOutOfBoundsException} if the index is out of bounds.
*/
public Node childNode(int index) {
return ensureChildNodes().get(index);
}
/**
Get this node's children. Presented as an unmodifiable list: new children can not be added, but the child nodes
themselves can be manipulated.
@return list of children. If no children, returns an empty list.
*/
public List<Node> childNodes() {
if (childNodeSize() == 0)
return EmptyNodes;
List<Node> children = ensureChildNodes();
List<Node> rewrap = new ArrayList<>(children.size()); // wrapped so that looping and moving will not throw a CME as the source changes
rewrap.addAll(children);
return Collections.unmodifiableList(rewrap);
}
/**
* Returns a deep copy of this node's children. Changes made to these nodes will not be reflected in the original
* nodes
* @return a deep copy of this node's children
*/
public List<Node> childNodesCopy() {
final List<Node> nodes = ensureChildNodes();
final ArrayList<Node> children = new ArrayList<>(nodes.size());
for (Node node : nodes) {
children.add(node.clone());
}
return children;
}
/**
* Get the number of child nodes that this node holds.
* @return the number of child nodes that this node holds.
*/
public abstract int childNodeSize();
protected Node[] childNodesAsArray() {
return ensureChildNodes().toArray(new Node[0]);
}
/**
* Delete all this node's children.
* @return this node, for chaining
*/
public abstract Node empty();
/**
Gets this node's parent node.
@return parent node; or null if no parent.
@see #hasParent()
*/
public @Nullable Node parent() {
return parentNode;
}
/**
Gets this node's parent node. Not overridable by extending classes, so useful if you really just need the Node type.
@return parent node; or null if no parent.
*/
public @Nullable final Node parentNode() {
return parentNode;
}
/**
* Get this node's root node; that is, its topmost ancestor. If this node is the top ancestor, returns {@code this}.
* @return topmost ancestor.
*/
public Node root() {
Node node = this;
while (node.parentNode != null)
node = node.parentNode;
return node;
}
/**
* Gets the Document associated with this Node.
* @return the Document associated with this Node, or null if there is no such Document.
*/
public @Nullable Document ownerDocument() {
Node root = root();
return (root instanceof Document) ? (Document) root : null;
}
/**
* Remove (delete) this node from the DOM tree. If this node has children, they are also removed.
*/
public void remove() {
Validate.notNull(parentNode);
parentNode.removeChild(this);
}
/**
* Insert the specified HTML into the DOM before this node (as a preceding sibling).
* @param html HTML to add before this node
* @return this node, for chaining
* @see #after(String)
*/
public Node before(String html) {
addSiblingHtml(siblingIndex, html);
return this;
}
/**
* Insert the specified node into the DOM before this node (as a preceding sibling).
* @param node to add before this node
* @return this node, for chaining
* @see #after(Node)
*/
public Node before(Node node) {
Validate.notNull(node);
Validate.notNull(parentNode);
parentNode.addChildren(siblingIndex, node);
return this;
}
/**
* Insert the specified HTML into the DOM after this node (as a following sibling).
* @param html HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
public Node after(String html) {
addSiblingHtml(siblingIndex + 1, html);
return this;
}
/**
* Insert the specified node into the DOM after this node (as a following sibling).
* @param node to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
public Node after(Node node) {
Validate.notNull(node);
Validate.notNull(parentNode);
parentNode.addChildren(siblingIndex + 1, node);
return this;
}
private void addSiblingHtml(int index, String html) {
Validate.notNull(html);
Validate.notNull(parentNode);
Element context = parent() instanceof Element ? (Element) parent() : null;
List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri());
parentNode.addChildren(index, nodes.toArray(new Node[0]));
}
/**
Wrap the supplied HTML around this node.
@param html HTML to wrap around this node, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep. If
the input HTML does not parse to a result starting with an Element, this will be a no-op.
@return this node, for chaining.
*/
public Node wrap(String html) {
Validate.notEmpty(html);
// Parse context - parent (because wrapping), this, or null
Element context =
parentNode != null && parentNode instanceof Element ? (Element) parentNode :
this instanceof Element ? (Element) this :
null;
List<Node> wrapChildren = NodeUtils.parser(this).parseFragmentInput(html, context, baseUri());
Node wrapNode = wrapChildren.get(0);
if (!(wrapNode instanceof Element)) // nothing to wrap with; noop
return this;
Element wrap = (Element) wrapNode;
Element deepest = getDeepChild(wrap);
if (parentNode != null)
parentNode.replaceChild(this, wrap);
deepest.addChildren(this); // side effect of tricking wrapChildren to lose first
// remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is remainder
if (wrapChildren.size() > 0) {
//noinspection ForLoopReplaceableByForEach (beacause it allocates an Iterator which is wasteful here)
for (int i = 0; i < wrapChildren.size(); i++) {
Node remainder = wrapChildren.get(i);
// if no parent, this could be the wrap node, so skip
if (wrap == remainder)
continue;
if (remainder.parentNode != null)
remainder.parentNode.removeChild(remainder);
wrap.after(remainder);
}
}
return this;
}
/**
* Removes this node from the DOM, and moves its children up into the node's parent. This has the effect of dropping
* the node but keeping its children.
* <p>
* For example, with the input html:
* </p>
* <p>{@code <div>One <span>Two <b>Three</b></span></div>}</p>
* Calling {@code element.unwrap()} on the {@code span} element will result in the html:
* <p>{@code <div>One Two <b>Three</b></div>}</p>
* and the {@code "Two "} {@link TextNode} being returned.
*
* @return the first child of this node, after the node has been unwrapped. @{code Null} if the node had no children.
* @see #remove()
* @see #wrap(String)
*/
public @Nullable Node unwrap() {
Validate.notNull(parentNode);
final List<Node> childNodes = ensureChildNodes();
Node firstChild = childNodes.size() > 0 ? childNodes.get(0) : null;
parentNode.addChildren(siblingIndex, this.childNodesAsArray());
this.remove();
return firstChild;
}
private Element getDeepChild(Element el) {
List<Element> children = el.children();
if (children.size() > 0)
return getDeepChild(children.get(0));
else
return el;
}
void nodelistChanged() {
// Element overrides this to clear its shadow children elements
}
/**
* Replace this node in the DOM with the supplied node.
* @param in the node that will will replace the existing node.
*/
public void replaceWith(Node in) {
Validate.notNull(in);
Validate.notNull(parentNode);
parentNode.replaceChild(this, in);
}
protected void setParentNode(Node parentNode) {
Validate.notNull(parentNode);
if (this.parentNode != null)
this.parentNode.removeChild(this);
this.parentNode = parentNode;
}
protected void replaceChild(Node out, Node in) {
Validate.isTrue(out.parentNode == this);
Validate.notNull(in);
if (in.parentNode != null)
in.parentNode.removeChild(in);
final int index = out.siblingIndex;
ensureChildNodes().set(index, in);
in.parentNode = this;
in.setSiblingIndex(index);
out.parentNode = null;
}
protected void removeChild(Node out) {
Validate.isTrue(out.parentNode == this);
final int index = out.siblingIndex;
ensureChildNodes().remove(index);
reindexChildren(index);
out.parentNode = null;
}
protected void addChildren(Node... children) {
//most used. short circuit addChildren(int), which hits reindex children and array copy
final List<Node> nodes = ensureChildNodes();
for (Node child: children) {
reparentChild(child);
nodes.add(child);
child.setSiblingIndex(nodes.size()-1);
}
}
protected void addChildren(int index, Node... children) {
Validate.notNull(children);
if (children.length == 0) {
return;
}
final List<Node> nodes = ensureChildNodes();
// fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace
final Node firstParent = children[0].parent();
if (firstParent != null && firstParent.childNodeSize() == children.length) {
boolean sameList = true;
final List<Node> firstParentNodes = firstParent.ensureChildNodes();
// identity check contents to see if same
int i = children.length;
while (i-- > 0) {
if (children[i] != firstParentNodes.get(i)) {
sameList = false;
break;
}
}
if (sameList) { // moving, so OK to empty firstParent and short-circuit
boolean wasEmpty = childNodeSize() == 0;
firstParent.empty();
nodes.addAll(index, Arrays.asList(children));
i = children.length;
while (i-- > 0) {
children[i].parentNode = this;
}
if (!(wasEmpty && children[0].siblingIndex == 0)) // skip reindexing if we just moved
reindexChildren(index);
return;
}
}
Validate.noNullElements(children);
for (Node child : children) {
reparentChild(child);
}
nodes.addAll(index, Arrays.asList(children));
reindexChildren(index);
}
protected void reparentChild(Node child) {
child.setParentNode(this);
}
private void reindexChildren(int start) {
if (childNodeSize() == 0) return;
final List<Node> childNodes = ensureChildNodes();
for (int i = start; i < childNodes.size(); i++) {
childNodes.get(i).setSiblingIndex(i);
}
}
/**
Retrieves this node's sibling nodes. Similar to {@link #childNodes() node.parent.childNodes()}, but does not
include this node (a node is not a sibling of itself).
@return node siblings. If the node has no parent, returns an empty list.
*/
public List<Node> siblingNodes() {
if (parentNode == null)
return Collections.emptyList();
List<Node> nodes = parentNode.ensureChildNodes();
List<Node> siblings = new ArrayList<>(nodes.size() - 1);
for (Node node: nodes)
if (node != this)
siblings.add(node);
return siblings;
}
/**
Get this node's next sibling.
@return next sibling, or @{code null} if this is the last sibling
*/
public @Nullable Node nextSibling() {
if (parentNode == null)
return null; // root
final List<Node> siblings = parentNode.ensureChildNodes();
final int index = siblingIndex+1;
if (siblings.size() > index)
return siblings.get(index);
else
return null;
}
/**
Get this node's previous sibling.
@return the previous sibling, or @{code null} if this is the first sibling
*/
public @Nullable Node previousSibling() {
if (parentNode == null)
return null; // root
if (siblingIndex > 0)
return parentNode.ensureChildNodes().get(siblingIndex-1);
else
return null;
}
/**
* Get the list index of this node in its node sibling list. E.g. if this is the first node
* sibling, returns 0.
* @return position in node sibling list
* @see org.jsoup.nodes.Element#elementSiblingIndex()
*/
public int siblingIndex() {
return siblingIndex;
}
protected void setSiblingIndex(int siblingIndex) {
this.siblingIndex = siblingIndex;
}
/**
* Perform a depth-first traversal through this node and its descendants.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this node, for chaining
*/
public Node traverse(NodeVisitor nodeVisitor) {
Validate.notNull(nodeVisitor);
NodeTraversor.traverse(nodeVisitor, this);
return this;
}
/**
* Perform a depth-first filtering through this node and its descendants.
* @param nodeFilter the filter callbacks to perform on each node
* @return this node, for chaining
*/
public Node filter(NodeFilter nodeFilter) {
Validate.notNull(nodeFilter);
NodeTraversor.filter(nodeFilter, this);
return this;
}
/**
Get the outer HTML of this node. For example, on a {@code p} element, may return {@code <p>Para</p>}.
@return outer HTML
@see Element#html()
@see Element#text()
*/
public String outerHtml() {
StringBuilder accum = StringUtil.borrowBuilder();
outerHtml(accum);
return StringUtil.releaseBuilder(accum);
}
protected void outerHtml(Appendable accum) {
NodeTraversor.traverse(new OuterHtmlVisitor(accum, NodeUtils.outputSettings(this)), this);
}
/**
Get the outer HTML of this node.
@param accum accumulator to place HTML into
@throws IOException if appending to the given accumulator fails.
*/
abstract void outerHtmlHead(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException;
abstract void outerHtmlTail(final Appendable accum, int depth, final Document.OutputSettings out) throws IOException;
/**
* Write this node and its children to the given {@link Appendable}.
*
* @param appendable the {@link Appendable} to write to.
* @return the supplied {@link Appendable}, for chaining.
*/
public <T extends Appendable> T html(T appendable) {
outerHtml(appendable);
return appendable;
}
/**
* Gets this node's outer HTML.
* @return outer HTML.
* @see #outerHtml()
*/
public String toString() {
return outerHtml();
}
protected void indent(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
accum.append('\n').append(StringUtil.padding(depth * out.indentAmount()));
}
/**
* Check if this node is the same instance of another (object identity test).
* <p>For an node value equality check, see {@link #hasSameValue(Object)}</p>
* @param o other object to compare to
* @return true if the content of this node is the same as the other
* @see Node#hasSameValue(Object)
*/
@Override
public boolean equals(@Nullable Object o) {
// implemented just so that javadoc is clear this is an identity test
return this == o;
}
/**
Provides a hashCode for this Node, based on it's object identity. Changes to the Node's content will not impact the
result.
@return an object identity based hashcode for this Node
*/
@Override
public int hashCode() {
// implemented so that javadoc and scanners are clear this is an identity test
return super.hashCode();
}
/**
* Check if this node is has the same content as another node. A node is considered the same if its name, attributes and content match the
* other node; particularly its position in the tree does not influence its similarity.
* @param o other object to compare to
* @return true if the content of this node is the same as the other
*/
public boolean hasSameValue(@Nullable Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return this.outerHtml().equals(((Node) o).outerHtml());
}
/**
* Create a stand-alone, deep copy of this node, and all of its children. The cloned node will have no siblings or
* parent node. As a stand-alone object, any changes made to the clone or any of its children will not impact the
* original node.
* <p>
* The cloned node may be adopted into another Document or node structure using {@link Element#appendChild(Node)}.
* @return a stand-alone cloned node, including clones of any children
* @see #shallowClone()
*/
@SuppressWarnings("MethodDoesntCallSuperMethod") // because it does call super.clone in doClone - analysis just isn't following
@Override
public Node clone() {
Node thisClone = doClone(null); // splits for orphan
// Queue up nodes that need their children cloned (BFS).
final LinkedList<Node> nodesToProcess = new LinkedList<>();
nodesToProcess.add(thisClone);
while (!nodesToProcess.isEmpty()) {
Node currParent = nodesToProcess.remove();
final int size = currParent.childNodeSize();
for (int i = 0; i < size; i++) {
final List<Node> childNodes = currParent.ensureChildNodes();
Node childClone = childNodes.get(i).doClone(currParent);
childNodes.set(i, childClone);
nodesToProcess.add(childClone);
}
}
return thisClone;
}
/**
* Create a stand-alone, shallow copy of this node. None of its children (if any) will be cloned, and it will have
* no parent or sibling nodes.
* @return a single independent copy of this node
* @see #clone()
*/
public Node shallowClone() {
return doClone(null);
}
/*
* Return a clone of the node using the given parent (which can be null).
* Not a deep copy of children.
*/
protected Node doClone(@Nullable Node parent) {
Node clone;
try {
clone = (Node) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
clone.parentNode = parent; // can be null, to create an orphan split
clone.siblingIndex = parent == null ? 0 : siblingIndex;
return clone;
}
private static class OuterHtmlVisitor implements NodeVisitor {
private final Appendable accum;
private final Document.OutputSettings out;
OuterHtmlVisitor(Appendable accum, Document.OutputSettings out) {
this.accum = accum;
this.out = out;
out.prepareEncoder();
}
public void head(Node node, int depth) {
try {
node.outerHtmlHead(accum, depth, out);
} catch (IOException exception) {
throw new SerializationException(exception);
}
}
public void tail(Node node, int depth) {
if (!node.nodeName().equals("#text")) { // saves a void hit.
try {
node.outerHtmlTail(accum, depth, out);
} catch (IOException exception) {
throw new SerializationException(exception);
}
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/NodeUtils.java
|
package org.jsoup.nodes;
import org.jsoup.helper.Validate;
import org.jsoup.helper.W3CDom;
import org.jsoup.parser.HtmlTreeBuilder;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.w3c.dom.NodeList;
import java.util.List;
/**
* Internal helpers for Nodes, to keep the actual node APIs relatively clean. A jsoup internal class, so don't use it as
* there is no contract API).
*/
final class NodeUtils {
/**
* Get the output setting for this node, or if this node has no document (or parent), retrieve the default output
* settings
*/
static Document.OutputSettings outputSettings(Node node) {
Document owner = node.ownerDocument();
return owner != null ? owner.outputSettings() : (new Document("")).outputSettings();
}
/**
* Get the parser that was used to make this node, or the default HTML parser if it has no parent.
*/
static Parser parser(Node node) {
Document doc = node.ownerDocument();
return doc != null && doc.parser() != null ? doc.parser() : new Parser(new HtmlTreeBuilder());
}
/**
This impl works by compiling the input xpath expression, and then evaluating it against a W3C Document converted
from the original jsoup element. The original jsoup elements are then fetched from the w3c doc user data (where we
stashed them during conversion). This process could potentially be optimized by transpiling the compiled xpath
expression to a jsoup Evaluator when there's 1:1 support, thus saving the W3C document conversion stage.
*/
static <T extends Node> List<T> selectXpath(String xpath, Element el, Class<T> nodeType) {
Validate.notEmpty(xpath);
Validate.notNull(el);
Validate.notNull(nodeType);
W3CDom w3c = new W3CDom();
org.w3c.dom.Document wDoc = w3c.fromJsoup(el);
NodeList nodeList = w3c.selectXpath(xpath, wDoc);
return w3c.sourceNodes(nodeList, nodeType);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/PseudoTextElement.java
|
package org.jsoup.nodes;
import org.jsoup.parser.Tag;
/**
* Represents a {@link TextNode} as an {@link Element}, to enable text nodes to be selected with
* the {@link org.jsoup.select.Selector} {@code :matchText} syntax.
*/
public class PseudoTextElement extends Element {
public PseudoTextElement(Tag tag, String baseUri, Attributes attributes) {
super(tag, baseUri, attributes);
}
@Override
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) {
}
@Override
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/TextNode.java
|
package org.jsoup.nodes;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import java.io.IOException;
/**
A text node.
@author Jonathan Hedley, jonathan@hedley.net */
public class TextNode extends LeafNode {
/**
Create a new TextNode representing the supplied (unencoded) text).
@param text raw text
@see #createFromEncoded(String)
*/
public TextNode(String text) {
value = text;
}
public String nodeName() {
return "#text";
}
/**
* Get the text content of this text node.
* @return Unencoded, normalised text.
* @see TextNode#getWholeText()
*/
public String text() {
return StringUtil.normaliseWhitespace(getWholeText());
}
/**
* Set the text content of this text node.
* @param text unencoded text
* @return this, for chaining
*/
public TextNode text(String text) {
coreValue(text);
return this;
}
/**
Get the (unencoded) text of this text node, including any newlines and spaces present in the original.
@return text
*/
public String getWholeText() {
return coreValue();
}
/**
Test if this text node is blank -- that is, empty or only whitespace (including newlines).
@return true if this document is empty or only whitespace, false if it contains any text content.
*/
public boolean isBlank() {
return StringUtil.isBlank(coreValue());
}
/**
* Split this text node into two nodes at the specified string offset. After splitting, this node will contain the
* original text up to the offset, and will have a new text node sibling containing the text after the offset.
* @param offset string offset point to split node at.
* @return the newly created text node containing the text after the offset.
*/
public TextNode splitText(int offset) {
final String text = coreValue();
Validate.isTrue(offset >= 0, "Split offset must be not be negative");
Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length");
String head = text.substring(0, offset);
String tail = text.substring(offset);
text(head);
TextNode tailNode = new TextNode(tail);
if (parent() != null)
parent().addChildren(siblingIndex()+1, tailNode);
return tailNode;
}
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
final boolean prettyPrint = out.prettyPrint();
if (prettyPrint && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) ))
indent(accum, depth, out);
final boolean normaliseWhite = prettyPrint && !Element.preserveWhitespace(parentNode);
final boolean stripWhite = prettyPrint && parentNode instanceof Document;
Entities.escape(accum, coreValue(), out, false, normaliseWhite, stripWhite);
}
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {}
@Override
public String toString() {
return outerHtml();
}
@Override
public TextNode clone() {
return (TextNode) super.clone();
}
/**
* Create a new TextNode from HTML encoded (aka escaped) data.
* @param encodedText Text containing encoded HTML (e.g. &lt;)
* @return TextNode containing unencoded data (e.g. <)
*/
public static TextNode createFromEncoded(String encodedText) {
String text = Entities.unescape(encodedText);
return new TextNode(text);
}
static String normaliseWhitespace(String text) {
text = StringUtil.normaliseWhitespace(text);
return text;
}
static String stripLeadingWhitespace(String text) {
return text.replaceFirst("^\\s+", "");
}
static boolean lastCharIsWhitespace(StringBuilder sb) {
return sb.length() != 0 && sb.charAt(sb.length() - 1) == ' ';
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/XmlDeclaration.java
|
package org.jsoup.nodes;
import org.jsoup.SerializationException;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import java.io.IOException;
/**
* An XML Declaration.
*/
public class XmlDeclaration extends LeafNode {
// todo this impl isn't really right, the data shouldn't be attributes, just a run of text after the name
private final boolean isProcessingInstruction; // <! if true, <? if false, declaration (and last data char should be ?)
/**
* Create a new XML declaration
* @param name of declaration
* @param isProcessingInstruction is processing instruction
*/
public XmlDeclaration(String name, boolean isProcessingInstruction) {
Validate.notNull(name);
value = name;
this.isProcessingInstruction = isProcessingInstruction;
}
public String nodeName() {
return "#declaration";
}
/**
* Get the name of this declaration.
* @return name of this declaration.
*/
public String name() {
return coreValue();
}
/**
* Get the unencoded XML declaration.
* @return XML declaration
*/
public String getWholeDeclaration() {
StringBuilder sb = StringUtil.borrowBuilder();
try {
getWholeDeclaration(sb, new Document.OutputSettings());
} catch (IOException e) {
throw new SerializationException(e);
}
return StringUtil.releaseBuilder(sb).trim();
}
private void getWholeDeclaration(Appendable accum, Document.OutputSettings out) throws IOException {
for (Attribute attribute : attributes()) {
String key = attribute.getKey();
String val = attribute.getValue();
if (!key.equals(nodeName())) { // skips coreValue (name)
accum.append(' ');
// basically like Attribute, but skip empty vals in XML
accum.append(key);
if (!val.isEmpty()) {
accum.append("=\"");
Entities.escape(accum, val, out, true, false, false);
accum.append('"');
}
}
}
}
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
accum
.append("<")
.append(isProcessingInstruction ? "!" : "?")
.append(coreValue());
getWholeDeclaration(accum, out);
accum
.append(isProcessingInstruction ? "!" : "?")
.append(">");
}
void outerHtmlTail(Appendable accum, int depth, Document.OutputSettings out) {
}
@Override
public String toString() {
return outerHtml();
}
@Override
public XmlDeclaration clone() {
return (XmlDeclaration) super.clone();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/nodes/package-info.java
|
/**
HTML document structure nodes.
*/
@NonnullByDefault
package org.jsoup.nodes;
import org.jsoup.internal.NonnullByDefault;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/CharacterReader.java
|
package org.jsoup.parser;
import org.jsoup.UncheckedIOException;
import org.jsoup.helper.Validate;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Locale;
/**
CharacterReader consumes tokens off a string. Used internally by jsoup. API subject to changes.
*/
public final class CharacterReader {
static final char EOF = (char) -1;
private static final int maxStringCacheLen = 12;
static final int maxBufferLen = 1024 * 32; // visible for testing
static final int readAheadLimit = (int) (maxBufferLen * 0.75); // visible for testing
private static final int minReadAheadLen = 1024; // the minimum mark length supported. No HTML entities can be larger than this.
private char[] charBuf;
private Reader reader;
private int bufLength;
private int bufSplitPoint;
private int bufPos;
private int readerPos;
private int bufMark = -1;
private static final int stringCacheSize = 512;
private String[] stringCache = new String[stringCacheSize]; // holds reused strings in this doc, to lessen garbage
@Nullable private ArrayList<Integer> newlinePositions = null; // optionally track the pos() position of newlines - scans during bufferUp()
private int lineNumberOffset = 1; // line numbers start at 1; += newlinePosition[indexof(pos)]
public CharacterReader(Reader input, int sz) {
Validate.notNull(input);
Validate.isTrue(input.markSupported());
reader = input;
charBuf = new char[Math.min(sz, maxBufferLen)];
bufferUp();
}
public CharacterReader(Reader input) {
this(input, maxBufferLen);
}
public CharacterReader(String input) {
this(new StringReader(input), input.length());
}
public void close() {
if (reader == null)
return;
try {
reader.close();
} catch (IOException ignored) {
} finally {
reader = null;
charBuf = null;
stringCache = null;
}
}
private boolean readFully; // if the underlying stream has been completely read, no value in further buffering
private void bufferUp() {
if (readFully || bufPos < bufSplitPoint)
return;
final int pos;
final int offset;
if (bufMark != -1) {
pos = bufMark;
offset = bufPos - bufMark;
} else {
pos = bufPos;
offset = 0;
}
try {
final long skipped = reader.skip(pos);
reader.mark(maxBufferLen);
int read = 0;
while (read <= minReadAheadLen) {
int thisRead = reader.read(charBuf, read, charBuf.length - read);
if (thisRead == -1)
readFully = true;
if (thisRead <= 0)
break;
read += thisRead;
}
reader.reset();
if (read > 0) {
Validate.isTrue(skipped == pos); // Previously asserted that there is room in buf to skip, so this will be a WTF
bufLength = read;
readerPos += pos;
bufPos = offset;
if (bufMark != -1)
bufMark = 0;
bufSplitPoint = Math.min(bufLength, readAheadLimit);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
scanBufferForNewlines(); // if enabled, we index newline positions for line number tracking
lastIcSeq = null; // cache for last containsIgnoreCase(seq)
}
/**
* Gets the current cursor position in the content.
* @return current position
*/
public int pos() {
return readerPos + bufPos;
}
/**
Enables or disables line number tracking. By default, will be <b>off</b>.Tracking line numbers improves the
legibility of parser error messages, for example. Tracking should be enabled before any content is read to be of
use.
@param track set tracking on|off
@since 1.14.3
*/
public void trackNewlines(boolean track) {
if (track && newlinePositions == null) {
newlinePositions = new ArrayList<>(maxBufferLen / 80); // rough guess of likely count
scanBufferForNewlines(); // first pass when enabled; subsequently called during bufferUp
}
else if (!track)
newlinePositions = null;
}
/**
Check if the tracking of newlines is enabled.
@return the current newline tracking state
@since 1.14.3
*/
public boolean isTrackNewlines() {
return newlinePositions != null;
}
/**
Get the current line number (that the reader has consumed to). Starts at line #1.
@return the current line number, or 1 if line tracking is not enabled.
@since 1.14.3
@see #trackNewlines(boolean)
*/
public int lineNumber() {
if (!isTrackNewlines())
return 1;
int i = lineNumIndex();
if (i == -1)
return lineNumberOffset; // first line
if (i < 0)
return Math.abs(i) + lineNumberOffset - 1;
return i + lineNumberOffset + 1;
}
/**
Get the current column number (that the reader has consumed to). Starts at column #1.
@return the current column number
@since 1.14.3
@see #trackNewlines(boolean)
*/
int columnNumber() {
if (!isTrackNewlines())
return pos() + 1;
int i = lineNumIndex();
if (i == -1)
return pos() + 1;
if (i < 0)
i = Math.abs(i) - 2;
return pos() - newlinePositions.get(i) + 1;
}
/**
Get a formatted string representing the current line and cursor positions. E.g. <code>5:10</code> indicating line
number 5 and column number 10.
@return line:col position
@since 1.14.3
@see #trackNewlines(boolean)
*/
String cursorPos() {
return lineNumber() + ":" + columnNumber();
}
private int lineNumIndex() {
if (!isTrackNewlines()) return 0;
return Collections.binarySearch(newlinePositions, pos());
}
/**
Scans the buffer for newline position, and tracks their location in newlinePositions.
*/
private void scanBufferForNewlines() {
if (!isTrackNewlines())
return;
lineNumberOffset += newlinePositions.size();
int lastPos = newlinePositions.size() > 0 ? newlinePositions.get(newlinePositions.size() -1) : -1;
newlinePositions.clear();
if (lastPos != -1) {
newlinePositions.add(lastPos); // roll the last pos to first, for cursor num after buffer
lineNumberOffset--; // as this takes a position
}
for (int i = bufPos; i < bufLength; i++) {
if (charBuf[i] == '\n')
newlinePositions.add(1 + readerPos + i);
}
}
/**
* Tests if all the content has been read.
* @return true if nothing left to read.
*/
public boolean isEmpty() {
bufferUp();
return bufPos >= bufLength;
}
private boolean isEmptyNoBufferUp() {
return bufPos >= bufLength;
}
/**
* Get the char at the current position.
* @return char
*/
public char current() {
bufferUp();
return isEmptyNoBufferUp() ? EOF : charBuf[bufPos];
}
char consume() {
bufferUp();
char val = isEmptyNoBufferUp() ? EOF : charBuf[bufPos];
bufPos++;
return val;
}
/**
Unconsume one character (bufPos--). MUST only be called directly after a consume(), and no chance of a bufferUp.
*/
void unconsume() {
if (bufPos < 1)
throw new UncheckedIOException(new IOException("WTF: No buffer left to unconsume.")); // a bug if this fires, need to trace it.
bufPos--;
}
/**
* Moves the current position by one.
*/
public void advance() {
bufPos++;
}
void mark() {
// make sure there is enough look ahead capacity
if (bufLength - bufPos < minReadAheadLen)
bufSplitPoint = 0;
bufferUp();
bufMark = bufPos;
}
void unmark() {
bufMark = -1;
}
void rewindToMark() {
if (bufMark == -1)
throw new UncheckedIOException(new IOException("Mark invalid"));
bufPos = bufMark;
unmark();
}
/**
* Returns the number of characters between the current position and the next instance of the input char
* @param c scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(char c) {
// doesn't handle scanning for surrogates
bufferUp();
for (int i = bufPos; i < bufLength; i++) {
if (c == charBuf[i])
return i - bufPos;
}
return -1;
}
/**
* Returns the number of characters between the current position and the next instance of the input sequence
*
* @param seq scan target
* @return offset between current position and next instance of target. -1 if not found.
*/
int nextIndexOf(CharSequence seq) {
bufferUp();
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = bufPos; offset < bufLength; offset++) {
// scan to first instance of startchar:
if (startChar != charBuf[offset])
while(++offset < bufLength && startChar != charBuf[offset]) { /* empty */ }
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < bufLength && last <= bufLength) {
for (int j = 1; i < last && seq.charAt(j) == charBuf[i]; i++, j++) { /* empty */ }
if (i == last) // found full sequence
return offset - bufPos;
}
}
return -1;
}
/**
* Reads characters up to the specific char.
* @param c the delimiter
* @return the chars read
*/
public String consumeTo(char c) {
int offset = nextIndexOf(c);
if (offset != -1) {
String consumed = cacheString(charBuf, stringCache, bufPos, offset);
bufPos += offset;
return consumed;
} else {
return consumeToEnd();
}
}
String consumeTo(String seq) {
int offset = nextIndexOf(seq);
if (offset != -1) {
String consumed = cacheString(charBuf, stringCache, bufPos, offset);
bufPos += offset;
return consumed;
} else if (bufLength - bufPos < seq.length()) {
// nextIndexOf() did a bufferUp(), so if the buffer is shorter than the search string, we must be at EOF
return consumeToEnd();
} else {
// the string we're looking for may be straddling a buffer boundary, so keep (length - 1) characters
// unread in case they contain the beginning of the search string
int endPos = bufLength - seq.length() + 1;
String consumed = cacheString(charBuf, stringCache, bufPos, endPos - bufPos);
bufPos = endPos;
return consumed;
}
}
/**
* Read characters until the first of any delimiters is found.
* @param chars delimiters to scan for
* @return characters read up to the matched delimiter.
*/
public String consumeToAny(final char... chars) {
bufferUp();
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
final int charLen = chars.length;
int i;
OUTER: while (pos < remaining) {
for (i = 0; i < charLen; i++) {
if (val[pos] == chars[i])
break OUTER;
}
pos++;
}
bufPos = pos;
return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeToAnySorted(final char... chars) {
bufferUp();
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
while (pos < remaining) {
if (Arrays.binarySearch(chars, val[pos]) >= 0)
break;
pos++;
}
bufPos = pos;
return bufPos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeData() {
// &, <, null
//bufferUp(); // no need to bufferUp, just called consume()
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
OUTER: while (pos < remaining) {
switch (val[pos]) {
case '&':
case '<':
case TokeniserState.nullChar:
break OUTER;
default:
pos++;
}
}
bufPos = pos;
return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeAttributeQuoted(final boolean single) {
// null, " or ', &
//bufferUp(); // no need to bufferUp, just called consume()
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
OUTER: while (pos < remaining) {
switch (val[pos]) {
case '&':
case TokeniserState.nullChar:
break OUTER;
case '\'':
if (single) break OUTER;
case '"':
if (!single) break OUTER;
default:
pos++;
}
}
bufPos = pos;
return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeRawData() {
// <, null
//bufferUp(); // no need to bufferUp, just called consume()
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
OUTER: while (pos < remaining) {
switch (val[pos]) {
case '<':
case TokeniserState.nullChar:
break OUTER;
default:
pos++;
}
}
bufPos = pos;
return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeTagName() {
// '\t', '\n', '\r', '\f', ' ', '/', '>'
// NOTE: out of spec, added '<' to fix common author bugs; does not stop and append on nullChar but eats
bufferUp();
int pos = bufPos;
final int start = pos;
final int remaining = bufLength;
final char[] val = charBuf;
OUTER: while (pos < remaining) {
switch (val[pos]) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
case '/':
case '>':
case '<':
break OUTER;
}
pos++;
}
bufPos = pos;
return pos > start ? cacheString(charBuf, stringCache, start, pos -start) : "";
}
String consumeToEnd() {
bufferUp();
String data = cacheString(charBuf, stringCache, bufPos, bufLength - bufPos);
bufPos = bufLength;
return data;
}
String consumeLetterSequence() {
bufferUp();
int start = bufPos;
while (bufPos < bufLength) {
char c = charBuf[bufPos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c))
bufPos++;
else
break;
}
return cacheString(charBuf, stringCache, start, bufPos - start);
}
String consumeLetterThenDigitSequence() {
bufferUp();
int start = bufPos;
while (bufPos < bufLength) {
char c = charBuf[bufPos];
if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c))
bufPos++;
else
break;
}
while (!isEmptyNoBufferUp()) {
char c = charBuf[bufPos];
if (c >= '0' && c <= '9')
bufPos++;
else
break;
}
return cacheString(charBuf, stringCache, start, bufPos - start);
}
String consumeHexSequence() {
bufferUp();
int start = bufPos;
while (bufPos < bufLength) {
char c = charBuf[bufPos];
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))
bufPos++;
else
break;
}
return cacheString(charBuf, stringCache, start, bufPos - start);
}
String consumeDigitSequence() {
bufferUp();
int start = bufPos;
while (bufPos < bufLength) {
char c = charBuf[bufPos];
if (c >= '0' && c <= '9')
bufPos++;
else
break;
}
return cacheString(charBuf, stringCache, start, bufPos - start);
}
boolean matches(char c) {
return !isEmpty() && charBuf[bufPos] == c;
}
boolean matches(String seq) {
bufferUp();
int scanLength = seq.length();
if (scanLength > bufLength - bufPos)
return false;
for (int offset = 0; offset < scanLength; offset++)
if (seq.charAt(offset) != charBuf[bufPos +offset])
return false;
return true;
}
boolean matchesIgnoreCase(String seq) {
bufferUp();
int scanLength = seq.length();
if (scanLength > bufLength - bufPos)
return false;
for (int offset = 0; offset < scanLength; offset++) {
char upScan = Character.toUpperCase(seq.charAt(offset));
char upTarget = Character.toUpperCase(charBuf[bufPos + offset]);
if (upScan != upTarget)
return false;
}
return true;
}
boolean matchesAny(char... seq) {
if (isEmpty())
return false;
bufferUp();
char c = charBuf[bufPos];
for (char seek : seq) {
if (seek == c)
return true;
}
return false;
}
boolean matchesAnySorted(char[] seq) {
bufferUp();
return !isEmpty() && Arrays.binarySearch(seq, charBuf[bufPos]) >= 0;
}
boolean matchesLetter() {
if (isEmpty())
return false;
char c = charBuf[bufPos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c);
}
/**
Checks if the current pos matches an ascii alpha (A-Z a-z) per https://infra.spec.whatwg.org/#ascii-alpha
@return if it matches or not
*/
boolean matchesAsciiAlpha() {
if (isEmpty())
return false;
char c = charBuf[bufPos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
boolean matchesDigit() {
if (isEmpty())
return false;
char c = charBuf[bufPos];
return (c >= '0' && c <= '9');
}
boolean matchConsume(String seq) {
bufferUp();
if (matches(seq)) {
bufPos += seq.length();
return true;
} else {
return false;
}
}
boolean matchConsumeIgnoreCase(String seq) {
if (matchesIgnoreCase(seq)) {
bufPos += seq.length();
return true;
} else {
return false;
}
}
// we maintain a cache of the previously scanned sequence, and return that if applicable on repeated scans.
// that improves the situation where there is a sequence of <p<p<p<p<p<p<p...</title> and we're bashing on the <p
// looking for the </title>. Resets in bufferUp()
@Nullable private String lastIcSeq; // scan cache
private int lastIcIndex; // nearest found indexOf
/** Used to check presence of </title>, </style> when we're in RCData and see a <xxx. Only finds consistent case. */
boolean containsIgnoreCase(String seq) {
if (seq.equals(lastIcSeq)) {
if (lastIcIndex == -1) return false;
if (lastIcIndex >= bufPos) return true;
}
lastIcSeq = seq;
String loScan = seq.toLowerCase(Locale.ENGLISH);
int lo = nextIndexOf(loScan);
if (lo > -1) {
lastIcIndex = bufPos + lo; return true;
}
String hiScan = seq.toUpperCase(Locale.ENGLISH);
int hi = nextIndexOf(hiScan);
boolean found = hi > -1;
lastIcIndex = found ? bufPos + hi : -1; // we don't care about finding the nearest, just that buf contains
return found;
}
@Override
public String toString() {
if (bufLength - bufPos < 0)
return "";
return new String(charBuf, bufPos, bufLength - bufPos);
}
/**
* Caches short strings, as a flyweight pattern, to reduce GC load. Just for this doc, to prevent leaks.
* <p />
* Simplistic, and on hash collisions just falls back to creating a new string, vs a full HashMap with Entry list.
* That saves both having to create objects as hash keys, and running through the entry list, at the expense of
* some more duplicates.
*/
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {
// limit (no cache):
if (count > maxStringCacheLen)
return new String(charBuf, start, count);
if (count < 1)
return "";
// calculate hash:
int hash = 0;
for (int i = 0; i < count; i++) {
hash = 31 * hash + charBuf[start + i];
}
// get from cache
final int index = hash & stringCacheSize - 1;
String cached = stringCache[index];
if (cached != null && rangeEquals(charBuf, start, count, cached)) // positive hit
return cached;
else {
cached = new String(charBuf, start, count);
stringCache[index] = cached; // add or replace, assuming most recently used are most likely to recur next
}
return cached;
}
/**
* Check if the value of the provided range equals the string.
*/
static boolean rangeEquals(final char[] charBuf, final int start, int count, final String cached) {
if (count == cached.length()) {
int i = start;
int j = 0;
while (count-- != 0) {
if (charBuf[i++] != cached.charAt(j++))
return false;
}
return true;
}
return false;
}
// just used for testing
boolean rangeEquals(final int start, final int count, final String cached) {
return rangeEquals(charBuf, start, count, cached);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/HtmlTreeBuilder.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.CDataNode;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import static org.jsoup.internal.StringUtil.inSorted;
import static org.jsoup.parser.HtmlTreeBuilderState.Constants.InTableFoster;
/**
* HTML Tree Builder; creates a DOM from Tokens.
*/
public class HtmlTreeBuilder extends TreeBuilder {
// tag searches. must be sorted, used in inSorted. HtmlTreeBuilderTest validates they're sorted.
static final String[] TagsSearchInScope = new String[]{"applet", "caption", "html", "marquee", "object", "table", "td", "th"};
static final String[] TagSearchList = new String[]{"ol", "ul"};
static final String[] TagSearchButton = new String[]{"button"};
static final String[] TagSearchTableScope = new String[]{"html", "table"};
static final String[] TagSearchSelectScope = new String[]{"optgroup", "option"};
static final String[] TagSearchEndTags = new String[]{"dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc"};
static final String[] TagThoroughSearchEndTags = new String[]{"caption", "colgroup", "dd", "dt", "li", "optgroup", "option", "p", "rb", "rp", "rt", "rtc", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] TagSearchSpecial = new String[]{"address", "applet", "area", "article", "aside", "base", "basefont", "bgsound",
"blockquote", "body", "br", "button", "caption", "center", "col", "colgroup", "command", "dd",
"details", "dir", "div", "dl", "dt", "embed", "fieldset", "figcaption", "figure", "footer", "form",
"frame", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "header", "hgroup", "hr", "html",
"iframe", "img", "input", "isindex", "li", "link", "listing", "marquee", "menu", "meta", "nav",
"noembed", "noframes", "noscript", "object", "ol", "p", "param", "plaintext", "pre", "script",
"section", "select", "style", "summary", "table", "tbody", "td", "textarea", "tfoot", "th", "thead",
"title", "tr", "ul", "wbr", "xmp"};
public static final int MaxScopeSearchDepth = 100; // prevents the parser bogging down in exceptionally broken pages
private HtmlTreeBuilderState state; // the current state
private HtmlTreeBuilderState originalState; // original / marked state
private boolean baseUriSetFromDoc;
private @Nullable Element headElement; // the current head element
private @Nullable FormElement formElement; // the current form element
private @Nullable Element contextElement; // fragment parse context -- could be null even if fragment parsing
private ArrayList<Element> formattingElements; // active (open) formatting elements
private ArrayList<HtmlTreeBuilderState> tmplInsertMode; // stack of Template Insertion modes
private List<String> pendingTableCharacters; // chars in table to be shifted out
private Token.EndTag emptyEnd; // reused empty end tag
private boolean framesetOk; // if ok to go into frameset
private boolean fosterInserts; // if next inserts should be fostered
private boolean fragmentParsing; // if parsing a fragment of html
ParseSettings defaultSettings() {
return ParseSettings.htmlDefault;
}
@Override
HtmlTreeBuilder newInstance() {
return new HtmlTreeBuilder();
}
@Override @ParametersAreNonnullByDefault
protected void initialiseParse(Reader input, String baseUri, Parser parser) {
super.initialiseParse(input, baseUri, parser);
// this is a bit mucky. todo - probably just create new parser objects to ensure all reset.
state = HtmlTreeBuilderState.Initial;
originalState = null;
baseUriSetFromDoc = false;
headElement = null;
formElement = null;
contextElement = null;
formattingElements = new ArrayList<>();
tmplInsertMode = new ArrayList<>();
pendingTableCharacters = new ArrayList<>();
emptyEnd = new Token.EndTag();
framesetOk = true;
fosterInserts = false;
fragmentParsing = false;
}
List<Node> parseFragment(String inputFragment, @Nullable Element context, String baseUri, Parser parser) {
// context may be null
state = HtmlTreeBuilderState.Initial;
initialiseParse(new StringReader(inputFragment), baseUri, parser);
contextElement = context;
fragmentParsing = true;
Element root = null;
if (context != null) {
if (context.ownerDocument() != null) // quirks setup:
doc.quirksMode(context.ownerDocument().quirksMode());
// initialise the tokeniser state:
String contextTag = context.normalName();
switch (contextTag) {
case "title":
case "textarea":
tokeniser.transition(TokeniserState.Rcdata);
break;
case "iframe":
case "noembed":
case "noframes":
case "style":
case "xml":
tokeniser.transition(TokeniserState.Rawtext);
break;
case "script":
tokeniser.transition(TokeniserState.ScriptData);
break;
case "noscript":
tokeniser.transition(TokeniserState.Data); // if scripting enabled, rawtext
break;
case "plaintext":
tokeniser.transition(TokeniserState.PLAINTEXT);
break;
case "template":
tokeniser.transition(TokeniserState.Data);
pushTemplateMode(HtmlTreeBuilderState.InTemplate);
break;
default:
tokeniser.transition(TokeniserState.Data);
}
root = new Element(tagFor(contextTag, settings), baseUri);
doc.appendChild(root);
stack.add(root);
resetInsertionMode();
// setup form element to nearest form on context (up ancestor chain). ensures form controls are associated
// with form correctly
Element formSearch = context;
while (formSearch != null) {
if (formSearch instanceof FormElement) {
formElement = (FormElement) formSearch;
break;
}
formSearch = formSearch.parent();
}
}
runParser();
if (context != null) {
// depending on context and the input html, content may have been added outside of the root el
// e.g. context=p, input=div, the div will have been pushed out.
List<Node> nodes = root.siblingNodes();
if (!nodes.isEmpty())
root.insertChildren(-1, nodes);
return root.childNodes();
}
else
return doc.childNodes();
}
@Override
protected boolean process(Token token) {
currentToken = token;
return this.state.process(token, this);
}
boolean process(Token token, HtmlTreeBuilderState state) {
currentToken = token;
return state.process(token, this);
}
void transition(HtmlTreeBuilderState state) {
this.state = state;
}
HtmlTreeBuilderState state() {
return state;
}
void markInsertionMode() {
originalState = state;
}
HtmlTreeBuilderState originalState() {
return originalState;
}
void framesetOk(boolean framesetOk) {
this.framesetOk = framesetOk;
}
boolean framesetOk() {
return framesetOk;
}
Document getDocument() {
return doc;
}
String getBaseUri() {
return baseUri;
}
void maybeSetBaseUri(Element base) {
if (baseUriSetFromDoc) // only listen to the first <base href> in parse
return;
String href = base.absUrl("href");
if (href.length() != 0) { // ignore <base target> etc
baseUri = href;
baseUriSetFromDoc = true;
doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base, and to update all descendants
}
}
boolean isFragmentParsing() {
return fragmentParsing;
}
void error(HtmlTreeBuilderState state) {
if (parser.getErrors().canAddError())
parser.getErrors().add(new ParseError(reader, "Unexpected %s token [%s] when in state [%s]",
currentToken.tokenType(), currentToken, state));
}
Element insert(final Token.StartTag startTag) {
// cleanup duplicate attributes:
if (startTag.hasAttributes() && !startTag.attributes.isEmpty()) {
int dupes = startTag.attributes.deduplicate(settings);
if (dupes > 0) {
error("Dropped duplicate attribute(s) in tag [%s]", startTag.normalName);
}
}
// 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(emptyEnd.reset().name(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing
return el;
}
Element el = new Element(tagFor(startTag.name(), settings), null, settings.normalizeAttributes(startTag.attributes));
insert(el);
return el;
}
Element insertStartTag(String startTagName) {
Element el = new Element(tagFor(startTagName, settings), null);
insert(el);
return el;
}
void insert(Element el) {
insertNode(el);
stack.add(el);
}
Element insertEmpty(Token.StartTag startTag) {
Tag tag = tagFor(startTag.name(), settings);
Element el = new Element(tag, null, settings.normalizeAttributes(startTag.attributes));
insertNode(el);
if (startTag.isSelfClosing()) {
if (tag.isKnownTag()) {
if (!tag.isEmpty())
tokeniser.error("Tag [%s] cannot be self closing; not a void tag", tag.normalName());
}
else // unknown tag, remember this is self closing for output
tag.setSelfClosing();
}
return el;
}
FormElement insertForm(Token.StartTag startTag, boolean onStack, boolean checkTemplateStack) {
Tag tag = tagFor(startTag.name(), settings);
FormElement el = new FormElement(tag, null, settings.normalizeAttributes(startTag.attributes));
if (checkTemplateStack) {
if(!onStack("template"))
setFormElement(el);
} else
setFormElement(el);
insertNode(el);
if (onStack)
stack.add(el);
return el;
}
void insert(Token.Comment commentToken) {
Comment comment = new Comment(commentToken.getData());
insertNode(comment);
}
void insert(Token.Character characterToken) {
final Node node;
Element el = currentElement(); // will be doc if no current element; allows for whitespace to be inserted into the doc root object (not on the stack)
final String tagName = el.normalName();
final String data = characterToken.getData();
if (characterToken.isCData())
node = new CDataNode(data);
else if (isContentForTagData(tagName))
node = new DataNode(data);
else
node = new TextNode(data);
el.appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack.
}
private void insertNode(Node node) {
// if the stack hasn't been set up yet, elements (doctype, comments) go into the doc
if (stack.isEmpty())
doc.appendChild(node);
else if (isFosterInserts() && StringUtil.inSorted(currentElement().normalName(), InTableFoster))
insertInFosterParent(node);
else
currentElement().appendChild(node);
// connect form controls to their form element
if (node instanceof Element && ((Element) node).tag().isFormListed()) {
if (formElement != null)
formElement.addElement((Element) node);
}
}
Element pop() {
int size = stack.size();
return stack.remove(size-1);
}
void push(Element element) {
stack.add(element);
}
ArrayList<Element> getStack() {
return stack;
}
boolean onStack(Element el) {
return onStack(stack, el);
}
boolean onStack(String elName) {
return getFromStack(elName) != null;
}
private static final int maxQueueDepth = 256; // an arbitrary tension point between real HTML and crafted pain
private static boolean onStack(ArrayList<Element> queue, Element element) {
final int bottom = queue.size() - 1;
final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0;
for (int pos = bottom; pos >= upper; pos--) {
Element next = queue.get(pos);
if (next == element) {
return true;
}
}
return false;
}
@Nullable
Element getFromStack(String elName) {
final int bottom = stack.size() - 1;
final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0;
for (int pos = bottom; pos >= upper; pos--) {
Element next = stack.get(pos);
if (next.normalName().equals(elName)) {
return next;
}
}
return null;
}
boolean removeFromStack(Element el) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (next == el) {
stack.remove(pos);
return true;
}
}
return false;
}
@Nullable
Element popStackToClose(String elName) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element el = stack.get(pos);
stack.remove(pos);
if (el.normalName().equals(elName))
return el;
}
return null;
}
// elnames is sorted, comes from Constants
void popStackToClose(String... elNames) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos);
if (inSorted(next.normalName(), elNames))
break;
}
}
void popStackToBefore(String elName) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (next.normalName().equals(elName)) {
break;
} else {
stack.remove(pos);
}
}
}
void clearStackToTableContext() {
clearStackToContext("table", "template");
}
void clearStackToTableBodyContext() {
clearStackToContext("tbody", "tfoot", "thead", "template");
}
void clearStackToTableRowContext() {
clearStackToContext("tr", "template");
}
private void clearStackToContext(String... nodeNames) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (StringUtil.in(next.normalName(), nodeNames) || next.normalName().equals("html"))
break;
else
stack.remove(pos);
}
}
@Nullable Element aboveOnStack(Element el) {
assert onStack(el);
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (next == el) {
return stack.get(pos-1);
}
}
return null;
}
void insertOnStackAfter(Element after, Element in) {
int i = stack.lastIndexOf(after);
Validate.isTrue(i != -1);
stack.add(i+1, in);
}
void replaceOnStack(Element out, Element in) {
replaceInQueue(stack, out, in);
}
private void replaceInQueue(ArrayList<Element> queue, Element out, Element in) {
int i = queue.lastIndexOf(out);
Validate.isTrue(i != -1);
queue.set(i, in);
}
void resetInsertionMode() {
// https://html.spec.whatwg.org/multipage/parsing.html#the-insertion-mode
boolean last = false;
final int bottom = stack.size() - 1;
final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0;
if (stack.size() == 0) { // nothing left of stack, just get to body
transition(HtmlTreeBuilderState.InBody);
}
LOOP: for (int pos = bottom; pos >= upper; pos--) {
Element node = stack.get(pos);
if (pos == upper) {
last = true;
if (fragmentParsing)
node = contextElement;
}
String name = node != null ? node.normalName() : "";
switch (name) {
case "select":
transition(HtmlTreeBuilderState.InSelect);
// todo - should loop up (with some limit) and check for table or template hits
break LOOP;
case "td":
case "th":
if (!last) {
transition(HtmlTreeBuilderState.InCell);
break LOOP;
}
break;
case "tr":
transition(HtmlTreeBuilderState.InRow);
break LOOP;
case "tbody":
case "thead":
case "tfoot":
transition(HtmlTreeBuilderState.InTableBody);
break LOOP;
case "caption":
transition(HtmlTreeBuilderState.InCaption);
break LOOP;
case "colgroup":
transition(HtmlTreeBuilderState.InColumnGroup);
break LOOP;
case "table":
transition(HtmlTreeBuilderState.InTable);
break LOOP;
case "template":
HtmlTreeBuilderState tmplState = currentTemplateMode();
Validate.notNull(tmplState, "Bug: no template insertion mode on stack!");
transition(tmplState);
break LOOP;
case "head":
if (!last) {
transition(HtmlTreeBuilderState.InHead);
break LOOP;
}
break;
case "body":
transition(HtmlTreeBuilderState.InBody);
break LOOP;
case "frameset":
transition(HtmlTreeBuilderState.InFrameset);
break LOOP;
case "html":
transition(headElement == null ? HtmlTreeBuilderState.BeforeHead : HtmlTreeBuilderState.AfterHead);
break LOOP;
}
if (last) {
transition(HtmlTreeBuilderState.InBody);
break;
}
}
}
// todo: tidy up in specific scope methods
private String[] specificScopeTarget = {null};
private boolean inSpecificScope(String targetName, String[] baseTypes, String[] extraTypes) {
specificScopeTarget[0] = targetName;
return inSpecificScope(specificScopeTarget, baseTypes, extraTypes);
}
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {
// https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope
final int bottom = stack.size() -1;
final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;
// don't walk too far up the tree
for (int pos = bottom; pos >= top; pos--) {
final String elName = stack.get(pos).normalName();
if (inSorted(elName, targetNames))
return true;
if (inSorted(elName, baseTypes))
return false;
if (extraTypes != null && inSorted(elName, extraTypes))
return false;
}
//Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes)
return false;
}
boolean inScope(String[] targetNames) {
return inSpecificScope(targetNames, TagsSearchInScope, null);
}
boolean inScope(String targetName) {
return inScope(targetName, null);
}
boolean inScope(String targetName, String[] extras) {
return inSpecificScope(targetName, TagsSearchInScope, extras);
// todo: in mathml namespace: mi, mo, mn, ms, mtext annotation-xml
// todo: in svg namespace: forignOjbect, desc, title
}
boolean inListItemScope(String targetName) {
return inScope(targetName, TagSearchList);
}
boolean inButtonScope(String targetName) {
return inScope(targetName, TagSearchButton);
}
boolean inTableScope(String targetName) {
return inSpecificScope(targetName, TagSearchTableScope, null);
}
boolean inSelectScope(String targetName) {
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element el = stack.get(pos);
String elName = el.normalName();
if (elName.equals(targetName))
return true;
if (!inSorted(elName, TagSearchSelectScope)) // all elements except
return false;
}
Validate.fail("Should not be reachable");
return false;
}
void setHeadElement(Element headElement) {
this.headElement = headElement;
}
Element getHeadElement() {
return headElement;
}
boolean isFosterInserts() {
return fosterInserts;
}
void setFosterInserts(boolean fosterInserts) {
this.fosterInserts = fosterInserts;
}
@Nullable FormElement getFormElement() {
return formElement;
}
void setFormElement(FormElement formElement) {
this.formElement = formElement;
}
void newPendingTableCharacters() {
pendingTableCharacters = new ArrayList<>();
}
List<String> getPendingTableCharacters() {
return pendingTableCharacters;
}
/**
13.2.6.3 Closing elements that have implied end tags
When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, or an rtc element, the UA must pop the current node off the stack of open elements.
If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list.
When the steps below require the UA to generate all implied end tags thoroughly, then, while the current node is a caption element, a colgroup element, a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, or a tr element, the UA must pop the current node off the stack of open elements.
@param excludeTag If a step requires the UA to generate implied end tags but lists an element to exclude from the
process, then the UA must perform the above steps as if that element was not in the above list.
*/
void generateImpliedEndTags(String excludeTag) {
while (inSorted(currentElement().normalName(), TagSearchEndTags)) {
if (excludeTag != null && currentElementIs(excludeTag))
break;
pop();
}
}
void generateImpliedEndTags() {
generateImpliedEndTags(false);
}
/**
Pops elements off the stack according to the implied end tag rules
@param thorough if we are thorough (includes table elements etc) or not
*/
void generateImpliedEndTags(boolean thorough) {
final String[] search = thorough ? TagThoroughSearchEndTags : TagSearchEndTags;
while (inSorted(currentElement().normalName(), search)) {
pop();
}
}
void closeElement(String name) {
generateImpliedEndTags(name);
if (!name.equals(currentElement().normalName())) error(state());
popStackToClose(name);
}
boolean isSpecial(Element el) {
// todo: mathml's mi, mo, mn
// todo: svg's foreigObject, desc, title
String name = el.normalName();
return inSorted(name, TagSearchSpecial);
}
Element lastFormattingElement() {
return formattingElements.size() > 0 ? formattingElements.get(formattingElements.size()-1) : null;
}
int positionOfElement(Element el){
for (int i = 0; i < formattingElements.size(); i++){
if (el == formattingElements.get(i))
return i;
}
return -1;
}
Element removeLastFormattingElement() {
int size = formattingElements.size();
if (size > 0)
return formattingElements.remove(size-1);
else
return null;
}
// active formatting elements
void pushActiveFormattingElements(Element in) {
checkActiveFormattingElements(in);
formattingElements.add(in);
}
void pushWithBookmark(Element in, int bookmark){
checkActiveFormattingElements(in);
// catch any range errors and assume bookmark is incorrect - saves a redundant range check.
try {
formattingElements.add(bookmark, in);
} catch (IndexOutOfBoundsException e) {
formattingElements.add(in);
}
}
void checkActiveFormattingElements(Element in){
int numSeen = 0;
for (int pos = formattingElements.size() -1; pos >= 0; pos--) {
Element el = formattingElements.get(pos);
if (el == null) // marker
break;
if (isSameFormattingElement(in, el))
numSeen++;
if (numSeen == 3) {
formattingElements.remove(pos);
break;
}
}
}
private boolean isSameFormattingElement(Element a, Element b) {
// same if: same namespace, tag, and attributes. Element.equals only checks tag, might in future check children
return a.normalName().equals(b.normalName()) &&
// a.namespace().equals(b.namespace()) &&
a.attributes().equals(b.attributes());
// todo: namespaces
}
void reconstructFormattingElements() {
Element last = lastFormattingElement();
if (last == null || onStack(last))
return;
Element entry = last;
int size = formattingElements.size();
int ceil = size - maxUsedFormattingElements; if (ceil <0) ceil = 0;
int pos = size - 1;
boolean skip = false;
while (true) {
if (pos == ceil) { // step 4. if none before, skip to 8
skip = true;
break;
}
entry = formattingElements.get(--pos); // step 5. one earlier than entry
if (entry == null || onStack(entry)) // step 6 - neither marker nor on stack
break; // jump to 8, else continue back to 4
}
while(true) {
if (!skip) // step 7: on later than entry
entry = formattingElements.get(++pos);
Validate.notNull(entry); // should not occur, as we break at last element
// 8. create new element from element, 9 insert into current node, onto stack
skip = false; // can only skip increment from 4.
Element newEl = insertStartTag(entry.normalName()); // todo: avoid fostering here?
// newEl.namespace(entry.namespace()); // todo: namespaces
if (entry.attributesSize() > 0)
newEl.attributes().addAll(entry.attributes());
// 10. replace entry with new entry
formattingElements.set(pos, newEl);
// 11
if (pos == size-1) // if not last entry in list, jump to 7
break;
}
}
private static final int maxUsedFormattingElements = 12; // limit how many elements get recreated
void clearFormattingElementsToLastMarker() {
while (!formattingElements.isEmpty()) {
Element el = removeLastFormattingElement();
if (el == null)
break;
}
}
void removeFromActiveFormattingElements(Element el) {
for (int pos = formattingElements.size() -1; pos >= 0; pos--) {
Element next = formattingElements.get(pos);
if (next == el) {
formattingElements.remove(pos);
break;
}
}
}
boolean isInActiveFormattingElements(Element el) {
return onStack(formattingElements, el);
}
Element getActiveFormattingElement(String nodeName) {
for (int pos = formattingElements.size() -1; pos >= 0; pos--) {
Element next = formattingElements.get(pos);
if (next == null) // scope marker
break;
else if (next.normalName().equals(nodeName))
return next;
}
return null;
}
void replaceActiveFormattingElement(Element out, Element in) {
replaceInQueue(formattingElements, out, in);
}
void insertMarkerToFormattingElements() {
formattingElements.add(null);
}
void insertInFosterParent(Node in) {
Element fosterParent;
Element lastTable = getFromStack("table");
boolean isLastTableParent = false;
if (lastTable != null) {
if (lastTable.parent() != null) {
fosterParent = lastTable.parent();
isLastTableParent = true;
} else
fosterParent = aboveOnStack(lastTable);
} else { // no table == frag
fosterParent = stack.get(0);
}
if (isLastTableParent) {
Validate.notNull(lastTable); // last table cannot be null by this point.
lastTable.before(in);
}
else
fosterParent.appendChild(in);
}
// Template Insertion Mode stack
void pushTemplateMode(HtmlTreeBuilderState state) {
tmplInsertMode.add(state);
}
@Nullable HtmlTreeBuilderState popTemplateMode() {
if (tmplInsertMode.size() > 0) {
return tmplInsertMode.remove(tmplInsertMode.size() -1);
} else {
return null;
}
}
int templateModeSize() {
return tmplInsertMode.size();
}
@Nullable HtmlTreeBuilderState currentTemplateMode() {
return (tmplInsertMode.size() > 0) ? tmplInsertMode.get(tmplInsertMode.size() -1) : null;
}
@Override
public String toString() {
return "TreeBuilder{" +
"currentToken=" + currentToken +
", state=" + state +
", currentElement=" + currentElement() +
'}';
}
protected boolean isContentForTagData(final String normalName) {
return (normalName.equals("script") || normalName.equals("style"));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/HtmlTreeBuilderState.java
|
package org.jsoup.parser;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.util.ArrayList;
import static org.jsoup.internal.StringUtil.inSorted;
import static org.jsoup.parser.HtmlTreeBuilderState.Constants.*;
/**
* The Tree Builder's current state. Each state embodies the processing for the state, and transitions to other states.
*/
enum HtmlTreeBuilderState {
Initial {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
return true; // ignore whitespace until we get the first content
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype()) {
// todo: parse error check on expected doctypes
// todo: quirk state check on doctype ids
Token.Doctype d = t.asDoctype();
DocumentType doctype = new DocumentType(
tb.settings.normalizeTag(d.getName()), d.getPublicIdentifier(), d.getSystemIdentifier());
doctype.setPubSysKey(d.getPubSysKey());
tb.getDocument().appendChild(doctype);
if (d.isForceQuirks())
tb.getDocument().quirksMode(Document.QuirksMode.quirks);
tb.transition(BeforeHtml);
} else {
// todo: check not iframe srcdoc
tb.transition(BeforeHtml);
return tb.process(t); // re-process token
}
return true;
}
},
BeforeHtml {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (isWhitespace(t)) {
tb.insert(t.asCharacter()); // out of spec - include whitespace
} else if (t.isStartTag() && t.asStartTag().normalName().equals("html")) {
tb.insert(t.asStartTag());
tb.transition(BeforeHead);
} else if (t.isEndTag() && (inSorted(t.asEndTag().normalName(), BeforeHtmlToHead))) {
return anythingElse(t, tb);
} else if (t.isEndTag()) {
tb.error(this);
return false;
} else {
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
tb.insertStartTag("html");
tb.transition(BeforeHead);
return tb.process(t);
}
},
BeforeHead {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter()); // out of spec - include whitespace
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isStartTag() && t.asStartTag().normalName().equals("html")) {
return InBody.process(t, tb); // does not transition
} else if (t.isStartTag() && t.asStartTag().normalName().equals("head")) {
Element head = tb.insert(t.asStartTag());
tb.setHeadElement(head);
tb.transition(InHead);
} else if (t.isEndTag() && (inSorted(t.asEndTag().normalName(), BeforeHtmlToHead))) {
tb.processStartTag("head");
return tb.process(t);
} else if (t.isEndTag()) {
tb.error(this);
return false;
} else {
tb.processStartTag("head");
return tb.process(t);
}
return true;
}
},
InHead {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter()); // out of spec - include whitespace
return true;
}
switch (t.type) {
case Comment:
tb.insert(t.asComment());
break;
case Doctype:
tb.error(this);
return false;
case StartTag:
Token.StartTag start = t.asStartTag();
String name = start.normalName();
if (name.equals("html")) {
return InBody.process(t, tb);
} else if (inSorted(name, InHeadEmpty)) {
Element el = tb.insertEmpty(start);
// jsoup special: update base the first time it is seen
if (name.equals("base") && el.hasAttr("href"))
tb.maybeSetBaseUri(el);
} else if (name.equals("meta")) {
tb.insertEmpty(start);
// todo: charset switches
} else if (name.equals("title")) {
handleRcData(start, tb);
} else if (inSorted(name, InHeadRaw)) {
handleRawtext(start, tb);
} else if (name.equals("noscript")) {
// else if noscript && scripting flag = true: rawtext (jsoup doesn't run script, to handle as noscript)
tb.insert(start);
tb.transition(InHeadNoscript);
} else if (name.equals("script")) {
// skips some script rules as won't execute them
tb.tokeniser.transition(TokeniserState.ScriptData);
tb.markInsertionMode();
tb.transition(Text);
tb.insert(start);
} else if (name.equals("head")) {
tb.error(this);
return false;
} else if (name.equals("template")) {
tb.insert(start);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
tb.transition(InTemplate);
tb.pushTemplateMode(InTemplate);
} else {
return anythingElse(t, tb);
}
break;
case EndTag:
Token.EndTag end = t.asEndTag();
name = end.normalName();
if (name.equals("head")) {
tb.pop();
tb.transition(AfterHead);
} else if (inSorted(name, Constants.InHeadEnd)) {
return anythingElse(t, tb);
} else if (name.equals("template")) {
if (!tb.onStack(name)) {
tb.error(this);
} else {
tb.generateImpliedEndTags(true);
if (!name.equals(tb.currentElement().normalName())) tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
tb.popTemplateMode();
tb.resetInsertionMode();
}
}
else {
tb.error(this);
return false;
}
break;
default:
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, TreeBuilder tb) {
tb.processEndTag("head");
return tb.process(t);
}
},
InHeadNoscript {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isDoctype()) {
tb.error(this);
} else if (t.isStartTag() && t.asStartTag().normalName().equals("html")) {
return tb.process(t, InBody);
} else if (t.isEndTag() && t.asEndTag().normalName().equals("noscript")) {
tb.pop();
tb.transition(InHead);
} else if (isWhitespace(t) || t.isComment() || (t.isStartTag() && inSorted(t.asStartTag().normalName(),
InHeadNoScriptHead))) {
return tb.process(t, InHead);
} else if (t.isEndTag() && t.asEndTag().normalName().equals("br")) {
return anythingElse(t, tb);
} else if ((t.isStartTag() && inSorted(t.asStartTag().normalName(), InHeadNoscriptIgnore)) || t.isEndTag()) {
tb.error(this);
return false;
} else {
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
// note that this deviates from spec, which is to pop out of noscript and reprocess in head:
// https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inheadnoscript
// allows content to be inserted as data
tb.error(this);
tb.insert(new Token.Character().data(t.toString()));
return true;
}
},
AfterHead {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter());
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype()) {
tb.error(this);
} else if (t.isStartTag()) {
Token.StartTag startTag = t.asStartTag();
String name = startTag.normalName();
if (name.equals("html")) {
return tb.process(t, InBody);
} else if (name.equals("body")) {
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InBody);
} else if (name.equals("frameset")) {
tb.insert(startTag);
tb.transition(InFrameset);
} else if (inSorted(name, InBodyStartToHead)) {
tb.error(this);
Element head = tb.getHeadElement();
tb.push(head);
tb.process(t, InHead);
tb.removeFromStack(head);
} else if (name.equals("head")) {
tb.error(this);
return false;
} else {
anythingElse(t, tb);
}
} else if (t.isEndTag()) {
String name = t.asEndTag().normalName();
if (inSorted(name, AfterHeadBody)) {
anythingElse(t, tb);
} else if (name.equals("template")) {
tb.process(t, InHead);
}
else {
tb.error(this);
return false;
}
} else {
anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
tb.processStartTag("body");
tb.framesetOk(true);
return tb.process(t);
}
},
InBody {
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 (tb.framesetOk() && isWhitespace(c)) { // don't check if whitespace if frames already closed
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:
return inBodyStartTag(t, tb);
case EndTag:
return inBodyEndTag(t, tb);
case EOF:
if (tb.templateModeSize() > 0)
return tb.process(t, InTemplate);
// todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html
// stop parsing
break;
}
return true;
}
private boolean inBodyStartTag(Token t, HtmlTreeBuilder tb) {
final Token.StartTag startTag = t.asStartTag();
final String name = startTag.normalName();
final ArrayList<Element> stack;
Element el;
switch (name) {
case "a":
if (tb.getActiveFormattingElement("a") != null) {
tb.error(this);
tb.processEndTag("a");
// still on stack?
Element remainingA = tb.getFromStack("a");
if (remainingA != null) {
tb.removeFromActiveFormattingElements(remainingA);
tb.removeFromStack(remainingA);
}
}
tb.reconstructFormattingElements();
el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
break;
case "span":
// same as final else, but short circuits lots of checks
tb.reconstructFormattingElements();
tb.insert(startTag);
break;
case "li":
tb.framesetOk(false);
stack = tb.getStack();
for (int i = stack.size() - 1; i > 0; i--) {
el = stack.get(i);
if (el.normalName().equals("li")) {
tb.processEndTag("li");
break;
}
if (tb.isSpecial(el) && !inSorted(el.normalName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
break;
case "html":
tb.error(this);
if (tb.onStack("template")) return false; // ignore
// otherwise, merge attributes onto real html (if present)
stack = tb.getStack();
if (stack.size() > 0) {
Element html = tb.getStack().get(0);
if (startTag.hasAttributes()) {
for (Attribute attribute : startTag.attributes) {
if (!html.hasAttr(attribute.getKey()))
html.attributes().put(attribute);
}
}
}
break;
case "body":
tb.error(this);
stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).normalName().equals("body")) || tb.onStack("template")) {
// only in fragment case
return false; // ignore
} else {
tb.framesetOk(false);
Element body = stack.get(1);
if (startTag.hasAttributes()) {
for (Attribute attribute : startTag.attributes) {
if (!body.hasAttr(attribute.getKey()))
body.attributes().put(attribute);
}
}
}
break;
case "frameset":
tb.error(this);
stack = tb.getStack();
if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).normalName().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.remove(stack.size() - 1);
tb.insert(startTag);
tb.transition(InFrameset);
}
break;
case "form":
if (tb.getFormElement() != null && !tb.onStack("template")) {
tb.error(this);
return false;
}
if (tb.inButtonScope("p")) {
tb.closeElement("p");
}
tb.insertForm(startTag, true, true); // won't associate to any template
break;
case "plaintext":
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out
break;
case "button":
if (tb.inButtonScope("button")) {
// close and reprocess
tb.error(this);
tb.processEndTag("button");
tb.process(startTag);
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
}
break;
case "nobr":
tb.reconstructFormattingElements();
if (tb.inScope("nobr")) {
tb.error(this);
tb.processEndTag("nobr");
tb.reconstructFormattingElements();
}
el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
break;
case "table":
if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
tb.framesetOk(false);
tb.transition(InTable);
break;
case "input":
tb.reconstructFormattingElements();
el = tb.insertEmpty(startTag);
if (!el.attr("type").equalsIgnoreCase("hidden"))
tb.framesetOk(false);
break;
case "hr":
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insertEmpty(startTag);
tb.framesetOk(false);
break;
case "image":
if (tb.getFromStack("svg") == null)
return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg
else
tb.insert(startTag);
break;
case "isindex":
// how much do we care about the early 90s?
tb.error(this);
if (tb.getFormElement() != null)
return false;
tb.processStartTag("form");
if (startTag.hasAttribute("action")) {
Element form = tb.getFormElement();
if (form != null && startTag.hasAttribute("action")) {
String action = startTag.attributes.get("action");
form.attributes().put("action", action); // always LC, so don't need to scan up for ownerdoc
}
}
tb.processStartTag("hr");
tb.processStartTag("label");
// hope you like english.
String prompt = startTag.hasAttribute("prompt") ?
startTag.attributes.get("prompt") :
"This is a searchable index. Enter search keywords: ";
tb.process(new Token.Character().data(prompt));
// input
Attributes inputAttribs = new Attributes();
if (startTag.hasAttributes()) {
for (Attribute attr : startTag.attributes) {
if (!inSorted(attr.getKey(), Constants.InBodyStartInputAttribs))
inputAttribs.put(attr);
}
}
inputAttribs.put("name", "isindex");
tb.processStartTag("input", inputAttribs);
tb.processEndTag("label");
tb.processStartTag("hr");
tb.processEndTag("form");
break;
case "textarea":
tb.insert(startTag);
if (!startTag.isSelfClosing()) {
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.framesetOk(false);
tb.transition(Text);
}
break;
case "xmp":
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.reconstructFormattingElements();
tb.framesetOk(false);
handleRawtext(startTag, tb);
break;
case "iframe":
tb.framesetOk(false);
handleRawtext(startTag, tb);
break;
case "noembed":
// also handle noscript if script enabled
handleRawtext(startTag, tb);
break;
case "select":
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.framesetOk(false);
if (startTag.selfClosing) break; // don't change states if not added to the stack
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);
break;
case "math":
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml)
tb.insert(startTag);
break;
case "svg":
tb.reconstructFormattingElements();
// todo: handle A start tag whose tag name is "svg" (xlink, svg)
tb.insert(startTag);
break;
// static final String[] Headings = new String[]{"h1", "h2", "h3", "h4", "h5", "h6"};
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
if (inSorted(tb.currentElement().normalName(), Constants.Headings)) {
tb.error(this);
tb.pop();
}
tb.insert(startTag);
break;
// static final String[] InBodyStartPreListing = new String[]{"listing", "pre"};
case "pre":
case "listing":
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
tb.reader.matchConsume("\n"); // ignore LF if next token
tb.framesetOk(false);
break;
// static final String[] DdDt = new String[]{"dd", "dt"};
case "dd":
case "dt":
tb.framesetOk(false);
stack = tb.getStack();
final int bottom = stack.size() - 1;
final int upper = bottom >= MaxStackScan ? bottom - MaxStackScan : 0;
for (int i = bottom; i >= upper; i--) {
el = stack.get(i);
if (inSorted(el.normalName(), Constants.DdDt)) {
tb.processEndTag(el.normalName());
break;
}
if (tb.isSpecial(el) && !inSorted(el.normalName(), Constants.InBodyStartLiBreakers))
break;
}
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
break;
// static final String[] InBodyStartOptions = new String[]{"optgroup", "option"};
case "optgroup":
case "option":
if (tb.currentElementIs("option"))
tb.processEndTag("option");
tb.reconstructFormattingElements();
tb.insert(startTag);
break;
// static final String[] InBodyStartRuby = new String[]{"rp", "rt"};
case "rp":
case "rt":
if (tb.inScope("ruby")) {
tb.generateImpliedEndTags();
if (!tb.currentElementIs("ruby")) {
tb.error(this);
tb.popStackToBefore("ruby"); // i.e. close up to but not include name
}
tb.insert(startTag);
}
// todo - is this right? drops rp, rt if ruby not in scope?
break;
default:
// todo - bring scan groups in if desired
if (!Tag.isKnownTag(name)) { // no special rules for custom tags
tb.insert(startTag);
} else if (inSorted(name, Constants.InBodyStartEmptyFormatters)) {
tb.reconstructFormattingElements();
tb.insertEmpty(startTag);
tb.framesetOk(false);
} else if (inSorted(name, Constants.InBodyStartPClosers)) {
if (tb.inButtonScope("p")) {
tb.processEndTag("p");
}
tb.insert(startTag);
} else if (inSorted(name, Constants.InBodyStartToHead)) {
return tb.process(t, InHead);
} else if (inSorted(name, Constants.Formatters)) {
tb.reconstructFormattingElements();
el = tb.insert(startTag);
tb.pushActiveFormattingElements(el);
} else if (inSorted(name, Constants.InBodyStartApplets)) {
tb.reconstructFormattingElements();
tb.insert(startTag);
tb.insertMarkerToFormattingElements();
tb.framesetOk(false);
} else if (inSorted(name, Constants.InBodyStartMedia)) {
tb.insertEmpty(startTag);
} else if (inSorted(name, Constants.InBodyStartDrop)) {
tb.error(this);
return false;
} else {
tb.reconstructFormattingElements();
tb.insert(startTag);
}
}
return true;
}
private static final int MaxStackScan = 24; // used for DD / DT scan, prevents runaway
private boolean inBodyEndTag(Token t, HtmlTreeBuilder tb) {
final Token.EndTag endTag = t.asEndTag();
final String name = endTag.normalName();
switch (name) {
case "template":
tb.process(t, InHead);
break;
case "sarcasm": // *sigh*
case "span":
// same as final fall through, but saves short circuit
return anyOtherEndTag(t, tb);
case "li":
if (!tb.inListItemScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
}
break;
case "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);
}
break;
case "html":
boolean notIgnored = tb.processEndTag("body");
if (notIgnored)
return tb.process(endTag);
break;
case "form":
if (!tb.onStack("template")) {
Element currentForm = tb.getFormElement();
tb.setFormElement(null);
if (currentForm == null || !tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElementIs(name))
tb.error(this);
// remove currentForm from stack. will shift anything under up.
tb.removeFromStack(currentForm);
} else { // template on stack
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElementIs(name)) tb.error(this);
tb.popStackToClose(name);
}
break;
case "p":
if (!tb.inButtonScope(name)) {
tb.error(this);
tb.processStartTag(name); // if no p to close, creates an empty <p></p>
return tb.process(endTag);
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
}
break;
case "dd":
case "dt":
if (!tb.inScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
}
break;
case "h1":
case "h2":
case "h3":
case "h4":
case "h5":
case "h6":
if (!tb.inScope(Constants.Headings)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags(name);
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(Constants.Headings);
}
break;
case "br":
tb.error(this);
tb.processStartTag("br");
return false;
default:
// todo - move rest to switch if desired
if (inSorted(name, Constants.InBodyEndAdoptionFormatters)) {
return inBodyEndTagAdoption(t, tb);
} else if (inSorted(name, Constants.InBodyEndClosers)) {
if (!tb.inScope(name)) {
// nothing to close
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
}
} else if (inSorted(name, Constants.InBodyStartApplets)) {
if (!tb.inScope("name")) {
if (!tb.inScope(name)) {
tb.error(this);
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
}
} else {
return anyOtherEndTag(t, tb);
}
}
return true;
}
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {
final String name = t.asEndTag().normalName; // case insensitive search - goal is to preserve output case, not for the parse to be case sensitive
final ArrayList<Element> stack = tb.getStack();
// deviate from spec slightly to speed when super deeply nested
Element elFromStack = tb.getFromStack(name);
if (elFromStack == null) {
tb.error(this);
return false;
}
for (int pos = stack.size() - 1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (node.normalName().equals(name)) {
tb.generateImpliedEndTags(name);
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
break;
} else {
if (tb.isSpecial(node)) {
tb.error(this);
return false;
}
}
}
return true;
}
// Adoption Agency Algorithm.
private boolean inBodyEndTagAdoption(Token t, HtmlTreeBuilder tb) {
final Token.EndTag endTag = t.asEndTag();
final String name = endTag.normalName();
final ArrayList<Element> stack = tb.getStack();
Element el;
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.normalName())) {
tb.error(this);
return false;
} else if (tb.currentElement() != formatEl)
tb.error(this);
Element furthestBlock = null;
Element commonAncestor = null;
boolean seenFormattingElement = false;
// the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents run-aways
final int stackSize = stack.size();
int bookmark = -1;
for (int si = 1; si < stackSize && si < 64; si++) {
// TODO: this no longer matches the current spec at https://html.spec.whatwg.org/#adoption-agency-algorithm and should be updated
el = stack.get(si);
if (el == formatEl) {
commonAncestor = stack.get(si - 1);
seenFormattingElement = true;
// 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.
bookmark = tb.positionOfElement(el);
} else if (seenFormattingElement && tb.isSpecial(el)) {
furthestBlock = el;
break;
}
}
if (furthestBlock == null) {
tb.popStackToClose(formatEl.normalName());
tb.removeFromActiveFormattingElements(formatEl);
return true;
}
Element node = furthestBlock;
Element lastNode = furthestBlock;
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;
} else if (node == formatEl)
break;
Element replacement = new Element(tb.tagFor(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri());
// case will follow the original node (so honours ParseSettings)
tb.replaceActiveFormattingElement(node, replacement);
tb.replaceOnStack(node, replacement);
node = replacement;
if (lastNode == furthestBlock) {
// 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...
bookmark = tb.positionOfElement(node) + 1;
}
if (lastNode.parent() != null)
lastNode.remove();
node.appendChild(lastNode);
lastNode = node;
}
if (commonAncestor != null) { // safety check, but would be an error if null
if (inSorted(commonAncestor.normalName(), 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());
adopter.appendChildren(furthestBlock.childNodes());
furthestBlock.appendChild(adopter);
tb.removeFromActiveFormattingElements(formatEl);
// insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.
tb.pushWithBookmark(adopter, bookmark);
tb.removeFromStack(formatEl);
tb.insertOnStackAfter(furthestBlock, adopter);
}
return true;
}
},
Text {
// in script, style etc. normally treated as data tags
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isCharacter()) {
tb.insert(t.asCharacter());
} else if (t.isEOF()) {
tb.error(this);
// if current node is script: already started
tb.pop();
tb.transition(tb.originalState());
return tb.process(t);
} else if (t.isEndTag()) {
// if: An end tag whose tag name is "script" -- scripting nesting level, if evaluating scripts
tb.pop();
tb.transition(tb.originalState());
}
return true;
}
},
InTable {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isCharacter() && inSorted(tb.currentElement().normalName(), InTableFoster)) {
tb.newPendingTableCharacters();
tb.markInsertionMode();
tb.transition(InTableText);
return tb.process(t);
} else if (t.isComment()) {
tb.insert(t.asComment());
return true;
} else if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isStartTag()) {
Token.StartTag startTag = t.asStartTag();
String name = startTag.normalName();
if (name.equals("caption")) {
tb.clearStackToTableContext();
tb.insertMarkerToFormattingElements();
tb.insert(startTag);
tb.transition(InCaption);
} else if (name.equals("colgroup")) {
tb.clearStackToTableContext();
tb.insert(startTag);
tb.transition(InColumnGroup);
} else if (name.equals("col")) {
tb.clearStackToTableContext();
tb.processStartTag("colgroup");
return tb.process(t);
} else if (inSorted(name, InTableToBody)) {
tb.clearStackToTableContext();
tb.insert(startTag);
tb.transition(InTableBody);
} else if (inSorted(name, InTableAddBody)) {
tb.clearStackToTableContext();
tb.processStartTag("tbody");
return tb.process(t);
} else if (name.equals("table")) {
tb.error(this);
if (!tb.inTableScope(name)) { // ignore it
return false;
} else {
tb.popStackToClose(name);
tb.resetInsertionMode();
if (tb.state() == InTable) {
// not per spec - but haven't transitioned out of table. so try something else
tb.insert(startTag);
return true;
}
return tb.process(t);
}
} else if (inSorted(name, InTableToHead)) {
return tb.process(t, InHead);
} else if (name.equals("input")) {
if (!(startTag.hasAttributes() && startTag.attributes.get("type").equalsIgnoreCase("hidden"))) {
return anythingElse(t, tb);
} else {
tb.insertEmpty(startTag);
}
} else if (name.equals("form")) {
tb.error(this);
if (tb.getFormElement() != null || tb.onStack("template"))
return false;
else {
tb.insertForm(startTag, false, false); // not added to stack. can associate to template
}
} else {
return anythingElse(t, tb);
}
return true; // todo: check if should return processed http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#parsing-main-intable
} else if (t.isEndTag()) {
Token.EndTag endTag = t.asEndTag();
String name = endTag.normalName();
if (name.equals("table")) {
if (!tb.inTableScope(name)) {
tb.error(this);
return false;
} else {
tb.popStackToClose("table");
tb.resetInsertionMode();
}
} else if (inSorted(name, InTableEndErr)) {
tb.error(this);
return false;
} else if (name.equals("template")) {
tb.process(t, InHead);
} else {
return anythingElse(t, tb);
}
return true; // todo: as above todo
} else if (t.isEOF()) {
if (tb.currentElementIs("html"))
tb.error(this);
return true; // stops parsing
}
return anythingElse(t, tb);
}
boolean anythingElse(Token t, HtmlTreeBuilder tb) {
tb.error(this);
tb.setFosterInserts(true);
tb.process(t, InBody);
tb.setFosterInserts(false);
return true;
}
},
InTableText {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.type == Token.TokenType.Character) {
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
tb.error(this);
return false;
} else {
tb.getPendingTableCharacters().add(c.getData());
}
} else {// todo - don't really like the way these table character data lists are built
if (tb.getPendingTableCharacters().size() > 0) {
for (String character : tb.getPendingTableCharacters()) {
if (!isWhitespace(character)) {
// InTable anything else section:
tb.error(this);
if (inSorted(tb.currentElement().normalName(), InTableFoster)) {
tb.setFosterInserts(true);
tb.process(new Token.Character().data(character), InBody);
tb.setFosterInserts(false);
} else {
tb.process(new Token.Character().data(character), InBody);
}
} else
tb.insert(new Token.Character().data(character));
}
tb.newPendingTableCharacters();
}
tb.transition(tb.originalState());
return tb.process(t);
}
return true;
}
},
InCaption {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isEndTag() && t.asEndTag().normalName().equals("caption")) {
Token.EndTag endTag = t.asEndTag();
String name = endTag.normalName();
if (!tb.inTableScope(name)) {
tb.error(this);
return false;
} else {
tb.generateImpliedEndTags();
if (!tb.currentElementIs("caption"))
tb.error(this);
tb.popStackToClose("caption");
tb.clearFormattingElementsToLastMarker();
tb.transition(InTable);
}
} else if ((
t.isStartTag() && inSorted(t.asStartTag().normalName(), InCellCol) ||
t.isEndTag() && t.asEndTag().normalName().equals("table"))
) {
tb.error(this);
boolean processed = tb.processEndTag("caption");
if (processed)
return tb.process(t);
} else if (t.isEndTag() && inSorted(t.asEndTag().normalName(), InCaptionIgnore)) {
tb.error(this);
return false;
} else {
return tb.process(t, InBody);
}
return true;
}
},
InColumnGroup {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter());
return true;
}
switch (t.type) {
case Comment:
tb.insert(t.asComment());
break;
case Doctype:
tb.error(this);
break;
case StartTag:
Token.StartTag startTag = t.asStartTag();
switch (startTag.normalName()) {
case "html":
return tb.process(t, InBody);
case "col":
tb.insertEmpty(startTag);
break;
case "template":
tb.process(t, InHead);
break;
default:
return anythingElse(t, tb);
}
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
String name = endTag.normalName();
switch (name) {
case "colgroup":
if (!tb.currentElementIs(name)) {
tb.error(this);
return false;
} else {
tb.pop();
tb.transition(InTable);
}
break;
case "template":
tb.process(t, InHead);
break;
default:
return anythingElse(t, tb);
}
break;
case EOF:
if (tb.currentElementIs("html"))
return true; // stop parsing; frag case
else
return anythingElse(t, tb);
default:
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
if (!tb.currentElementIs("colgroup")) {
tb.error(this);
return false;
}
tb.pop();
tb.transition(InTable);
tb.process(t);
return true;
}
},
InTableBody {
boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case StartTag:
Token.StartTag startTag = t.asStartTag();
String name = startTag.normalName();
if (name.equals("tr")) {
tb.clearStackToTableBodyContext();
tb.insert(startTag);
tb.transition(InRow);
} else if (inSorted(name, InCellNames)) {
tb.error(this);
tb.processStartTag("tr");
return tb.process(startTag);
} else if (inSorted(name, InTableBodyExit)) {
return exitTableBody(t, tb);
} else
return anythingElse(t, tb);
break;
case EndTag:
Token.EndTag endTag = t.asEndTag();
name = endTag.normalName();
if (inSorted(name, InTableEndIgnore)) {
if (!tb.inTableScope(name)) {
tb.error(this);
return false;
} else {
tb.clearStackToTableBodyContext();
tb.pop();
tb.transition(InTable);
}
} else if (name.equals("table")) {
return exitTableBody(t, tb);
} else if (inSorted(name, InTableBodyEndIgnore)) {
tb.error(this);
return false;
} else
return anythingElse(t, tb);
break;
default:
return anythingElse(t, tb);
}
return true;
}
private boolean exitTableBody(Token t, HtmlTreeBuilder tb) {
if (!(tb.inTableScope("tbody") || tb.inTableScope("thead") || tb.inScope("tfoot"))) {
// frag case
tb.error(this);
return false;
}
tb.clearStackToTableBodyContext();
tb.processEndTag(tb.currentElement().normalName()); // tbody, tfoot, thead
return tb.process(t);
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
return tb.process(t, InTable);
}
},
InRow {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isStartTag()) {
Token.StartTag startTag = t.asStartTag();
String name = startTag.normalName();
if (inSorted(name, InCellNames)) {
tb.clearStackToTableRowContext();
tb.insert(startTag);
tb.transition(InCell);
tb.insertMarkerToFormattingElements();
} else if (inSorted(name, InRowMissing)) {
return handleMissingTr(t, tb);
} else {
return anythingElse(t, tb);
}
} else if (t.isEndTag()) {
Token.EndTag endTag = t.asEndTag();
String name = endTag.normalName();
if (name.equals("tr")) {
if (!tb.inTableScope(name)) {
tb.error(this); // frag
return false;
}
tb.clearStackToTableRowContext();
tb.pop(); // tr
tb.transition(InTableBody);
} else if (name.equals("table")) {
return handleMissingTr(t, tb);
} else if (inSorted(name, InTableToBody)) {
if (!tb.inTableScope(name) || !tb.inTableScope("tr")) {
tb.error(this);
return false;
}
tb.clearStackToTableRowContext();
tb.pop(); // tr
tb.transition(InTableBody);
} else if (inSorted(name, InRowIgnore)) {
tb.error(this);
return false;
} else {
return anythingElse(t, tb);
}
} else {
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
return tb.process(t, InTable);
}
private boolean handleMissingTr(Token t, TreeBuilder tb) {
boolean processed = tb.processEndTag("tr");
if (processed)
return tb.process(t);
else
return false;
}
},
InCell {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isEndTag()) {
Token.EndTag endTag = t.asEndTag();
String name = endTag.normalName();
if (inSorted(name, Constants.InCellNames)) {
if (!tb.inTableScope(name)) {
tb.error(this);
tb.transition(InRow); // might not be in scope if empty: <td /> and processing fake end tag
return false;
}
tb.generateImpliedEndTags();
if (!tb.currentElementIs(name))
tb.error(this);
tb.popStackToClose(name);
tb.clearFormattingElementsToLastMarker();
tb.transition(InRow);
} else if (inSorted(name, Constants.InCellBody)) {
tb.error(this);
return false;
} else if (inSorted(name, Constants.InCellTable)) {
if (!tb.inTableScope(name)) {
tb.error(this);
return false;
}
closeCell(tb);
return tb.process(t);
} else {
return anythingElse(t, tb);
}
} else if (t.isStartTag() &&
inSorted(t.asStartTag().normalName(), Constants.InCellCol)) {
if (!(tb.inTableScope("td") || tb.inTableScope("th"))) {
tb.error(this);
return false;
}
closeCell(tb);
return tb.process(t);
} else {
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
return tb.process(t, InBody);
}
private void closeCell(HtmlTreeBuilder tb) {
if (tb.inTableScope("td"))
tb.processEndTag("td");
else
tb.processEndTag("th"); // only here if th or td in scope
}
},
InSelect {
boolean process(Token t, HtmlTreeBuilder tb) {
switch (t.type) {
case Character:
Token.Character c = t.asCharacter();
if (c.getData().equals(nullString)) {
tb.error(this);
return false;
} else {
tb.insert(c);
}
break;
case Comment:
tb.insert(t.asComment());
break;
case Doctype:
tb.error(this);
return false;
case StartTag:
Token.StartTag start = t.asStartTag();
String name = start.normalName();
if (name.equals("html"))
return tb.process(start, InBody);
else if (name.equals("option")) {
if (tb.currentElementIs("option"))
tb.processEndTag("option");
tb.insert(start);
} else if (name.equals("optgroup")) {
if (tb.currentElementIs("option"))
tb.processEndTag("option"); // pop option and flow to pop optgroup
if (tb.currentElementIs("optgroup"))
tb.processEndTag("optgroup");
tb.insert(start);
} else if (name.equals("select")) {
tb.error(this);
return tb.processEndTag("select");
} else if (inSorted(name, InSelectEnd)) {
tb.error(this);
if (!tb.inSelectScope("select"))
return false; // frag
tb.processEndTag("select");
return tb.process(start);
} else if (name.equals("script") || name.equals("template")) {
return tb.process(t, InHead);
} else {
return anythingElse(t, tb);
}
break;
case EndTag:
Token.EndTag end = t.asEndTag();
name = end.normalName();
switch (name) {
case "optgroup":
if (tb.currentElementIs("option") && tb.aboveOnStack(tb.currentElement()) != null && tb.aboveOnStack(tb.currentElement()).normalName().equals("optgroup"))
tb.processEndTag("option");
if (tb.currentElementIs("optgroup"))
tb.pop();
else
tb.error(this);
break;
case "option":
if (tb.currentElementIs("option"))
tb.pop();
else
tb.error(this);
break;
case "select":
if (!tb.inSelectScope(name)) {
tb.error(this);
return false;
} else {
tb.popStackToClose(name);
tb.resetInsertionMode();
}
break;
case "template":
return tb.process(t, InHead);
default:
return anythingElse(t, tb);
}
break;
case EOF:
if (!tb.currentElementIs("html"))
tb.error(this);
break;
default:
return anythingElse(t, tb);
}
return true;
}
private boolean anythingElse(Token t, HtmlTreeBuilder tb) {
tb.error(this);
return false;
}
},
InSelectInTable {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isStartTag() && inSorted(t.asStartTag().normalName(), InSelectTableEnd)) {
tb.error(this);
tb.popStackToClose("select");
tb.resetInsertionMode();
return tb.process(t);
} else if (t.isEndTag() && inSorted(t.asEndTag().normalName(), InSelectTableEnd)) {
tb.error(this);
if (tb.inTableScope(t.asEndTag().normalName())) {
tb.popStackToClose("select");
tb.resetInsertionMode();
return (tb.process(t));
} else
return false;
} else {
return tb.process(t, InSelect);
}
}
},
InTemplate {
boolean process(Token t, HtmlTreeBuilder tb) {
final String name;
switch (t.type) {
case Character:
case Comment:
case Doctype:
tb.process(t, InBody);
break;
case StartTag:
name = t.asStartTag().normalName();
if (inSorted(name, InTemplateToHead))
tb.process(t, InHead);
else if (inSorted(name, InTemplateToTable)) {
tb.popTemplateMode();
tb.pushTemplateMode(InTable);
tb.transition(InTable);
return tb.process(t);
}
else if (name.equals("col")) {
tb.popTemplateMode();
tb.pushTemplateMode(InColumnGroup);
tb.transition(InColumnGroup);
return tb.process(t);
} else if (name.equals("tr")) {
tb.popTemplateMode();
tb.pushTemplateMode(InTableBody);
tb.transition(InTableBody);
return tb.process(t);
} else if (name.equals("td") || name.equals("th")) {
tb.popTemplateMode();
tb.pushTemplateMode(InRow);
tb.transition(InRow);
return tb.process(t);
} else {
tb.popTemplateMode();
tb.pushTemplateMode(InBody);
tb.transition(InBody);
return tb.process(t);
}
break;
case EndTag:
name = t.asEndTag().normalName();
if (name.equals("template"))
tb.process(t, InHead);
else {
tb.error(this);
return false;
}
break;
case EOF:
if (!tb.onStack("template")) {// stop parsing
return true;
}
tb.error(this);
tb.popStackToClose("template");
tb.clearFormattingElementsToLastMarker();
tb.popTemplateMode();
tb.resetInsertionMode();
// spec deviation - if we did not break out of Template, stop processing, and don't worry about cleaning up ultra-deep template stacks
// limited depth because this can recurse and will blow stack if too deep
if (tb.state() != InTemplate && tb.templateModeSize() < 12)
return tb.process(t);
else return true;
}
return true;
}
},
AfterBody {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter()); // out of spec - include whitespace. spec would move into body
} else if (t.isComment()) {
tb.insert(t.asComment()); // into html node
} else if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isStartTag() && t.asStartTag().normalName().equals("html")) {
return tb.process(t, InBody);
} else if (t.isEndTag() && t.asEndTag().normalName().equals("html")) {
if (tb.isFragmentParsing()) {
tb.error(this);
return false;
} else {
tb.transition(AfterAfterBody);
}
} else if (t.isEOF()) {
// chillax! we're done
} else {
tb.error(this);
tb.transition(InBody);
return tb.process(t);
}
return true;
}
},
InFrameset {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter());
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isStartTag()) {
Token.StartTag start = t.asStartTag();
switch (start.normalName()) {
case "html":
return tb.process(start, InBody);
case "frameset":
tb.insert(start);
break;
case "frame":
tb.insertEmpty(start);
break;
case "noframes":
return tb.process(start, InHead);
default:
tb.error(this);
return false;
}
} else if (t.isEndTag() && t.asEndTag().normalName().equals("frameset")) {
if (tb.currentElementIs("html")) { // frag
tb.error(this);
return false;
} else {
tb.pop();
if (!tb.isFragmentParsing() && !tb.currentElementIs("frameset")) {
tb.transition(AfterFrameset);
}
}
} else if (t.isEOF()) {
if (!tb.currentElementIs("html")) {
tb.error(this);
return true;
}
} else {
tb.error(this);
return false;
}
return true;
}
},
AfterFrameset {
boolean process(Token t, HtmlTreeBuilder tb) {
if (isWhitespace(t)) {
tb.insert(t.asCharacter());
} else if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype()) {
tb.error(this);
return false;
} else if (t.isStartTag() && t.asStartTag().normalName().equals("html")) {
return tb.process(t, InBody);
} else if (t.isEndTag() && t.asEndTag().normalName().equals("html")) {
tb.transition(AfterAfterFrameset);
} else if (t.isStartTag() && t.asStartTag().normalName().equals("noframes")) {
return tb.process(t, InHead);
} else if (t.isEOF()) {
// cool your heels, we're complete
} else {
tb.error(this);
return false;
}
return true;
}
},
AfterAfterBody {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype() || (t.isStartTag() && t.asStartTag().normalName().equals("html"))) {
return tb.process(t, InBody);
} else if (isWhitespace(t)) {
// allows space after </html>, and put the body back on stack to allow subsequent tags if any
// todo - might be better for </body> and </html> to close them, allow trailing space, and then reparent
// that space into body if other tags get re-added. but that's overkill for now
Element html = tb.popStackToClose("html");
tb.insert(t.asCharacter());
if (html != null) {
tb.stack.add(html);
Element body = html.selectFirst("body");
if (body != null) tb.stack.add(body);
}
}else if (t.isEOF()) {
// nice work chuck
} else {
tb.error(this);
tb.transition(InBody);
return tb.process(t);
}
return true;
}
},
AfterAfterFrameset {
boolean process(Token t, HtmlTreeBuilder tb) {
if (t.isComment()) {
tb.insert(t.asComment());
} else if (t.isDoctype() || isWhitespace(t) || (t.isStartTag() && t.asStartTag().normalName().equals("html"))) {
return tb.process(t, InBody);
} else if (t.isEOF()) {
// nice work chuck
} else if (t.isStartTag() && t.asStartTag().normalName().equals("noframes")) {
return tb.process(t, InHead);
} else {
tb.error(this);
return false;
}
return true;
}
},
ForeignContent {
boolean process(Token t, HtmlTreeBuilder tb) {
return true;
// todo: implement. Also; how do we get here?
}
};
private static final String nullString = String.valueOf('\u0000');
abstract boolean process(Token t, HtmlTreeBuilder tb);
private static boolean isWhitespace(Token t) {
if (t.isCharacter()) {
String data = t.asCharacter().getData();
return StringUtil.isBlank(data);
}
return false;
}
private static boolean isWhitespace(String data) {
return StringUtil.isBlank(data);
}
private static void handleRcData(Token.StartTag startTag, HtmlTreeBuilder tb) {
tb.tokeniser.transition(TokeniserState.Rcdata);
tb.markInsertionMode();
tb.transition(Text);
tb.insert(startTag);
}
private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {
tb.tokeniser.transition(TokeniserState.Rawtext);
tb.markInsertionMode();
tb.transition(Text);
tb.insert(startTag);
}
// lists of tags to search through
static final class Constants {
static final String[] InHeadEmpty = new String[]{"base", "basefont", "bgsound", "command", "link"};
static final String[] InHeadRaw = new String[]{"noframes", "style"};
static final String[] InHeadEnd = new String[]{"body", "br", "html"};
static final String[] AfterHeadBody = new String[]{"body", "br", "html"};
static final String[] BeforeHtmlToHead = new String[]{"body", "br", "head", "html", };
static final String[] InHeadNoScriptHead = new String[]{"basefont", "bgsound", "link", "meta", "noframes", "style"};
static final String[] InBodyStartToHead = new String[]{"base", "basefont", "bgsound", "command", "link", "meta", "noframes", "script", "style", "template", "title"};
static final String[] InBodyStartPClosers = new String[]{"address", "article", "aside", "blockquote", "center", "details", "dir", "div", "dl",
"fieldset", "figcaption", "figure", "footer", "header", "hgroup", "menu", "nav", "ol",
"p", "section", "summary", "ul"};
static final String[] Headings = new String[]{"h1", "h2", "h3", "h4", "h5", "h6"};
static final String[] InBodyStartLiBreakers = new String[]{"address", "div", "p"};
static final String[] DdDt = new String[]{"dd", "dt"};
static final String[] Formatters = new String[]{"b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"};
static final String[] InBodyStartApplets = new String[]{"applet", "marquee", "object"};
static final String[] InBodyStartEmptyFormatters = new String[]{"area", "br", "embed", "img", "keygen", "wbr"};
static final String[] InBodyStartMedia = new String[]{"param", "source", "track"};
static final String[] InBodyStartInputAttribs = new String[]{"action", "name", "prompt"};
static final String[] InBodyStartDrop = new String[]{"caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] InBodyEndClosers = new String[]{"address", "article", "aside", "blockquote", "button", "center", "details", "dir", "div",
"dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "menu",
"nav", "ol", "pre", "section", "summary", "ul"};
static final String[] InBodyEndAdoptionFormatters = new String[]{"a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"};
static final String[] InBodyEndTableFosters = new String[]{"table", "tbody", "tfoot", "thead", "tr"};
static final String[] InTableToBody = new String[]{"tbody", "tfoot", "thead"};
static final String[] InTableAddBody = new String[]{"td", "th", "tr"};
static final String[] InTableToHead = new String[]{"script", "style", "template"};
static final String[] InCellNames = new String[]{"td", "th"};
static final String[] InCellBody = new String[]{"body", "caption", "col", "colgroup", "html"};
static final String[] InCellTable = new String[]{ "table", "tbody", "tfoot", "thead", "tr"};
static final String[] InCellCol = new String[]{"caption", "col", "colgroup", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] InTableEndErr = new String[]{"body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] InTableFoster = new String[]{"table", "tbody", "tfoot", "thead", "tr"};
static final String[] InTableBodyExit = new String[]{"caption", "col", "colgroup", "tbody", "tfoot", "thead"};
static final String[] InTableBodyEndIgnore = new String[]{"body", "caption", "col", "colgroup", "html", "td", "th", "tr"};
static final String[] InRowMissing = new String[]{"caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr"};
static final String[] InRowIgnore = new String[]{"body", "caption", "col", "colgroup", "html", "td", "th"};
static final String[] InSelectEnd = new String[]{"input", "keygen", "textarea"};
static final String[] InSelectTableEnd = new String[]{"caption", "table", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] InTableEndIgnore = new String[]{"tbody", "tfoot", "thead"};
static final String[] InHeadNoscriptIgnore = new String[]{"head", "noscript"};
static final String[] InCaptionIgnore = new String[]{"body", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr"};
static final String[] InTemplateToHead = new String[] {"base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"};
static final String[] InTemplateToTable = new String[] {"caption", "colgroup", "tbody", "tfoot", "thead"};
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/ParseError.java
|
package org.jsoup.parser;
/**
* A Parse Error records an error in the input HTML that occurs in either the tokenisation or the tree building phase.
*/
public class ParseError {
private int pos;
private String cursorPos;
private String errorMsg;
ParseError(CharacterReader reader, String errorMsg) {
pos = reader.pos();
cursorPos = reader.cursorPos();
this.errorMsg = errorMsg;
}
ParseError(CharacterReader reader, String errorFormat, Object... args) {
pos = reader.pos();
cursorPos = reader.cursorPos();
this.errorMsg = String.format(errorFormat, args);
}
ParseError(int pos, String errorMsg) {
this.pos = pos;
cursorPos = String.valueOf(pos);
this.errorMsg = errorMsg;
}
ParseError(int pos, String errorFormat, Object... args) {
this.pos = pos;
cursorPos = String.valueOf(pos);
this.errorMsg = String.format(errorFormat, args);
}
/**
* Retrieve the error message.
* @return the error message.
*/
public String getErrorMessage() {
return errorMsg;
}
/**
* Retrieves the offset of the error.
* @return error offset within input
*/
public int getPosition() {
return pos;
}
/**
Get the formatted line:column cursor position where the error occured.
@return line:number cursor position
*/
public String getCursorPos() {
return cursorPos;
}
@Override
public String toString() {
return "<" + cursorPos + ">: " + errorMsg;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/ParseErrorList.java
|
package org.jsoup.parser;
import java.util.ArrayList;
/**
* A container for ParseErrors.
*
* @author Jonathan Hedley
*/
public class ParseErrorList extends ArrayList<ParseError>{
private static final int INITIAL_CAPACITY = 16;
private final int initialCapacity;
private final int maxSize;
ParseErrorList(int initialCapacity, int maxSize) {
super(initialCapacity);
this.initialCapacity = initialCapacity;
this.maxSize = maxSize;
}
/**
Create a new ParseErrorList with the same settings, but no errors in the list
@param copy initial and max size details to copy
*/
ParseErrorList(ParseErrorList copy) {
this(copy.initialCapacity, copy.maxSize);
}
boolean canAddError() {
return size() < maxSize;
}
int getMaxSize() {
return maxSize;
}
public static ParseErrorList noTracking() {
return new ParseErrorList(0, 0);
}
public static ParseErrorList tracking(int maxSize) {
return new ParseErrorList(INITIAL_CAPACITY, maxSize);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/ParseSettings.java
|
package org.jsoup.parser;
import org.jsoup.nodes.Attributes;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
* Controls parser settings, to optionally preserve tag and/or attribute name case.
*/
public class ParseSettings {
/**
* HTML default settings: both tag and attribute names are lower-cased during parsing.
*/
public static final ParseSettings htmlDefault;
/**
* Preserve both tag and attribute case.
*/
public static final ParseSettings preserveCase;
static {
htmlDefault = new ParseSettings(false, false);
preserveCase = new ParseSettings(true, true);
}
private final boolean preserveTagCase;
private final boolean preserveAttributeCase;
/**
* Returns true if preserving tag name case.
*/
public boolean preserveTagCase() {
return preserveTagCase;
}
/**
* Returns true if preserving attribute case.
*/
public boolean preserveAttributeCase() {
return preserveAttributeCase;
}
/**
* Define parse settings.
* @param tag preserve tag case?
* @param attribute preserve attribute name case?
*/
public ParseSettings(boolean tag, boolean attribute) {
preserveTagCase = tag;
preserveAttributeCase = attribute;
}
ParseSettings(ParseSettings copy) {
this(copy.preserveTagCase, copy.preserveAttributeCase);
}
/**
* Normalizes a tag name according to the case preservation setting.
*/
public String normalizeTag(String name) {
name = name.trim();
if (!preserveTagCase)
name = lowerCase(name);
return name;
}
/**
* Normalizes an attribute according to the case preservation setting.
*/
public String normalizeAttribute(String name) {
name = name.trim();
if (!preserveAttributeCase)
name = lowerCase(name);
return name;
}
Attributes normalizeAttributes(Attributes attributes) {
if (attributes != null && !preserveAttributeCase) {
attributes.normalize();
}
return attributes;
}
/** Returns the normal name that a Tag will have (trimmed and lower-cased) */
static String normalName(String name) {
return lowerCase(name.trim());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/Parser.java
|
package org.jsoup.parser;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
/**
* Parses HTML into a {@link org.jsoup.nodes.Document}. Generally best to use one of the more convenient parse methods
* in {@link org.jsoup.Jsoup}.
*/
public class Parser {
private TreeBuilder treeBuilder;
private ParseErrorList errors;
private ParseSettings settings;
/**
* Create a new Parser, using the specified TreeBuilder
* @param treeBuilder TreeBuilder to use to parse input into Documents.
*/
public Parser(TreeBuilder treeBuilder) {
this.treeBuilder = treeBuilder;
settings = treeBuilder.defaultSettings();
errors = ParseErrorList.noTracking();
}
/**
Creates a new Parser as a deep copy of this; including initializing a new TreeBuilder. Allows independent (multi-threaded) use.
@return a copied parser
*/
public Parser newInstance() {
return new Parser(this);
}
private Parser(Parser copy) {
treeBuilder = copy.treeBuilder.newInstance(); // because extended
errors = new ParseErrorList(copy.errors); // only copies size, not contents
settings = new ParseSettings(copy.settings);
}
public Document parseInput(String html, String baseUri) {
return treeBuilder.parse(new StringReader(html), baseUri, this);
}
public Document parseInput(Reader inputHtml, String baseUri) {
return treeBuilder.parse(inputHtml, baseUri, this);
}
public List<Node> parseFragmentInput(String fragment, Element context, String baseUri) {
return treeBuilder.parseFragment(fragment, context, baseUri, this);
}
// gets & sets
/**
* Get the TreeBuilder currently in use.
* @return current TreeBuilder.
*/
public TreeBuilder getTreeBuilder() {
return treeBuilder;
}
/**
* Update the TreeBuilder used when parsing content.
* @param treeBuilder current TreeBuilder
* @return this, for chaining
*/
public Parser setTreeBuilder(TreeBuilder treeBuilder) {
this.treeBuilder = treeBuilder;
treeBuilder.parser = this;
return this;
}
/**
* Check if parse error tracking is enabled.
* @return current track error state.
*/
public boolean isTrackErrors() {
return errors.getMaxSize() > 0;
}
/**
* Enable or disable parse error tracking for the next parse.
* @param maxErrors the maximum number of errors to track. Set to 0 to disable.
* @return this, for chaining
*/
public Parser setTrackErrors(int maxErrors) {
errors = maxErrors > 0 ? ParseErrorList.tracking(maxErrors) : ParseErrorList.noTracking();
return this;
}
/**
* Retrieve the parse errors, if any, from the last parse.
* @return list of parse errors, up to the size of the maximum errors tracked.
* @see #setTrackErrors(int)
*/
public ParseErrorList getErrors() {
return errors;
}
public Parser settings(ParseSettings settings) {
this.settings = settings;
return this;
}
public ParseSettings settings() {
return settings;
}
/**
(An internal method, visible for Element. For HTML parse, signals that script and style text should be treated as
Data Nodes).
*/
public boolean isContentForTagData(String normalName) {
return getTreeBuilder().isContentForTagData(normalName);
}
// static parse functions below
/**
* Parse HTML into a Document.
*
* @param html HTML to parse
* @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
*
* @return parsed Document
*/
public static Document parse(String html, String baseUri) {
TreeBuilder treeBuilder = new HtmlTreeBuilder();
return treeBuilder.parse(new StringReader(html), baseUri, new Parser(treeBuilder));
}
/**
* Parse a fragment of HTML into a list of nodes. The context element, if supplied, supplies parsing context.
*
* @param fragmentHtml the fragment of HTML to parse
* @param context (optional) the element that this HTML fragment is being parsed for (i.e. for inner HTML). This
* provides stack context (for implicit element creation).
* @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
*
* @return list of nodes parsed from the input HTML. Note that the context element, if supplied, is not modified.
*/
public static List<Node> parseFragment(String fragmentHtml, Element context, String baseUri) {
HtmlTreeBuilder treeBuilder = new HtmlTreeBuilder();
return treeBuilder.parseFragment(fragmentHtml, context, baseUri, new Parser(treeBuilder));
}
/**
* Parse a fragment of HTML into a list of nodes. The context element, if supplied, supplies parsing context.
*
* @param fragmentHtml the fragment of HTML to parse
* @param context (optional) the element that this HTML fragment is being parsed for (i.e. for inner HTML). This
* provides stack context (for implicit element creation).
* @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
* @param errorList list to add errors to
*
* @return list of nodes parsed from the input HTML. Note that the context element, if supplied, is not modified.
*/
public static List<Node> parseFragment(String fragmentHtml, Element context, String baseUri, ParseErrorList errorList) {
HtmlTreeBuilder treeBuilder = new HtmlTreeBuilder();
Parser parser = new Parser(treeBuilder);
parser.errors = errorList;
return treeBuilder.parseFragment(fragmentHtml, context, baseUri, parser);
}
/**
* Parse a fragment of XML into a list of nodes.
*
* @param fragmentXml the fragment of XML to parse
* @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
* @return list of nodes parsed from the input XML.
*/
public static List<Node> parseXmlFragment(String fragmentXml, String baseUri) {
XmlTreeBuilder treeBuilder = new XmlTreeBuilder();
return treeBuilder.parseFragment(fragmentXml, baseUri, new Parser(treeBuilder));
}
/**
* Parse a fragment of HTML into the {@code body} of a Document.
*
* @param bodyHtml fragment of HTML
* @param baseUri base URI of document (i.e. original fetch location), for resolving relative URLs.
*
* @return Document, with empty head, and HTML parsed into body
*/
public static Document parseBodyFragment(String bodyHtml, String baseUri) {
Document doc = Document.createShell(baseUri);
Element body = doc.body();
List<Node> nodeList = parseFragment(bodyHtml, body, baseUri);
Node[] nodes = nodeList.toArray(new Node[0]); // the node list gets modified when re-parented
for (int i = nodes.length - 1; i > 0; i--) {
nodes[i].remove();
}
for (Node node : nodes) {
body.appendChild(node);
}
return doc;
}
/**
* Utility method to unescape HTML entities from a string
* @param string HTML escaped string
* @param inAttribute if the string is to be escaped in strict mode (as attributes are)
* @return an unescaped string
*/
public static String unescapeEntities(String string, boolean inAttribute) {
Tokeniser tokeniser = new Tokeniser(new CharacterReader(string), ParseErrorList.noTracking());
return tokeniser.unescapeEntities(inAttribute);
}
// builders
/**
* Create a new HTML parser. This parser treats input as HTML5, and enforces the creation of a normalised document,
* based on a knowledge of the semantics of the incoming tags.
* @return a new HTML parser.
*/
public static Parser htmlParser() {
return new Parser(new HtmlTreeBuilder());
}
/**
* Create a new XML parser. This parser assumes no knowledge of the incoming tags and does not treat it as HTML,
* rather creates a simple tree directly from the input.
* @return a new simple XML parser.
*/
public static Parser xmlParser() {
return new Parser(new XmlTreeBuilder());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/Tag.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.internal.Normalizer;
import java.util.HashMap;
import java.util.Map;
/**
* HTML Tag capabilities.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public class Tag implements Cloneable {
private static final Map<String, Tag> tags = new HashMap<>(); // map of known tags
private String tagName;
private String normalName; // always the lower case version of this tag, regardless of case preservation mode
private boolean isBlock = true; // block
private boolean formatAsBlock = true; // should be formatted as a block
private boolean empty = false; // can hold nothing; e.g. img
private boolean selfClosing = false; // can self close (<foo />). used for unknown tags that self close, without forcing them as empty.
private boolean preserveWhitespace = false; // for pre, textarea, script etc
private boolean formList = false; // a control that appears in forms: input, textarea, output etc
private boolean formSubmit = false; // a control that can be submitted in a form: input etc
private Tag(String tagName) {
this.tagName = tagName;
normalName = Normalizer.lowerCase(tagName);
}
/**
* Get this tag's name.
*
* @return the tag's name
*/
public String getName() {
return tagName;
}
/**
* Get this tag's normalized (lowercased) name.
* @return the tag's normal name.
*/
public String normalName() {
return normalName;
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". Case insensitive.
* @param settings used to control tag name sensitivity
* @return The tag, either defined or new generic.
*/
public static Tag valueOf(String tagName, ParseSettings settings) {
Validate.notNull(tagName);
Tag tag = tags.get(tagName);
if (tag == null) {
tagName = settings.normalizeTag(tagName); // the name we'll use
Validate.notEmpty(tagName);
String normalName = Normalizer.lowerCase(tagName); // the lower-case name to get tag settings off
tag = tags.get(normalName);
if (tag == null) {
// not defined: create default; go anywhere, do anything! (incl be inside a <p>)
tag = new Tag(tagName);
tag.isBlock = false;
} else if (settings.preserveTagCase() && !tagName.equals(normalName)) {
tag = tag.clone(); // get a new version vs the static one, so name update doesn't reset all
tag.tagName = tagName;
}
}
return tag;
}
/**
* Get a Tag by name. If not previously defined (unknown), returns a new generic tag, that can do anything.
* <p>
* Pre-defined tags (P, DIV etc) will be ==, but unknown tags are not registered and will only .equals().
* </p>
*
* @param tagName Name of tag, e.g. "p". <b>Case sensitive</b>.
* @return The tag, either defined or new generic.
*/
public static Tag valueOf(String tagName) {
return valueOf(tagName, ParseSettings.preserveCase);
}
/**
* Gets if this is a block tag.
*
* @return if block tag
*/
public boolean isBlock() {
return isBlock;
}
/**
* Gets if this tag should be formatted as a block (or as inline)
*
* @return if should be formatted as block or inline
*/
public boolean formatAsBlock() {
return formatAsBlock;
}
/**
* Gets if this tag is an inline tag.
*
* @return if this tag is an inline tag.
*/
public boolean isInline() {
return !isBlock;
}
/**
* Get if this is an empty tag
*
* @return if this is an empty tag
*/
public boolean isEmpty() {
return empty;
}
/**
* Get if this tag is self closing.
*
* @return if this tag should be output as self closing.
*/
public boolean isSelfClosing() {
return empty || selfClosing;
}
/**
* Get if this is a pre-defined tag, or was auto created on parsing.
*
* @return if a known tag
*/
public boolean isKnownTag() {
return tags.containsKey(tagName);
}
/**
* Check if this tagname is a known tag.
*
* @param tagName name of tag
* @return if known HTML tag
*/
public static boolean isKnownTag(String tagName) {
return tags.containsKey(tagName);
}
/**
* Get if this tag should preserve whitespace within child text nodes.
*
* @return if preserve whitespace
*/
public boolean preserveWhitespace() {
return preserveWhitespace;
}
/**
* Get if this tag represents a control associated with a form. E.g. input, textarea, output
* @return if associated with a form
*/
public boolean isFormListed() {
return formList;
}
/**
* Get if this tag represents an element that should be submitted with a form. E.g. input, option
* @return if submittable with a form
*/
public boolean isFormSubmittable() {
return formSubmit;
}
Tag setSelfClosing() {
selfClosing = true;
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Tag)) return false;
Tag tag = (Tag) o;
if (!tagName.equals(tag.tagName)) return false;
if (empty != tag.empty) return false;
if (formatAsBlock != tag.formatAsBlock) return false;
if (isBlock != tag.isBlock) return false;
if (preserveWhitespace != tag.preserveWhitespace) return false;
if (selfClosing != tag.selfClosing) return false;
if (formList != tag.formList) return false;
return formSubmit == tag.formSubmit;
}
@Override
public int hashCode() {
int result = tagName.hashCode();
result = 31 * result + (isBlock ? 1 : 0);
result = 31 * result + (formatAsBlock ? 1 : 0);
result = 31 * result + (empty ? 1 : 0);
result = 31 * result + (selfClosing ? 1 : 0);
result = 31 * result + (preserveWhitespace ? 1 : 0);
result = 31 * result + (formList ? 1 : 0);
result = 31 * result + (formSubmit ? 1 : 0);
return result;
}
@Override
public String toString() {
return tagName;
}
@Override
protected Tag clone() {
try {
return (Tag) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
// internal static initialisers:
// prepped from http://www.w3.org/TR/REC-html40/sgml/dtd.html and other sources
private static final String[] blockTags = {
"html", "head", "body", "frameset", "script", "noscript", "style", "meta", "link", "title", "frame",
"noframes", "section", "nav", "aside", "hgroup", "header", "footer", "p", "h1", "h2", "h3", "h4", "h5", "h6",
"ul", "ol", "pre", "div", "blockquote", "hr", "address", "figure", "figcaption", "form", "fieldset", "ins",
"del", "dl", "dt", "dd", "li", "table", "caption", "thead", "tfoot", "tbody", "colgroup", "col", "tr", "th",
"td", "video", "audio", "canvas", "details", "menu", "plaintext", "template", "article", "main",
"svg", "math", "center", "template",
"dir", "applet", "marquee", "listing" // deprecated but still known / special handling
};
private static final String[] inlineTags = {
"object", "base", "font", "tt", "i", "b", "u", "big", "small", "em", "strong", "dfn", "code", "samp", "kbd",
"var", "cite", "abbr", "time", "acronym", "mark", "ruby", "rt", "rp", "a", "img", "br", "wbr", "map", "q",
"sub", "sup", "bdo", "iframe", "embed", "span", "input", "select", "textarea", "label", "button", "optgroup",
"option", "legend", "datalist", "keygen", "output", "progress", "meter", "area", "param", "source", "track",
"summary", "command", "device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track",
"data", "bdi", "s", "strike", "nobr"
};
private static final String[] emptyTags = {
"meta", "link", "base", "frame", "img", "br", "wbr", "embed", "hr", "input", "keygen", "col", "command",
"device", "area", "basefont", "bgsound", "menuitem", "param", "source", "track"
};
// todo - rework this to format contents as inline; and update html emitter in Element. Same output, just neater.
private static final String[] formatAsInlineTags = {
"title", "a", "p", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "address", "li", "th", "td", "script", "style",
"ins", "del", "s"
};
private static final String[] preserveWhitespaceTags = {
"pre", "plaintext", "title", "textarea"
// script is not here as it is a data node, which always preserve whitespace
};
// todo: I think we just need submit tags, and can scrub listed
private static final String[] formListedTags = {
"button", "fieldset", "input", "keygen", "object", "output", "select", "textarea"
};
private static final String[] formSubmitTags = {
"input", "keygen", "object", "select", "textarea"
};
static {
// creates
for (String tagName : blockTags) {
Tag tag = new Tag(tagName);
register(tag);
}
for (String tagName : inlineTags) {
Tag tag = new Tag(tagName);
tag.isBlock = false;
tag.formatAsBlock = false;
register(tag);
}
// mods:
for (String tagName : emptyTags) {
Tag tag = tags.get(tagName);
Validate.notNull(tag);
tag.empty = true;
}
for (String tagName : formatAsInlineTags) {
Tag tag = tags.get(tagName);
Validate.notNull(tag);
tag.formatAsBlock = false;
}
for (String tagName : preserveWhitespaceTags) {
Tag tag = tags.get(tagName);
Validate.notNull(tag);
tag.preserveWhitespace = true;
}
for (String tagName : formListedTags) {
Tag tag = tags.get(tagName);
Validate.notNull(tag);
tag.formList = true;
}
for (String tagName : formSubmitTags) {
Tag tag = tags.get(tagName);
Validate.notNull(tag);
tag.formSubmit = true;
}
}
private static void register(Tag tag) {
tags.put(tag.tagName, tag);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/Token.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attributes;
import javax.annotation.Nullable;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
* Parse tokens for the Tokeniser.
*/
abstract class Token {
TokenType type;
private Token() {
}
String tokenType() {
return this.getClass().getSimpleName();
}
/**
* Reset the data represent by this token, for reuse. Prevents the need to create transfer objects for every
* piece of data, which immediately get GCed.
*/
abstract Token reset();
static void reset(StringBuilder sb) {
if (sb != null) {
sb.delete(0, sb.length());
}
}
static final class Doctype extends Token {
final StringBuilder name = new StringBuilder();
String pubSysKey = null;
final StringBuilder publicIdentifier = new StringBuilder();
final StringBuilder systemIdentifier = new StringBuilder();
boolean forceQuirks = false;
Doctype() {
type = TokenType.Doctype;
}
@Override
Token reset() {
reset(name);
pubSysKey = null;
reset(publicIdentifier);
reset(systemIdentifier);
forceQuirks = false;
return this;
}
String getName() {
return name.toString();
}
String getPubSysKey() {
return pubSysKey;
}
String getPublicIdentifier() {
return publicIdentifier.toString();
}
public String getSystemIdentifier() {
return systemIdentifier.toString();
}
public boolean isForceQuirks() {
return forceQuirks;
}
@Override
public String toString() {
return "<!doctype " + getName() + ">";
}
}
static abstract class Tag extends Token {
@Nullable protected String tagName;
@Nullable protected String normalName; // lc version of tag name, for case insensitive tree build
private final StringBuilder attrName = new StringBuilder(); // try to get attr names and vals in one shot, vs Builder
@Nullable private String attrNameS;
private boolean hasAttrName = false;
private final StringBuilder attrValue = new StringBuilder();
@Nullable private String attrValueS;
private boolean hasAttrValue = false;
private boolean hasEmptyAttrValue = false; // distinguish boolean attribute from empty string value
boolean selfClosing = false;
@Nullable Attributes attributes; // start tags get attributes on construction. End tags get attributes on first new attribute (but only for parser convenience, not used).
@Override
Tag reset() {
tagName = null;
normalName = null;
reset(attrName);
attrNameS = null;
hasAttrName = false;
reset(attrValue);
attrValueS = null;
hasEmptyAttrValue = false;
hasAttrValue = false;
selfClosing = false;
attributes = null;
return this;
}
/* Limits runaway crafted HTML from spewing attributes and getting a little sluggish in ensureCapacity.
Real-world HTML will P99 around 8 attributes, so plenty of headroom. Implemented here and not in the Attributes
object so that API users can add more if ever required. */
private static final int MaxAttributes = 512;
final void newAttribute() {
if (attributes == null)
attributes = new Attributes();
if (hasAttrName && attributes.size() < MaxAttributes) {
// the tokeniser has skipped whitespace control chars, but trimming could collapse to empty for other control codes, so verify here
String name = attrName.length() > 0 ? attrName.toString() : attrNameS;
name = name.trim();
if (name.length() > 0) {
String value;
if (hasAttrValue)
value = attrValue.length() > 0 ? attrValue.toString() : attrValueS;
else if (hasEmptyAttrValue)
value = "";
else
value = null;
// note that we add, not put. So that the first is kept, and rest are deduped, once in a context where case sensitivity is known (the appropriate tree builder).
attributes.add(name, value);
}
}
reset(attrName);
attrNameS = null;
hasAttrName = false;
reset(attrValue);
attrValueS = null;
hasAttrValue = false;
hasEmptyAttrValue = false;
}
final boolean hasAttributes() {
return attributes != null;
}
final boolean hasAttribute(String key) {
return attributes != null && attributes.hasKey(key);
}
final void finaliseTag() {
// finalises for emit
if (hasAttrName) {
newAttribute();
}
}
/** Preserves case */
final String name() { // preserves case, for input into Tag.valueOf (which may drop case)
Validate.isFalse(tagName == null || tagName.length() == 0);
return tagName;
}
/** Lower case */
final String normalName() { // lower case, used in tree building for working out where in tree it should go
return normalName;
}
final String toStringName() {
return tagName != null ? tagName : "[unset]";
}
final Tag name(String name) {
tagName = name;
normalName = ParseSettings.normalName(tagName);
return this;
}
final boolean isSelfClosing() {
return selfClosing;
}
// these appenders are rarely hit in not null state-- caused by null chars.
final void appendTagName(String append) {
// might have null chars - need to replace with null replacement character
append = append.replace(TokeniserState.nullChar, Tokeniser.replacementChar);
tagName = tagName == null ? append : tagName.concat(append);
normalName = ParseSettings.normalName(tagName);
}
final void appendTagName(char append) {
appendTagName(String.valueOf(append));
}
final void appendAttributeName(String append) {
// might have null chars because we eat in one pass - need to replace with null replacement character
append = append.replace(TokeniserState.nullChar, Tokeniser.replacementChar);
ensureAttrName();
if (attrName.length() == 0) {
attrNameS = append;
} else {
attrName.append(append);
}
}
final void appendAttributeName(char append) {
ensureAttrName();
attrName.append(append);
}
final void appendAttributeValue(String append) {
ensureAttrValue();
if (attrValue.length() == 0) {
attrValueS = append;
} else {
attrValue.append(append);
}
}
final void appendAttributeValue(char append) {
ensureAttrValue();
attrValue.append(append);
}
final void appendAttributeValue(char[] append) {
ensureAttrValue();
attrValue.append(append);
}
final void appendAttributeValue(int[] appendCodepoints) {
ensureAttrValue();
for (int codepoint : appendCodepoints) {
attrValue.appendCodePoint(codepoint);
}
}
final void setEmptyAttributeValue() {
hasEmptyAttrValue = true;
}
private void ensureAttrName() {
hasAttrName = true;
// if on second hit, we'll need to move to the builder
if (attrNameS != null) {
attrName.append(attrNameS);
attrNameS = null;
}
}
private void ensureAttrValue() {
hasAttrValue = true;
// if on second hit, we'll need to move to the builder
if (attrValueS != null) {
attrValue.append(attrValueS);
attrValueS = null;
}
}
@Override
abstract public String toString();
}
final static class StartTag extends Tag {
StartTag() {
super();
type = TokenType.StartTag;
}
@Override
Tag reset() {
super.reset();
attributes = null;
return this;
}
StartTag nameAttr(String name, Attributes attributes) {
this.tagName = name;
this.attributes = attributes;
normalName = ParseSettings.normalName(tagName);
return this;
}
@Override
public String toString() {
if (hasAttributes() && attributes.size() > 0)
return "<" + toStringName() + " " + attributes.toString() + ">";
else
return "<" + toStringName() + ">";
}
}
final static class EndTag extends Tag{
EndTag() {
super();
type = TokenType.EndTag;
}
@Override
public String toString() {
return "</" + toStringName() + ">";
}
}
final static class Comment extends Token {
private final StringBuilder data = new StringBuilder();
private String dataS; // try to get in one shot
boolean bogus = false;
@Override
Token reset() {
reset(data);
dataS = null;
bogus = false;
return this;
}
Comment() {
type = TokenType.Comment;
}
String getData() {
return dataS != null ? dataS : data.toString();
}
final Comment append(String append) {
ensureData();
if (data.length() == 0) {
dataS = append;
} else {
data.append(append);
}
return this;
}
final Comment append(char append) {
ensureData();
data.append(append);
return this;
}
private void ensureData() {
// if on second hit, we'll need to move to the builder
if (dataS != null) {
data.append(dataS);
dataS = null;
}
}
@Override
public String toString() {
return "<!--" + getData() + "-->";
}
}
static class Character extends Token {
private String data;
Character() {
super();
type = TokenType.Character;
}
@Override
Token reset() {
data = null;
return this;
}
Character data(String data) {
this.data = data;
return this;
}
String getData() {
return data;
}
@Override
public String toString() {
return getData();
}
}
final static class CData extends Character {
CData(String data) {
super();
this.data(data);
}
@Override
public String toString() {
return "<![CDATA[" + getData() + "]]>";
}
}
final static class EOF extends Token {
EOF() {
type = Token.TokenType.EOF;
}
@Override
Token reset() {
return this;
}
@Override
public String toString() {
return "";
}
}
final boolean isDoctype() {
return type == TokenType.Doctype;
}
final Doctype asDoctype() {
return (Doctype) this;
}
final boolean isStartTag() {
return type == TokenType.StartTag;
}
final StartTag asStartTag() {
return (StartTag) this;
}
final boolean isEndTag() {
return type == TokenType.EndTag;
}
final EndTag asEndTag() {
return (EndTag) this;
}
final boolean isComment() {
return type == TokenType.Comment;
}
final Comment asComment() {
return (Comment) this;
}
final boolean isCharacter() {
return type == TokenType.Character;
}
final boolean isCData() {
return this instanceof CData;
}
final Character asCharacter() {
return (Character) this;
}
final boolean isEOF() {
return type == TokenType.EOF;
}
public enum TokenType {
Doctype,
StartTag,
EndTag,
Comment,
Character, // note no CData - treated in builder as an extension of Character
EOF
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/TokenQueue.java
|
package org.jsoup.parser;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
/**
* A character queue with parsing helpers.
*
* @author Jonathan Hedley
*/
public class TokenQueue {
private String queue;
private int pos = 0;
private static final char ESC = '\\'; // escape char for chomp balanced.
/**
Create a new TokenQueue.
@param data string of data to back queue.
*/
public TokenQueue(String data) {
Validate.notNull(data);
queue = data;
}
/**
* Is the queue empty?
* @return true if no data left in queue.
*/
public boolean isEmpty() {
return remainingLength() == 0;
}
private int remainingLength() {
return queue.length() - pos;
}
/**
* Retrieves but does not remove the first character from the queue.
* @return First character, or 0 if empty.
*@deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public char peek() {
return isEmpty() ? 0 : queue.charAt(pos);
}
/**
Add a character to the start of the queue (will be the next character retrieved).
@param c character to add
@deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public void addFirst(Character c) {
addFirst(c.toString());
}
/**
Add a string to the start of the queue.
@param seq string to add.
*/
public void addFirst(String seq) {
// not very performant, but an edge case
queue = seq + queue.substring(pos);
pos = 0;
}
/**
* Tests if the next characters on the queue match the sequence. Case insensitive.
* @param seq String to check queue for.
* @return true if the next characters match.
*/
public boolean matches(String seq) {
return queue.regionMatches(true, pos, seq, 0, seq.length());
}
/**
* Case sensitive match test.
* @param seq string to case sensitively check for
* @return true if matched, false if not
* @deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public boolean matchesCS(String seq) {
return queue.startsWith(seq, pos);
}
/**
Tests if the next characters match any of the sequences. Case insensitive.
@param seq list of strings to case insensitively check for
@return true of any matched, false if none did
*/
public boolean matchesAny(String... seq) {
for (String s : seq) {
if (matches(s))
return true;
}
return false;
}
public boolean matchesAny(char... seq) {
if (isEmpty())
return false;
for (char c: seq) {
if (queue.charAt(pos) == c)
return true;
}
return false;
}
/**
@deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public boolean matchesStartTag() {
// micro opt for matching "<x"
return (remainingLength() >= 2 && queue.charAt(pos) == '<' && Character.isLetter(queue.charAt(pos+1)));
}
/**
* Tests if the queue matches the sequence (as with match), and if they do, removes the matched string from the
* queue.
* @param seq String to search for, and if found, remove from queue.
* @return true if found and removed, false if not found.
*/
public boolean matchChomp(String seq) {
if (matches(seq)) {
pos += seq.length();
return true;
} else {
return false;
}
}
/**
Tests if queue starts with a whitespace character.
@return if starts with whitespace
*/
public boolean matchesWhitespace() {
return !isEmpty() && StringUtil.isWhitespace(queue.charAt(pos));
}
/**
Test if the queue matches a word character (letter or digit).
@return if matches a word character
*/
public boolean matchesWord() {
return !isEmpty() && Character.isLetterOrDigit(queue.charAt(pos));
}
/**
* Drops the next character off the queue.
*/
public void advance() {
if (!isEmpty()) pos++;
}
/**
* Consume one character off queue.
* @return first character on queue.
*/
public char consume() {
return queue.charAt(pos++);
}
/**
* Consumes the supplied sequence of the queue. If the queue does not start with the supplied sequence, will
* throw an illegal state exception -- but you should be running match() against that condition.
<p>
Case insensitive.
* @param seq sequence to remove from head of queue.
*/
public void consume(String seq) {
if (!matches(seq))
throw new IllegalStateException("Queue did not match expected sequence");
int len = seq.length();
if (len > remainingLength())
throw new IllegalStateException("Queue not long enough to consume sequence");
pos += len;
}
/**
* Pulls a string off the queue, up to but exclusive of the match sequence, or to the queue running out.
* @param seq String to end on (and not include in return, but leave on queue). <b>Case sensitive.</b>
* @return The matched data consumed from queue.
*/
public String consumeTo(String seq) {
int offset = queue.indexOf(seq, pos);
if (offset != -1) {
String consumed = queue.substring(pos, offset);
pos += consumed.length();
return consumed;
} else {
return remainder();
}
}
public String consumeToIgnoreCase(String seq) {
int start = pos;
String first = seq.substring(0, 1);
boolean canScan = first.toLowerCase().equals(first.toUpperCase()); // if first is not cased, use index of
while (!isEmpty()) {
if (matches(seq))
break;
if (canScan) {
int skip = queue.indexOf(first, pos) - pos;
if (skip == 0) // this char is the skip char, but not match, so force advance of pos
pos++;
else if (skip < 0) // no chance of finding, grab to end
pos = queue.length();
else
pos += skip;
}
else
pos++;
}
return queue.substring(start, pos);
}
/**
Consumes to the first sequence provided, or to the end of the queue. Leaves the terminator on the queue.
@param seq any number of terminators to consume to. <b>Case insensitive.</b>
@return consumed string
*/
// todo: method name. not good that consumeTo cares for case, and consume to any doesn't. And the only use for this
// is is a case sensitive time...
public String consumeToAny(String... seq) {
int start = pos;
while (!isEmpty() && !matchesAny(seq)) {
pos++;
}
return queue.substring(start, pos);
}
/**
* Pulls a string off the queue (like consumeTo), and then pulls off the matched string (but does not return it).
* <p>
* If the queue runs out of characters before finding the seq, will return as much as it can (and queue will go
* isEmpty() == true).
* @param seq String to match up to, and not include in return, and to pull off queue. <b>Case sensitive.</b>
* @return Data matched from queue.
*/
public String chompTo(String seq) {
String data = consumeTo(seq);
matchChomp(seq);
return data;
}
public String chompToIgnoreCase(String seq) {
String data = consumeToIgnoreCase(seq); // case insensitive scan
matchChomp(seq);
return data;
}
/**
* Pulls a balanced string off the queue. E.g. if queue is "(one (two) three) four", (,) will return "one (two) three",
* and leave " four" on the queue. Unbalanced openers and closers can be quoted (with ' or ") or escaped (with \). Those escapes will be left
* in the returned string, which is suitable for regexes (where we need to preserve the escape), but unsuitable for
* contains text strings; use unescape for that.
* @param open opener
* @param close closer
* @return data matched from the queue
*/
public String chompBalanced(char open, char close) {
int start = -1;
int end = -1;
int depth = 0;
char last = 0;
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
boolean inRegexQE = false; // regex \Q .. \E escapes from Pattern.quote()
do {
if (isEmpty()) break;
char c = consume();
if (last != ESC) {
if (c == '\'' && c != open && !inDoubleQuote)
inSingleQuote = !inSingleQuote;
else if (c == '"' && c != open && !inSingleQuote)
inDoubleQuote = !inDoubleQuote;
if (inSingleQuote || inDoubleQuote || inRegexQE){
last = c;
continue;
}
if (c == open) {
depth++;
if (start == -1)
start = pos;
}
else if (c == close)
depth--;
} else if (c == 'Q') {
inRegexQE = true;
} else if (c == 'E') {
inRegexQE = false;
}
if (depth > 0 && last != 0)
end = pos; // don't include the outer match pair in the return
last = c;
} while (depth > 0);
final String out = (end >= 0) ? queue.substring(start, end) : "";
if (depth > 0) {// ran out of queue before seeing enough )
Validate.fail("Did not find balanced marker at '" + out + "'");
}
return out;
}
/**
* Unescape a \ escaped string.
* @param in backslash escaped string
* @return unescaped string
*/
public static String unescape(String in) {
StringBuilder out = StringUtil.borrowBuilder();
char last = 0;
for (char c : in.toCharArray()) {
if (c == ESC) {
if (last == ESC)
out.append(c);
}
else
out.append(c);
last = c;
}
return StringUtil.releaseBuilder(out);
}
/**
* Pulls the next run of whitespace characters of the queue.
* @return Whether consuming whitespace or not
*/
public boolean consumeWhitespace() {
boolean seen = false;
while (matchesWhitespace()) {
pos++;
seen = true;
}
return seen;
}
/**
* Retrieves the next run of word type (letter or digit) off the queue.
* @return String of word characters from queue, or empty string if none.
*/
public String consumeWord() {
int start = pos;
while (matchesWord())
pos++;
return queue.substring(start, pos);
}
/**
* Consume an tag name off the queue (word or :, _, -)
*
* @return tag name
* @deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public String consumeTagName() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny(':', '_', '-')))
pos++;
return queue.substring(start, pos);
}
/**
* Consume a CSS element selector (tag name, but | instead of : for namespaces (or *| for wildcard namespace), to not conflict with :pseudo selects).
*
* @return tag name
*/
public String consumeElementSelector() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny("*|","|", "_", "-")))
pos++;
return queue.substring(start, pos);
}
/**
Consume a CSS identifier (ID or class) off the queue (letter, digit, -, _)
http://www.w3.org/TR/CSS2/syndata.html#value-def-identifier
@return identifier
*/
public String consumeCssIdentifier() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_')))
pos++;
return queue.substring(start, pos);
}
/**
Consume an attribute key off the queue (letter, digit, -, _, :")
@return attribute key
@deprecated unused and will be removed in 1.15.x
*/
@Deprecated
public String consumeAttributeKey() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_', ':')))
pos++;
return queue.substring(start, pos);
}
/**
Consume and return whatever is left on the queue.
@return remained of queue.
*/
public String remainder() {
final String remainder = queue.substring(pos);
pos = queue.length();
return remainder;
}
@Override
public String toString() {
return queue.substring(pos);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/Tokeniser.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Entities;
import javax.annotation.Nullable;
import java.util.Arrays;
/**
* Readers the input stream into tokens.
*/
final class Tokeniser {
static final char replacementChar = '\uFFFD'; // replaces null character
private static final char[] notCharRefCharsSorted = new char[]{'\t', '\n', '\r', '\f', ' ', '<', '&'};
// Some illegal character escapes are parsed by browsers as windows-1252 instead. See issue #1034
// https://html.spec.whatwg.org/multipage/parsing.html#numeric-character-reference-end-state
static final int win1252ExtensionsStart = 0x80;
static final int[] win1252Extensions = new int[] {
// we could build this manually, but Windows-1252 is not a standard java charset so that could break on
// some platforms - this table is verified with a test
0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021,
0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F,
0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014,
0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178,
};
static {
Arrays.sort(notCharRefCharsSorted);
}
private final CharacterReader reader; // html input
private final ParseErrorList errors; // errors found while tokenising
private TokeniserState state = TokeniserState.Data; // current tokenisation state
private Token emitPending; // the token we are about to emit on next read
private boolean isEmitPending = false;
private String charsString = null; // characters pending an emit. Will fall to charsBuilder if more than one
private StringBuilder charsBuilder = new StringBuilder(1024); // buffers characters to output as one token, if more than one emit per read
StringBuilder dataBuffer = new StringBuilder(1024); // buffers data looking for </script>
Token.Tag tagPending; // tag we are building up
Token.StartTag startPending = new Token.StartTag();
Token.EndTag endPending = new Token.EndTag();
Token.Character charPending = new Token.Character();
Token.Doctype doctypePending = new Token.Doctype(); // doctype building up
Token.Comment commentPending = new Token.Comment(); // comment building up
private String lastStartTag; // the last start tag emitted, to test appropriate end tag
@Nullable private String lastStartCloseSeq; // "</" + lastStartTag, so we can quickly check for that in RCData
Tokeniser(CharacterReader reader, ParseErrorList errors) {
this.reader = reader;
this.errors = errors;
}
Token read() {
while (!isEmitPending) {
state.read(this, reader);
}
// if emit is pending, a non-character token was found: return any chars in buffer, and leave token for next read:
final StringBuilder cb = this.charsBuilder;
if (cb.length() != 0) {
String str = cb.toString();
cb.delete(0, cb.length());
charsString = null;
return charPending.data(str);
} else if (charsString != null) {
Token token = charPending.data(charsString);
charsString = null;
return token;
} else {
isEmitPending = false;
return emitPending;
}
}
void emit(Token token) {
Validate.isFalse(isEmitPending);
emitPending = token;
isEmitPending = true;
if (token.type == Token.TokenType.StartTag) {
Token.StartTag startTag = (Token.StartTag) token;
lastStartTag = startTag.tagName;
lastStartCloseSeq = null; // only lazy inits
} else if (token.type == Token.TokenType.EndTag) {
Token.EndTag endTag = (Token.EndTag) token;
if (endTag.hasAttributes())
error("Attributes incorrectly present on end tag [/%s]", endTag.normalName());
}
}
void emit(final String str) {
// buffer strings up until last string token found, to emit only one token for a run of character refs etc.
// does not set isEmitPending; read checks that
if (charsString == null) {
charsString = str;
}
else {
if (charsBuilder.length() == 0) { // switching to string builder as more than one emit before read
charsBuilder.append(charsString);
}
charsBuilder.append(str);
}
}
// variations to limit need to create temp strings
void emit(final StringBuilder str) {
if (charsString == null) {
charsString = str.toString();
}
else {
if (charsBuilder.length() == 0) {
charsBuilder.append(charsString);
}
charsBuilder.append(str);
}
}
void emit(char c) {
if (charsString == null) {
charsString = String.valueOf(c);
}
else {
if (charsBuilder.length() == 0) {
charsBuilder.append(charsString);
}
charsBuilder.append(c);
}
}
void emit(char[] chars) {
emit(String.valueOf(chars));
}
void emit(int[] codepoints) {
emit(new String(codepoints, 0, codepoints.length));
}
TokeniserState getState() {
return state;
}
void transition(TokeniserState state) {
this.state = state;
}
void advanceTransition(TokeniserState state) {
reader.advance();
this.state = state;
}
final private int[] codepointHolder = new int[1]; // holder to not have to keep creating arrays
final private int[] multipointHolder = new int[2];
@Nullable int[] consumeCharacterReference(Character additionalAllowedCharacter, boolean inAttribute) {
if (reader.isEmpty())
return null;
if (additionalAllowedCharacter != null && additionalAllowedCharacter == reader.current())
return null;
if (reader.matchesAnySorted(notCharRefCharsSorted))
return null;
final int[] codeRef = codepointHolder;
reader.mark();
if (reader.matchConsume("#")) { // numbered
boolean isHexMode = reader.matchConsumeIgnoreCase("X");
String numRef = isHexMode ? reader.consumeHexSequence() : reader.consumeDigitSequence();
if (numRef.length() == 0) { // didn't match anything
characterReferenceError("numeric reference with no numerals");
reader.rewindToMark();
return null;
}
reader.unmark();
if (!reader.matchConsume(";"))
characterReferenceError("missing semicolon on [&#%s]", numRef); // missing semi
int charval = -1;
try {
int base = isHexMode ? 16 : 10;
charval = Integer.valueOf(numRef, base);
} catch (NumberFormatException ignored) {
} // skip
if (charval == -1 || (charval >= 0xD800 && charval <= 0xDFFF) || charval > 0x10FFFF) {
characterReferenceError("character [%s] outside of valid range", charval);
codeRef[0] = replacementChar;
} else {
// fix illegal unicode characters to match browser behavior
if (charval >= win1252ExtensionsStart && charval < win1252ExtensionsStart + win1252Extensions.length) {
characterReferenceError("character [%s] is not a valid unicode code point", charval);
charval = win1252Extensions[charval - win1252ExtensionsStart];
}
// todo: implement number replacement table
// todo: check for extra illegal unicode points as parse errors
codeRef[0] = charval;
}
return codeRef;
} else { // named
// get as many letters as possible, and look for matching entities.
String nameRef = reader.consumeLetterThenDigitSequence();
boolean looksLegit = reader.matches(';');
// found if a base named entity without a ;, or an extended entity with the ;.
boolean found = (Entities.isBaseNamedEntity(nameRef) || (Entities.isNamedEntity(nameRef) && looksLegit));
if (!found) {
reader.rewindToMark();
if (looksLegit) // named with semicolon
characterReferenceError("invalid named reference [%s]", nameRef);
return null;
}
if (inAttribute && (reader.matchesLetter() || reader.matchesDigit() || reader.matchesAny('=', '-', '_'))) {
// don't want that to match
reader.rewindToMark();
return null;
}
reader.unmark();
if (!reader.matchConsume(";"))
characterReferenceError("missing semicolon on [&%s]", nameRef); // missing semi
int numChars = Entities.codepointsForName(nameRef, multipointHolder);
if (numChars == 1) {
codeRef[0] = multipointHolder[0];
return codeRef;
} else if (numChars ==2) {
return multipointHolder;
} else {
Validate.fail("Unexpected characters returned for " + nameRef);
return multipointHolder;
}
}
}
Token.Tag createTagPending(boolean start) {
tagPending = start ? startPending.reset() : endPending.reset();
return tagPending;
}
void emitTagPending() {
tagPending.finaliseTag();
emit(tagPending);
}
void createCommentPending() {
commentPending.reset();
}
void emitCommentPending() {
emit(commentPending);
}
void createBogusCommentPending() {
commentPending.reset();
commentPending.bogus = true;
}
void createDoctypePending() {
doctypePending.reset();
}
void emitDoctypePending() {
emit(doctypePending);
}
void createTempBuffer() {
Token.reset(dataBuffer);
}
boolean isAppropriateEndTagToken() {
return lastStartTag != null && tagPending.name().equalsIgnoreCase(lastStartTag);
}
String appropriateEndTagName() {
return lastStartTag; // could be null
}
/** Returns the closer sequence {@code </lastStart} */
String appropriateEndTagSeq() {
if (lastStartCloseSeq == null) // reset on start tag emit
lastStartCloseSeq = "</" + lastStartTag;
return lastStartCloseSeq;
}
void error(TokeniserState state) {
if (errors.canAddError())
errors.add(new ParseError(reader, "Unexpected character '%s' in input state [%s]", reader.current(), state));
}
void eofError(TokeniserState state) {
if (errors.canAddError())
errors.add(new ParseError(reader, "Unexpectedly reached end of file (EOF) in input state [%s]", state));
}
private void characterReferenceError(String message, Object... args) {
if (errors.canAddError())
errors.add(new ParseError(reader, String.format("Invalid character reference: " + message, args)));
}
void error(String errorMsg) {
if (errors.canAddError())
errors.add(new ParseError(reader, errorMsg));
}
void error(String errorMsg, Object... args) {
if (errors.canAddError())
errors.add(new ParseError(reader, errorMsg, args));
}
boolean currentNodeInHtmlNS() {
// todo: implement namespaces correctly
return true;
// Element currentNode = currentNode();
// return currentNode != null && currentNode.namespace().equals("HTML");
}
/**
* Utility method to consume reader and unescape entities found within.
* @param inAttribute if the text to be unescaped is in an attribute
* @return unescaped string from reader
*/
String unescapeEntities(boolean inAttribute) {
StringBuilder builder = StringUtil.borrowBuilder();
while (!reader.isEmpty()) {
builder.append(reader.consumeTo('&'));
if (reader.matches('&')) {
reader.consume();
int[] c = consumeCharacterReference(null, inAttribute);
if (c == null || c.length==0)
builder.append('&');
else {
builder.appendCodePoint(c[0]);
if (c.length == 2)
builder.appendCodePoint(c[1]);
}
}
}
return StringUtil.releaseBuilder(builder);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/TokeniserState.java
|
package org.jsoup.parser;
import org.jsoup.nodes.DocumentType;
/**
* States and transition activations for the Tokeniser.
*/
enum TokeniserState {
Data {
// in data state, gather characters until a character reference or tag is found
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInData);
break;
case '<':
t.advanceTransition(TagOpen);
break;
case nullChar:
t.error(this); // NOT replacement character (oddly?)
t.emit(r.consume());
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
},
CharacterReferenceInData {
// from & in data
void read(Tokeniser t, CharacterReader r) {
readCharRef(t, Data);
}
},
Rcdata {
/// handles data in title, textarea etc
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '&':
t.advanceTransition(CharacterReferenceInRcdata);
break;
case '<':
t.advanceTransition(RcdataLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeData();
t.emit(data);
break;
}
}
},
CharacterReferenceInRcdata {
void read(Tokeniser t, CharacterReader r) {
readCharRef(t, Rcdata);
}
},
Rawtext {
void read(Tokeniser t, CharacterReader r) {
readRawData(t, r, this, RawtextLessthanSign);
}
},
ScriptData {
void read(Tokeniser t, CharacterReader r) {
readRawData(t, r, this, ScriptDataLessthanSign);
}
},
PLAINTEXT {
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeTo(nullChar);
t.emit(data);
break;
}
}
},
TagOpen {
// from < in data
void read(Tokeniser t, CharacterReader r) {
switch (r.current()) {
case '!':
t.advanceTransition(MarkupDeclarationOpen);
break;
case '/':
t.advanceTransition(EndTagOpen);
break;
case '?':
t.createBogusCommentPending();
t.transition(BogusComment);
break;
default:
if (r.matchesAsciiAlpha()) {
t.createTagPending(true);
t.transition(TagName);
} else {
t.error(this);
t.emit('<'); // char that got us here
t.transition(Data);
}
break;
}
}
},
EndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.emit("</");
t.transition(Data);
} else if (r.matchesAsciiAlpha()) {
t.createTagPending(false);
t.transition(TagName);
} else if (r.matches('>')) {
t.error(this);
t.advanceTransition(Data);
} else {
t.error(this);
t.createBogusCommentPending();
t.commentPending.append('/'); // push the / back on that got us here
t.transition(BogusComment);
}
}
},
TagName {
// from < or </ in data, will have start or end tag pending
void read(Tokeniser t, CharacterReader r) {
// previous TagOpen state did NOT consume, will have a letter char in current
String tagName = r.consumeTagName();
t.tagPending.appendTagName(tagName);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '<': // NOTE: out of spec, but clear author intent
r.unconsume();
t.error(this);
// intended fall through to next >
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar: // replacement
t.tagPending.appendTagName(replacementStr);
break;
case eof: // should emit pending tag?
t.eofError(this);
t.transition(Data);
break;
default: // buffer underrun
t.tagPending.appendTagName(c);
}
}
},
RcdataLessthanSign {
// from < in rcdata
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RCDATAEndTagOpen);
} else if (r.matchesAsciiAlpha() && t.appropriateEndTagName() != null && !r.containsIgnoreCase(t.appropriateEndTagSeq())) {
// diverge from spec: got a start tag, but there's no appropriate end tag (</title>), so rather than
// consuming to EOF; break out here
t.tagPending = t.createTagPending(false).name(t.appropriateEndTagName());
t.emitTagPending();
t.transition(TagOpen); // straight into TagOpen, as we came from < and looks like we're on a start tag
} else {
t.emit("<");
t.transition(Rcdata);
}
}
},
RCDATAEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesAsciiAlpha()) {
t.createTagPending(false);
t.tagPending.appendTagName(r.current());
t.dataBuffer.append(r.current());
t.advanceTransition(RCDATAEndTagName);
} else {
t.emit("</");
t.transition(Rcdata);
}
}
},
RCDATAEndTagName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesAsciiAlpha()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name);
t.dataBuffer.append(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
if (t.isAppropriateEndTagToken())
t.transition(BeforeAttributeName);
else
anythingElse(t, r);
break;
case '/':
if (t.isAppropriateEndTagToken())
t.transition(SelfClosingStartTag);
else
anythingElse(t, r);
break;
case '>':
if (t.isAppropriateEndTagToken()) {
t.emitTagPending();
t.transition(Data);
}
else
anythingElse(t, r);
break;
default:
anythingElse(t, r);
}
}
private void anythingElse(Tokeniser t, CharacterReader r) {
t.emit("</");
t.emit(t.dataBuffer);
r.unconsume();
t.transition(Rcdata);
}
},
RawtextLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(RawtextEndTagOpen);
} else {
t.emit('<');
t.transition(Rawtext);
}
}
},
RawtextEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
readEndTag(t, r, RawtextEndTagName, Rawtext);
}
},
RawtextEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, Rawtext);
}
},
ScriptDataLessthanSign {
void read(Tokeniser t, CharacterReader r) {
switch (r.consume()) {
case '/':
t.createTempBuffer();
t.transition(ScriptDataEndTagOpen);
break;
case '!':
t.emit("<!");
t.transition(ScriptDataEscapeStart);
break;
case eof:
t.emit("<");
t.eofError(this);
t.transition(Data);
break;
default:
t.emit("<");
r.unconsume();
t.transition(ScriptData);
}
}
},
ScriptDataEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
readEndTag(t, r, ScriptDataEndTagName, ScriptData);
}
},
ScriptDataEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, ScriptData);
}
},
ScriptDataEscapeStart {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('-')) {
t.emit('-');
t.advanceTransition(ScriptDataEscapeStartDash);
} else {
t.transition(ScriptData);
}
}
},
ScriptDataEscapeStartDash {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('-')) {
t.emit('-');
t.advanceTransition(ScriptDataEscapedDashDash);
} else {
t.transition(ScriptData);
}
}
},
ScriptDataEscaped {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
switch (r.current()) {
case '-':
t.emit('-');
t.advanceTransition(ScriptDataEscapedDash);
break;
case '<':
t.advanceTransition(ScriptDataEscapedLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
default:
String data = r.consumeToAny('-', '<', nullChar);
t.emit(data);
}
}
},
ScriptDataEscapedDash {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
t.transition(ScriptDataEscapedDashDash);
break;
case '<':
t.transition(ScriptDataEscapedLessthanSign);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataEscaped);
break;
default:
t.emit(c);
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedDashDash {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.transition(Data);
return;
}
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
break;
case '<':
t.transition(ScriptDataEscapedLessthanSign);
break;
case '>':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataEscaped);
break;
default:
t.emit(c);
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesAsciiAlpha()) {
t.createTempBuffer();
t.dataBuffer.append(r.current());
t.emit("<");
t.emit(r.current());
t.advanceTransition(ScriptDataDoubleEscapeStart);
} else if (r.matches('/')) {
t.createTempBuffer();
t.advanceTransition(ScriptDataEscapedEndTagOpen);
} else {
t.emit('<');
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedEndTagOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesAsciiAlpha()) {
t.createTagPending(false);
t.tagPending.appendTagName(r.current());
t.dataBuffer.append(r.current());
t.advanceTransition(ScriptDataEscapedEndTagName);
} else {
t.emit("</");
t.transition(ScriptDataEscaped);
}
}
},
ScriptDataEscapedEndTagName {
void read(Tokeniser t, CharacterReader r) {
handleDataEndTag(t, r, ScriptDataEscaped);
}
},
ScriptDataDoubleEscapeStart {
void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t, r, ScriptDataDoubleEscaped, ScriptDataEscaped);
}
},
ScriptDataDoubleEscaped {
void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedDash);
break;
case '<':
t.emit(c);
t.advanceTransition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
String data = r.consumeToAny('-', '<', nullChar);
t.emit(data);
}
}
},
ScriptDataDoubleEscapedDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
t.transition(ScriptDataDoubleEscapedDashDash);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapedDashDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.emit(c);
break;
case '<':
t.emit(c);
t.transition(ScriptDataDoubleEscapedLessthanSign);
break;
case '>':
t.emit(c);
t.transition(ScriptData);
break;
case nullChar:
t.error(this);
t.emit(replacementChar);
t.transition(ScriptDataDoubleEscaped);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.emit(c);
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapedLessthanSign {
void read(Tokeniser t, CharacterReader r) {
if (r.matches('/')) {
t.emit('/');
t.createTempBuffer();
t.advanceTransition(ScriptDataDoubleEscapeEnd);
} else {
t.transition(ScriptDataDoubleEscaped);
}
}
},
ScriptDataDoubleEscapeEnd {
void read(Tokeniser t, CharacterReader r) {
handleDataDoubleEscapeTag(t,r, ScriptDataEscaped, ScriptDataDoubleEscaped);
}
},
BeforeAttributeName {
// from tagname <xxx
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case '/':
t.transition(SelfClosingStartTag);
break;
case '<': // NOTE: out of spec, but clear (spec has this as a part of the attribute name)
r.unconsume();
t.error(this);
// intended fall through as if >
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
r.unconsume();
t.error(this);
t.tagPending.newAttribute();
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '=':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
},
AttributeName {
// from before attribute name
void read(Tokeniser t, CharacterReader r) {
String name = r.consumeToAnySorted(attributeNameCharsSorted); // spec deviate - consume and emit nulls in one hit vs stepping
t.tagPending.appendAttributeName(name);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
t.error(this);
t.tagPending.appendAttributeName(c);
break;
default: // buffer underrun
t.tagPending.appendAttributeName(c);
}
}
},
AfterAttributeName {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '=':
t.transition(BeforeAttributeValue);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeName(replacementChar);
t.transition(AttributeName);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
t.error(this);
t.tagPending.newAttribute();
t.tagPending.appendAttributeName(c);
t.transition(AttributeName);
break;
default: // A-Z, anything else
t.tagPending.newAttribute();
r.unconsume();
t.transition(AttributeName);
}
}
},
BeforeAttributeValue {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
// ignore
break;
case '"':
t.transition(AttributeValue_doubleQuoted);
break;
case '&':
r.unconsume();
t.transition(AttributeValue_unquoted);
break;
case '\'':
t.transition(AttributeValue_singleQuoted);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
t.transition(AttributeValue_unquoted);
break;
case eof:
t.eofError(this);
t.emitTagPending();
t.transition(Data);
break;
case '>':
t.error(this);
t.emitTagPending();
t.transition(Data);
break;
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
t.transition(AttributeValue_unquoted);
break;
default:
r.unconsume();
t.transition(AttributeValue_unquoted);
}
}
},
AttributeValue_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
String value = r.consumeAttributeQuoted(false);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
else
t.tagPending.setEmptyAttributeValue();
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
int[] ref = t.consumeCharacterReference('"', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default: // hit end of buffer in first read, still in attribute
t.tagPending.appendAttributeValue(c);
}
}
},
AttributeValue_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
String value = r.consumeAttributeQuoted(true);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
else
t.tagPending.setEmptyAttributeValue();
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterAttributeValue_quoted);
break;
case '&':
int[] ref = t.consumeCharacterReference('\'', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default: // hit end of buffer in first read, still in attribute
t.tagPending.appendAttributeValue(c);
}
}
},
AttributeValue_unquoted {
void read(Tokeniser t, CharacterReader r) {
String value = r.consumeToAnySorted(attributeValueUnquoted);
if (value.length() > 0)
t.tagPending.appendAttributeValue(value);
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '&':
int[] ref = t.consumeCharacterReference('>', true);
if (ref != null)
t.tagPending.appendAttributeValue(ref);
else
t.tagPending.appendAttributeValue('&');
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.tagPending.appendAttributeValue(replacementChar);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
case '"':
case '\'':
case '<':
case '=':
case '`':
t.error(this);
t.tagPending.appendAttributeValue(c);
break;
default: // hit end of buffer in first read, still in attribute
t.tagPending.appendAttributeValue(c);
}
}
},
// CharacterReferenceInAttributeValue state handled inline
AfterAttributeValue_quoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
r.unconsume();
t.error(this);
t.transition(BeforeAttributeName);
}
}
},
SelfClosingStartTag {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.tagPending.selfClosing = true;
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
r.unconsume();
t.error(this);
t.transition(BeforeAttributeName);
}
}
},
BogusComment {
void read(Tokeniser t, CharacterReader r) {
// todo: handle bogus comment starting from eof. when does that trigger?
t.commentPending.append(r.consumeTo('>'));
// todo: replace nullChar with replaceChar
char next = r.current();
if (next == '>' || next == eof) {
r.consume();
t.emitCommentPending();
t.transition(Data);
}
}
},
MarkupDeclarationOpen {
void read(Tokeniser t, CharacterReader r) {
if (r.matchConsume("--")) {
t.createCommentPending();
t.transition(CommentStart);
} else if (r.matchConsumeIgnoreCase("DOCTYPE")) {
t.transition(Doctype);
} else if (r.matchConsume("[CDATA[")) {
// todo: should actually check current namespace, and only non-html allows cdata. until namespace
// is implemented properly, keep handling as cdata
//} else if (!t.currentNodeInHtmlNS() && r.matchConsume("[CDATA[")) {
t.createTempBuffer();
t.transition(CdataSection);
} else {
t.error(this);
t.createBogusCommentPending();
t.transition(BogusComment);
}
}
},
CommentStart {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
r.unconsume();
t.transition(Comment);
}
}
},
CommentStartDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentStartDash);
break;
case nullChar:
t.error(this);
t.commentPending.append(replacementChar);
t.transition(Comment);
break;
case '>':
t.error(this);
t.emitCommentPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.append(c);
t.transition(Comment);
}
}
},
Comment {
void read(Tokeniser t, CharacterReader r) {
char c = r.current();
switch (c) {
case '-':
t.advanceTransition(CommentEndDash);
break;
case nullChar:
t.error(this);
r.advance();
t.commentPending.append(replacementChar);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.append(r.consumeToAny('-', nullChar));
}
}
},
CommentEndDash {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.transition(CommentEnd);
break;
case nullChar:
t.error(this);
t.commentPending.append('-').append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.append('-').append(c);
t.transition(Comment);
}
}
},
CommentEnd {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.append("--").append(replacementChar);
t.transition(Comment);
break;
case '!':
t.error(this);
t.transition(CommentEndBang);
break;
case '-':
t.error(this);
t.commentPending.append('-');
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.error(this);
t.commentPending.append("--").append(c);
t.transition(Comment);
}
}
},
CommentEndBang {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '-':
t.commentPending.append("--!");
t.transition(CommentEndDash);
break;
case '>':
t.emitCommentPending();
t.transition(Data);
break;
case nullChar:
t.error(this);
t.commentPending.append("--!").append(replacementChar);
t.transition(Comment);
break;
case eof:
t.eofError(this);
t.emitCommentPending();
t.transition(Data);
break;
default:
t.commentPending.append("--!").append(c);
t.transition(Comment);
}
}
},
Doctype {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeName);
break;
case eof:
t.eofError(this);
// note: fall through to > case
case '>': // catch invalid <!DOCTYPE>
t.error(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeDoctypeName);
}
}
},
BeforeDoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesAsciiAlpha()) {
t.createDoctypePending();
t.transition(DoctypeName);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break; // ignore whitespace
case nullChar:
t.error(this);
t.createDoctypePending();
t.doctypePending.name.append(replacementChar);
t.transition(DoctypeName);
break;
case eof:
t.eofError(this);
t.createDoctypePending();
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.createDoctypePending();
t.doctypePending.name.append(c);
t.transition(DoctypeName);
}
}
},
DoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.doctypePending.name.append(name);
return;
}
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(AfterDoctypeName);
break;
case nullChar:
t.error(this);
t.doctypePending.name.append(replacementChar);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.name.append(c);
}
}
},
AfterDoctypeName {
void read(Tokeniser t, CharacterReader r) {
if (r.isEmpty()) {
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
return;
}
if (r.matchesAny('\t', '\n', '\r', '\f', ' '))
r.advance(); // ignore whitespace
else if (r.matches('>')) {
t.emitDoctypePending();
t.advanceTransition(Data);
} else if (r.matchConsumeIgnoreCase(DocumentType.PUBLIC_KEY)) {
t.doctypePending.pubSysKey = DocumentType.PUBLIC_KEY;
t.transition(AfterDoctypePublicKeyword);
} else if (r.matchConsumeIgnoreCase(DocumentType.SYSTEM_KEY)) {
t.doctypePending.pubSysKey = DocumentType.SYSTEM_KEY;
t.transition(AfterDoctypeSystemKeyword);
} else {
t.error(this);
t.doctypePending.forceQuirks = true;
t.advanceTransition(BogusDoctype);
}
}
},
AfterDoctypePublicKeyword {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypePublicIdentifier);
break;
case '"':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
BeforeDoctypePublicIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '"':
// set public id to empty string
t.transition(DoctypePublicIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypePublicIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
DoctypePublicIdentifier_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
},
DoctypePublicIdentifier_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypePublicIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.publicIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.publicIdentifier.append(c);
}
}
},
AfterDoctypePublicIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BetweenDoctypePublicAndSystemIdentifiers);
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
BetweenDoctypePublicAndSystemIdentifiers {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
AfterDoctypeSystemKeyword {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeDoctypeSystemIdentifier);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case '"':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
t.error(this);
// system id empty
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
}
}
},
BeforeDoctypeSystemIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '"':
// set system id to empty string
t.transition(DoctypeSystemIdentifier_doubleQuoted);
break;
case '\'':
// set public id to empty string
t.transition(DoctypeSystemIdentifier_singleQuoted);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.doctypePending.forceQuirks = true;
t.transition(BogusDoctype);
}
}
},
DoctypeSystemIdentifier_doubleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '"':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
},
DoctypeSystemIdentifier_singleQuoted {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\'':
t.transition(AfterDoctypeSystemIdentifier);
break;
case nullChar:
t.error(this);
t.doctypePending.systemIdentifier.append(replacementChar);
break;
case '>':
t.error(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.doctypePending.systemIdentifier.append(c);
}
}
},
AfterDoctypeSystemIdentifier {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
break;
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.doctypePending.forceQuirks = true;
t.emitDoctypePending();
t.transition(Data);
break;
default:
t.error(this);
t.transition(BogusDoctype);
// NOT force quirks
}
}
},
BogusDoctype {
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.emitDoctypePending();
t.transition(Data);
break;
case eof:
t.emitDoctypePending();
t.transition(Data);
break;
default:
// ignore char
break;
}
}
},
CdataSection {
void read(Tokeniser t, CharacterReader r) {
String data = r.consumeTo("]]>");
t.dataBuffer.append(data);
if (r.matchConsume("]]>") || r.isEmpty()) {
t.emit(new Token.CData(t.dataBuffer.toString()));
t.transition(Data);
}// otherwise, buffer underrun, stay in data section
}
};
abstract void read(Tokeniser t, CharacterReader r);
static final char nullChar = '\u0000';
// char searches. must be sorted, used in inSorted. MUST update TokenisetStateTest if more arrays are added.
static final char[] attributeNameCharsSorted = new char[]{'\t', '\n', '\f', '\r', ' ', '"', '\'', '/', '<', '=', '>'};
static final char[] attributeValueUnquoted = new char[]{nullChar, '\t', '\n', '\f', '\r', ' ', '"', '&', '\'', '<', '=', '>', '`'};
private static final char replacementChar = Tokeniser.replacementChar;
private static final String replacementStr = String.valueOf(Tokeniser.replacementChar);
private static final char eof = CharacterReader.EOF;
/**
* Handles RawtextEndTagName, ScriptDataEndTagName, and ScriptDataEscapedEndTagName. Same body impl, just
* different else exit transitions.
*/
private static void handleDataEndTag(Tokeniser t, CharacterReader r, TokeniserState elseTransition) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name);
t.dataBuffer.append(name);
return;
}
boolean needsExitTransition = false;
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
needsExitTransition = true;
}
} else {
needsExitTransition = true;
}
if (needsExitTransition) {
t.emit("</");
t.emit(t.dataBuffer);
t.transition(elseTransition);
}
}
private static void readRawData(Tokeniser t, CharacterReader r, TokeniserState current, TokeniserState advance) {
switch (r.current()) {
case '<':
t.advanceTransition(advance);
break;
case nullChar:
t.error(current);
r.advance();
t.emit(replacementChar);
break;
case eof:
t.emit(new Token.EOF());
break;
default:
String data = r.consumeRawData();
t.emit(data);
break;
}
}
private static void readCharRef(Tokeniser t, TokeniserState advance) {
int[] c = t.consumeCharacterReference(null, false);
if (c == null)
t.emit('&');
else
t.emit(c);
t.transition(advance);
}
private static void readEndTag(Tokeniser t, CharacterReader r, TokeniserState a, TokeniserState b) {
if (r.matchesAsciiAlpha()) {
t.createTagPending(false);
t.transition(a);
} else {
t.emit("</");
t.transition(b);
}
}
private static void handleDataDoubleEscapeTag(Tokeniser t, CharacterReader r, TokeniserState primary, TokeniserState fallback) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.dataBuffer.append(name);
t.emit(name);
return;
}
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\r':
case '\f':
case ' ':
case '/':
case '>':
if (t.dataBuffer.toString().equals("script"))
t.transition(primary);
else
t.transition(fallback);
t.emit(c);
break;
default:
r.unconsume();
t.transition(fallback);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/TreeBuilder.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Jonathan Hedley
*/
abstract class TreeBuilder {
protected Parser parser;
CharacterReader reader;
Tokeniser tokeniser;
protected Document doc; // current doc we are building into
protected ArrayList<Element> stack; // the stack of open elements
protected String baseUri; // current base uri, for creating new elements
protected Token currentToken; // currentToken is used only for error tracking.
protected ParseSettings settings;
protected Map<String, Tag> seenTags; // tags we've used in this parse; saves tag GC for custom tags.
private Token.StartTag start = new Token.StartTag(); // start tag to process
private Token.EndTag end = new Token.EndTag();
abstract ParseSettings defaultSettings();
@ParametersAreNonnullByDefault
protected void initialiseParse(Reader input, String baseUri, Parser parser) {
Validate.notNull(input, "String input must not be null");
Validate.notNull(baseUri, "BaseURI must not be null");
Validate.notNull(parser);
doc = new Document(baseUri);
doc.parser(parser);
this.parser = parser;
settings = parser.settings();
reader = new CharacterReader(input);
reader.trackNewlines(parser.isTrackErrors()); // when tracking errors, enable newline tracking for better error reports
currentToken = null;
tokeniser = new Tokeniser(reader, parser.getErrors());
stack = new ArrayList<>(32);
seenTags = new HashMap<>();
this.baseUri = baseUri;
}
@ParametersAreNonnullByDefault
Document parse(Reader input, String baseUri, Parser parser) {
initialiseParse(input, baseUri, parser);
runParser();
// tidy up - as the Parser and Treebuilder are retained in document for settings / fragments
reader.close();
reader = null;
tokeniser = null;
stack = null;
seenTags = null;
return doc;
}
/**
Create a new copy of this TreeBuilder
@return copy, ready for a new parse
*/
abstract TreeBuilder newInstance();
abstract List<Node> parseFragment(String inputFragment, Element context, String baseUri, Parser parser);
protected void runParser() {
final Tokeniser tokeniser = this.tokeniser;
final Token.TokenType eof = Token.TokenType.EOF;
while (true) {
Token token = tokeniser.read();
process(token);
token.reset();
if (token.type == eof)
break;
}
}
protected abstract boolean process(Token token);
protected boolean processStartTag(String name) {
final Token.StartTag start = this.start;
if (currentToken == start) { // don't recycle an in-use token
return process(new Token.StartTag().name(name));
}
return process(start.reset().name(name));
}
public boolean processStartTag(String name, Attributes attrs) {
final Token.StartTag start = this.start;
if (currentToken == start) { // don't recycle an in-use token
return process(new Token.StartTag().nameAttr(name, attrs));
}
start.reset();
start.nameAttr(name, attrs);
return process(start);
}
protected boolean processEndTag(String name) {
if (currentToken == end) { // don't recycle an in-use token
return process(new Token.EndTag().name(name));
}
return process(end.reset().name(name));
}
/**
Get the current element (last on the stack). If all items have been removed, returns the document instead
(which might not actually be on the stack; use stack.size() == 0 to test if required.
@return the last element on the stack, if any; or the root document
*/
protected Element currentElement() {
int size = stack.size();
return size > 0 ? stack.get(size-1) : doc;
}
/**
Checks if the Current Element's normal name equals the supplied name.
@param normalName name to check
@return true if there is a current element on the stack, and its name equals the supplied
*/
protected boolean currentElementIs(String normalName) {
if (stack.size() == 0)
return false;
Element current = currentElement();
return current != null && current.normalName().equals(normalName);
}
/**
* If the parser is tracking errors, add an error at the current position.
* @param msg error message
*/
protected void error(String msg) {
error(msg, (Object[]) null);
}
/**
* If the parser is tracking errors, add an error at the current position.
* @param msg error message template
* @param args template arguments
*/
protected void error(String msg, Object... args) {
ParseErrorList errors = parser.getErrors();
if (errors.canAddError())
errors.add(new ParseError(reader, msg, args));
}
/**
(An internal method, visible for Element. For HTML parse, signals that script and style text should be treated as
Data Nodes).
*/
protected boolean isContentForTagData(String normalName) {
return false;
}
protected Tag tagFor(String tagName, ParseSettings settings) {
Tag tag = seenTags.get(tagName); // note that we don't normalize the cache key. But tag via valueOf may be normalized.
if (tag == null) {
tag = Tag.valueOf(tagName, settings);
seenTags.put(tagName, tag);
}
return tag;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/XmlTreeBuilder.java
|
package org.jsoup.parser;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.CDataNode;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.nodes.XmlDeclaration;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;
/**
* Use the {@code XmlTreeBuilder} when you want to parse XML without any of the HTML DOM rules being applied to the
* document.
* <p>Usage example: {@code Document xmlDoc = Jsoup.parse(html, baseUrl, Parser.xmlParser());}</p>
*
* @author Jonathan Hedley
*/
public class XmlTreeBuilder extends TreeBuilder {
ParseSettings defaultSettings() {
return ParseSettings.preserveCase;
}
@Override @ParametersAreNonnullByDefault
protected void initialiseParse(Reader input, String baseUri, Parser parser) {
super.initialiseParse(input, baseUri, parser);
stack.add(doc); // place the document onto the stack. differs from HtmlTreeBuilder (not on stack)
doc.outputSettings()
.syntax(Document.OutputSettings.Syntax.xml)
.escapeMode(Entities.EscapeMode.xhtml)
.prettyPrint(false); // as XML, we don't understand what whitespace is significant or not
}
Document parse(Reader input, String baseUri) {
return parse(input, baseUri, new Parser(this));
}
Document parse(String input, String baseUri) {
return parse(new StringReader(input), baseUri, new Parser(this));
}
@Override
XmlTreeBuilder newInstance() {
return new XmlTreeBuilder();
}
@Override
protected boolean process(Token token) {
// start tag, end tag, doctype, comment, character, eof
switch (token.type) {
case StartTag:
insert(token.asStartTag());
break;
case EndTag:
popStackToClose(token.asEndTag());
break;
case Comment:
insert(token.asComment());
break;
case Character:
insert(token.asCharacter());
break;
case Doctype:
insert(token.asDoctype());
break;
case EOF: // could put some normalisation here if desired
break;
default:
Validate.fail("Unexpected token type: " + token.type);
}
return true;
}
private void insertNode(Node node) {
currentElement().appendChild(node);
}
Element insert(Token.StartTag startTag) {
Tag tag = tagFor(startTag.name(), settings);
// todo: wonder if for xml parsing, should treat all tags as unknown? because it's not html.
if (startTag.hasAttributes())
startTag.attributes.deduplicate(settings);
Element el = new Element(tag, null, settings.normalizeAttributes(startTag.attributes));
insertNode(el);
if (startTag.isSelfClosing()) {
if (!tag.isKnownTag()) // unknown tag, remember this is self closing for output. see above.
tag.setSelfClosing();
} else {
stack.add(el);
}
return el;
}
void insert(Token.Comment commentToken) {
Comment comment = new Comment(commentToken.getData());
Node insert = comment;
if (commentToken.bogus && comment.isXmlDeclaration()) {
// xml declarations are emitted as bogus comments (which is right for html, but not xml)
// so we do a bit of a hack and parse the data as an element to pull the attributes out
XmlDeclaration decl = comment.asXmlDeclaration(); // else, we couldn't parse it as a decl, so leave as a comment
if (decl != null)
insert = decl;
}
insertNode(insert);
}
void insert(Token.Character token) {
final String data = token.getData();
insertNode(token.isCData() ? new CDataNode(data) : new TextNode(data));
}
void insert(Token.Doctype d) {
DocumentType doctypeNode = new DocumentType(settings.normalizeTag(d.getName()), d.getPublicIdentifier(), d.getSystemIdentifier());
doctypeNode.setPubSysKey(d.getPubSysKey());
insertNode(doctypeNode);
}
/**
* If the stack contains an element with this tag's name, pop up the stack to remove the first occurrence. If not
* found, skips.
*
* @param endTag tag to close
*/
private void popStackToClose(Token.EndTag endTag) {
// like in HtmlTreeBuilder - don't scan up forever for very (artificially) deeply nested stacks
String elName = settings.normalizeTag(endTag.tagName);
Element firstFound = null;
final int bottom = stack.size() - 1;
final int upper = bottom >= maxQueueDepth ? bottom - maxQueueDepth : 0;
for (int pos = stack.size() -1; pos >= upper; pos--) {
Element next = stack.get(pos);
if (next.nodeName().equals(elName)) {
firstFound = next;
break;
}
}
if (firstFound == null)
return; // not found, skip
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos);
if (next == firstFound)
break;
}
}
private static final int maxQueueDepth = 256; // an arbitrary tension point between real XML and crafted pain
List<Node> parseFragment(String inputFragment, String baseUri, Parser parser) {
initialiseParse(new StringReader(inputFragment), baseUri, parser);
runParser();
return doc.childNodes();
}
List<Node> parseFragment(String inputFragment, Element context, String baseUri, Parser parser) {
return parseFragment(inputFragment, baseUri, parser);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/parser/package-info.java
|
/**
Contains the HTML parser, tag specifications, and HTML tokeniser.
*/
package org.jsoup.parser;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/safety/Cleaner.java
|
package org.jsoup.safety;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.parser.ParseErrorList;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
import java.util.List;
/**
The safelist based HTML cleaner. Use to ensure that end-user provided HTML contains only the elements and attributes
that you are expecting; no junk, and no cross-site scripting attacks!
<p>
The HTML cleaner parses the input as HTML and then runs it through a safe-list, so the output HTML can only contain
HTML that is allowed by the safelist.
</p>
<p>
It is assumed that the input HTML is a body fragment; the clean methods only pull from the source's body, and the
canned safe-lists only allow body contained tags.
</p>
<p>
Rather than interacting directly with a Cleaner object, generally see the {@code clean} methods in {@link org.jsoup.Jsoup}.
</p>
*/
public class Cleaner {
private final Safelist safelist;
/**
Create a new cleaner, that sanitizes documents using the supplied safelist.
@param safelist safe-list to clean with
*/
public Cleaner(Safelist safelist) {
Validate.notNull(safelist);
this.safelist = safelist;
}
/**
Use {@link #Cleaner(Safelist)} instead.
@deprecated as of 1.14.1.
*/
@Deprecated
public Cleaner(Whitelist whitelist) {
Validate.notNull(whitelist);
this.safelist = whitelist;
}
/**
Creates a new, clean document, from the original dirty document, containing only elements allowed by the safelist.
The original document is not modified. Only elements from the dirty document's <code>body</code> are used. The
OutputSettings of the original document are cloned into the clean document.
@param dirtyDocument Untrusted base document to clean.
@return cleaned document.
*/
public Document clean(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
copySafeNodes(dirtyDocument.body(), clean.body());
clean.outputSettings(dirtyDocument.outputSettings().clone());
return clean;
}
/**
Determines if the input document <b>body</b>is valid, against the safelist. It is considered valid if all the tags and attributes
in the input HTML are allowed by the safelist, and that there is no content in the <code>head</code>.
<p>
This method can be used as a validator for user input. An invalid document will still be cleaned successfully
using the {@link #clean(Document)} document. If using as a validator, it is recommended to still clean the document
to ensure enforced attributes are set correctly, and that the output is tidied.
</p>
@param dirtyDocument document to test
@return true if no tags or attributes need to be removed; false if they do
*/
public boolean isValid(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
int numDiscarded = copySafeNodes(dirtyDocument.body(), clean.body());
return numDiscarded == 0
&& dirtyDocument.head().childNodes().isEmpty(); // because we only look at the body, but we start from a shell, make sure there's nothing in the head
}
public boolean isValidBodyHtml(String bodyHtml) {
Document clean = Document.createShell("");
Document dirty = Document.createShell("");
ParseErrorList errorList = ParseErrorList.tracking(1);
List<Node> nodes = Parser.parseFragment(bodyHtml, dirty.body(), "", errorList);
dirty.body().insertChildren(0, nodes);
int numDiscarded = copySafeNodes(dirty.body(), clean.body());
return numDiscarded == 0 && errorList.isEmpty();
}
/**
Iterates the input and copies trusted nodes (tags, attributes, text) into the destination.
*/
private final class CleaningVisitor implements NodeVisitor {
private int numDiscarded = 0;
private final Element root;
private Element destination; // current element to append nodes to
private CleaningVisitor(Element root, Element destination) {
this.root = root;
this.destination = destination;
}
public void head(Node source, int depth) {
if (source instanceof Element) {
Element sourceEl = (Element) source;
if (safelist.isSafeTag(sourceEl.normalName())) { // safe, clone and copy safe attrs
ElementMeta meta = createSafeElement(sourceEl);
Element destChild = meta.el;
destination.appendChild(destChild);
numDiscarded += meta.numAttribsDiscarded;
destination = destChild;
} else if (source != root) { // not a safe tag, so don't add. don't count root against discarded.
numDiscarded++;
}
} else if (source instanceof TextNode) {
TextNode sourceText = (TextNode) source;
TextNode destText = new TextNode(sourceText.getWholeText());
destination.appendChild(destText);
} else if (source instanceof DataNode && safelist.isSafeTag(source.parent().nodeName())) {
DataNode sourceData = (DataNode) source;
DataNode destData = new DataNode(sourceData.getWholeData());
destination.appendChild(destData);
} else { // else, we don't care about comments, xml proc instructions, etc
numDiscarded++;
}
}
public void tail(Node source, int depth) {
if (source instanceof Element && safelist.isSafeTag(source.nodeName())) {
destination = destination.parent(); // would have descended, so pop destination stack
}
}
}
private int copySafeNodes(Element source, Element dest) {
CleaningVisitor cleaningVisitor = new CleaningVisitor(source, dest);
NodeTraversor.traverse(cleaningVisitor, source);
return cleaningVisitor.numDiscarded;
}
private ElementMeta createSafeElement(Element sourceEl) {
String sourceTag = sourceEl.tagName();
Attributes destAttrs = new Attributes();
Element dest = new Element(Tag.valueOf(sourceTag), sourceEl.baseUri(), destAttrs);
int numDiscarded = 0;
Attributes sourceAttrs = sourceEl.attributes();
for (Attribute sourceAttr : sourceAttrs) {
if (safelist.isSafeAttribute(sourceTag, sourceEl, sourceAttr))
destAttrs.put(sourceAttr);
else
numDiscarded++;
}
Attributes enforcedAttrs = safelist.getEnforcedAttributes(sourceTag);
destAttrs.addAll(enforcedAttrs);
return new ElementMeta(dest, numDiscarded);
}
private static class ElementMeta {
Element el;
int numAttribsDiscarded;
ElementMeta(Element el, int numAttribsDiscarded) {
this.el = el;
this.numAttribsDiscarded = numAttribsDiscarded;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/safety/Safelist.java
|
package org.jsoup.safety;
/*
Thank you to Ryan Grove (wonko.com) for the Ruby HTML cleaner http://github.com/rgrove/sanitize/, which inspired
this safe-list configuration, and the initial defaults.
*/
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static org.jsoup.internal.Normalizer.lowerCase;
/**
Safe-lists define what HTML (elements and attributes) to allow through the cleaner. Everything else is removed.
<p>
Start with one of the defaults:
</p>
<ul>
<li>{@link #none}
<li>{@link #simpleText}
<li>{@link #basic}
<li>{@link #basicWithImages}
<li>{@link #relaxed}
</ul>
<p>
If you need to allow more through (please be careful!), tweak a base safelist with:
</p>
<ul>
<li>{@link #addTags(String... tagNames)}
<li>{@link #addAttributes(String tagName, String... attributes)}
<li>{@link #addEnforcedAttribute(String tagName, String attribute, String value)}
<li>{@link #addProtocols(String tagName, String attribute, String... protocols)}
</ul>
<p>
You can remove any setting from an existing safelist with:
</p>
<ul>
<li>{@link #removeTags(String... tagNames)}
<li>{@link #removeAttributes(String tagName, String... attributes)}
<li>{@link #removeEnforcedAttribute(String tagName, String attribute)}
<li>{@link #removeProtocols(String tagName, String attribute, String... removeProtocols)}
</ul>
<p>
The cleaner and these safelists assume that you want to clean a <code>body</code> fragment of HTML (to add user
supplied HTML into a templated page), and not to clean a full HTML document. If the latter is the case, either wrap the
document HTML around the cleaned body HTML, or create a safelist that allows <code>html</code> and <code>head</code>
elements as appropriate.
</p>
<p>
If you are going to extend a safelist, please be very careful. Make sure you understand what attributes may lead to
XSS attack vectors. URL attributes are particularly vulnerable and require careful validation. See
the <a href="https://owasp.org/www-community/xss-filter-evasion-cheatsheet">XSS Filter Evasion Cheat Sheet</a> for some
XSS attack examples (that jsoup will safegaurd against the default Cleaner and Safelist configuration).
</p>
*/
public class Safelist {
private Set<TagName> tagNames; // tags allowed, lower case. e.g. [p, br, span]
private Map<TagName, Set<AttributeKey>> attributes; // tag -> attribute[]. allowed attributes [href] for a tag.
private Map<TagName, Map<AttributeKey, AttributeValue>> enforcedAttributes; // always set these attribute values
private Map<TagName, Map<AttributeKey, Set<Protocol>>> protocols; // allowed URL protocols for attributes
private boolean preserveRelativeLinks; // option to preserve relative links
/**
This safelist allows only text nodes: all HTML will be stripped.
@return safelist
*/
public static Safelist none() {
return new Safelist();
}
/**
This safelist allows only simple text formatting: <code>b, em, i, strong, u</code>. All other HTML (tags and
attributes) will be removed.
@return safelist
*/
public static Safelist simpleText() {
return new Safelist()
.addTags("b", "em", "i", "strong", "u")
;
}
/**
<p>
This safelist allows a fuller range of text nodes: <code>a, b, blockquote, br, cite, code, dd, dl, dt, em, i, li,
ol, p, pre, q, small, span, strike, strong, sub, sup, u, ul</code>, and appropriate attributes.
</p>
<p>
Links (<code>a</code> elements) can point to <code>http, https, ftp, mailto</code>, and have an enforced
<code>rel=nofollow</code> attribute.
</p>
<p>
Does not allow images.
</p>
@return safelist
*/
public static Safelist basic() {
return new Safelist()
.addTags(
"a", "b", "blockquote", "br", "cite", "code", "dd", "dl", "dt", "em",
"i", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong", "sub",
"sup", "u", "ul")
.addAttributes("a", "href")
.addAttributes("blockquote", "cite")
.addAttributes("q", "cite")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addEnforcedAttribute("a", "rel", "nofollow")
;
}
/**
This safelist allows the same text tags as {@link #basic}, and also allows <code>img</code> tags, with appropriate
attributes, with <code>src</code> pointing to <code>http</code> or <code>https</code>.
@return safelist
*/
public static Safelist basicWithImages() {
return basic()
.addTags("img")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addProtocols("img", "src", "http", "https")
;
}
/**
This safelist allows a full range of text and structural body HTML: <code>a, b, blockquote, br, caption, cite,
code, col, colgroup, dd, div, dl, dt, em, h1, h2, h3, h4, h5, h6, i, img, li, ol, p, pre, q, small, span, strike, strong, sub,
sup, table, tbody, td, tfoot, th, thead, tr, u, ul</code>
<p>
Links do not have an enforced <code>rel=nofollow</code> attribute, but you can add that if desired.
</p>
@return safelist
*/
public static Safelist relaxed() {
return new Safelist()
.addTags(
"a", "b", "blockquote", "br", "caption", "cite", "code", "col",
"colgroup", "dd", "div", "dl", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6",
"i", "img", "li", "ol", "p", "pre", "q", "small", "span", "strike", "strong",
"sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u",
"ul")
.addAttributes("a", "href", "title")
.addAttributes("blockquote", "cite")
.addAttributes("col", "span", "width")
.addAttributes("colgroup", "span", "width")
.addAttributes("img", "align", "alt", "height", "src", "title", "width")
.addAttributes("ol", "start", "type")
.addAttributes("q", "cite")
.addAttributes("table", "summary", "width")
.addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width")
.addAttributes(
"th", "abbr", "axis", "colspan", "rowspan", "scope",
"width")
.addAttributes("ul", "type")
.addProtocols("a", "href", "ftp", "http", "https", "mailto")
.addProtocols("blockquote", "cite", "http", "https")
.addProtocols("cite", "cite", "http", "https")
.addProtocols("img", "src", "http", "https")
.addProtocols("q", "cite", "http", "https")
;
}
/**
Create a new, empty safelist. Generally it will be better to start with a default prepared safelist instead.
@see #basic()
@see #basicWithImages()
@see #simpleText()
@see #relaxed()
*/
public Safelist() {
tagNames = new HashSet<>();
attributes = new HashMap<>();
enforcedAttributes = new HashMap<>();
protocols = new HashMap<>();
preserveRelativeLinks = false;
}
/**
Deep copy an existing Safelist to a new Safelist.
@param copy the Safelist to copy
*/
public Safelist(Safelist copy) {
this();
tagNames.addAll(copy.tagNames);
attributes.putAll(copy.attributes);
enforcedAttributes.putAll(copy.enforcedAttributes);
protocols.putAll(copy.protocols);
preserveRelativeLinks = copy.preserveRelativeLinks;
}
/**
Add a list of allowed elements to a safelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to allow
@return this (for chaining)
*/
public Safelist addTags(String... tags) {
Validate.notNull(tags);
for (String tagName : tags) {
Validate.notEmpty(tagName);
tagNames.add(TagName.valueOf(tagName));
}
return this;
}
/**
Remove a list of allowed elements from a safelist. (If a tag is not allowed, it will be removed from the HTML.)
@param tags tag names to disallow
@return this (for chaining)
*/
public Safelist removeTags(String... tags) {
Validate.notNull(tags);
for(String tag: tags) {
Validate.notEmpty(tag);
TagName tagName = TagName.valueOf(tag);
if(tagNames.remove(tagName)) { // Only look in sub-maps if tag was allowed
attributes.remove(tagName);
enforcedAttributes.remove(tagName);
protocols.remove(tagName);
}
}
return this;
}
/**
Add a list of allowed attributes to a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>addAttributes("a", "href", "class")</code> allows <code>href</code> and <code>class</code> attributes
on <code>a</code> tags.
</p>
<p>
To make an attribute valid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>addAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for. The tag will be added to the allowed tag list if necessary.
@param attributes List of valid attributes for the tag
@return this (for chaining)
*/
public Safelist addAttributes(String tag, String... attributes) {
Validate.notEmpty(tag);
Validate.notNull(attributes);
Validate.isTrue(attributes.length > 0, "No attribute names supplied.");
TagName tagName = TagName.valueOf(tag);
tagNames.add(tagName);
Set<AttributeKey> attributeSet = new HashSet<>();
for (String key : attributes) {
Validate.notEmpty(key);
attributeSet.add(AttributeKey.valueOf(key));
}
if (this.attributes.containsKey(tagName)) {
Set<AttributeKey> currentSet = this.attributes.get(tagName);
currentSet.addAll(attributeSet);
} else {
this.attributes.put(tagName, attributeSet);
}
return this;
}
/**
Remove a list of allowed attributes from a tag. (If an attribute is not allowed on an element, it will be removed.)
<p>
E.g.: <code>removeAttributes("a", "href", "class")</code> disallows <code>href</code> and <code>class</code>
attributes on <code>a</code> tags.
</p>
<p>
To make an attribute invalid for <b>all tags</b>, use the pseudo tag <code>:all</code>, e.g.
<code>removeAttributes(":all", "class")</code>.
</p>
@param tag The tag the attributes are for.
@param attributes List of invalid attributes for the tag
@return this (for chaining)
*/
public Safelist removeAttributes(String tag, String... attributes) {
Validate.notEmpty(tag);
Validate.notNull(attributes);
Validate.isTrue(attributes.length > 0, "No attribute names supplied.");
TagName tagName = TagName.valueOf(tag);
Set<AttributeKey> attributeSet = new HashSet<>();
for (String key : attributes) {
Validate.notEmpty(key);
attributeSet.add(AttributeKey.valueOf(key));
}
if(tagNames.contains(tagName) && this.attributes.containsKey(tagName)) { // Only look in sub-maps if tag was allowed
Set<AttributeKey> currentSet = this.attributes.get(tagName);
currentSet.removeAll(attributeSet);
if(currentSet.isEmpty()) // Remove tag from attribute map if no attributes are allowed for tag
this.attributes.remove(tagName);
}
if(tag.equals(":all")) // Attribute needs to be removed from all individually set tags
for(TagName name: this.attributes.keySet()) {
Set<AttributeKey> currentSet = this.attributes.get(name);
currentSet.removeAll(attributeSet);
if(currentSet.isEmpty()) // Remove tag from attribute map if no attributes are allowed for tag
this.attributes.remove(name);
}
return this;
}
/**
Add an enforced attribute to a tag. An enforced attribute will always be added to the element. If the element
already has the attribute set, it will be overridden with this value.
<p>
E.g.: <code>addEnforcedAttribute("a", "rel", "nofollow")</code> will make all <code>a</code> tags output as
<code><a href="..." rel="nofollow"></code>
</p>
@param tag The tag the enforced attribute is for. The tag will be added to the allowed tag list if necessary.
@param attribute The attribute name
@param value The enforced attribute value
@return this (for chaining)
*/
public Safelist addEnforcedAttribute(String tag, String attribute, String value) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notEmpty(value);
TagName tagName = TagName.valueOf(tag);
tagNames.add(tagName);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
AttributeValue attrVal = AttributeValue.valueOf(value);
if (enforcedAttributes.containsKey(tagName)) {
enforcedAttributes.get(tagName).put(attrKey, attrVal);
} else {
Map<AttributeKey, AttributeValue> attrMap = new HashMap<>();
attrMap.put(attrKey, attrVal);
enforcedAttributes.put(tagName, attrMap);
}
return this;
}
/**
Remove a previously configured enforced attribute from a tag.
@param tag The tag the enforced attribute is for.
@param attribute The attribute name
@return this (for chaining)
*/
public Safelist removeEnforcedAttribute(String tag, String attribute) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
TagName tagName = TagName.valueOf(tag);
if(tagNames.contains(tagName) && enforcedAttributes.containsKey(tagName)) {
AttributeKey attrKey = AttributeKey.valueOf(attribute);
Map<AttributeKey, AttributeValue> attrMap = enforcedAttributes.get(tagName);
attrMap.remove(attrKey);
if(attrMap.isEmpty()) // Remove tag from enforced attribute map if no enforced attributes are present
enforcedAttributes.remove(tagName);
}
return this;
}
/**
* Configure this Safelist to preserve relative links in an element's URL attribute, or convert them to absolute
* links. By default, this is <b>false</b>: URLs will be made absolute (e.g. start with an allowed protocol, like
* e.g. {@code http://}.
* <p>
* Note that when handling relative links, the input document must have an appropriate {@code base URI} set when
* parsing, so that the link's protocol can be confirmed. Regardless of the setting of the {@code preserve relative
* links} option, the link must be resolvable against the base URI to an allowed protocol; otherwise the attribute
* will be removed.
* </p>
*
* @param preserve {@code true} to allow relative links, {@code false} (default) to deny
* @return this Safelist, for chaining.
* @see #addProtocols
*/
public Safelist preserveRelativeLinks(boolean preserve) {
preserveRelativeLinks = preserve;
return this;
}
/**
Add allowed URL protocols for an element's URL attribute. This restricts the possible values of the attribute to
URLs with the defined protocol.
<p>
E.g.: <code>addProtocols("a", "href", "ftp", "http", "https")</code>
</p>
<p>
To allow a link to an in-page URL anchor (i.e. <code><a href="#anchor"></code>, add a <code>#</code>:<br>
E.g.: <code>addProtocols("a", "href", "#")</code>
</p>
@param tag Tag the URL protocol is for
@param attribute Attribute name
@param protocols List of valid protocols
@return this, for chaining
*/
public Safelist addProtocols(String tag, String attribute, String... protocols) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notNull(protocols);
TagName tagName = TagName.valueOf(tag);
AttributeKey attrKey = AttributeKey.valueOf(attribute);
Map<AttributeKey, Set<Protocol>> attrMap;
Set<Protocol> protSet;
if (this.protocols.containsKey(tagName)) {
attrMap = this.protocols.get(tagName);
} else {
attrMap = new HashMap<>();
this.protocols.put(tagName, attrMap);
}
if (attrMap.containsKey(attrKey)) {
protSet = attrMap.get(attrKey);
} else {
protSet = new HashSet<>();
attrMap.put(attrKey, protSet);
}
for (String protocol : protocols) {
Validate.notEmpty(protocol);
Protocol prot = Protocol.valueOf(protocol);
protSet.add(prot);
}
return this;
}
/**
Remove allowed URL protocols for an element's URL attribute. If you remove all protocols for an attribute, that
attribute will allow any protocol.
<p>
E.g.: <code>removeProtocols("a", "href", "ftp")</code>
</p>
@param tag Tag the URL protocol is for
@param attribute Attribute name
@param removeProtocols List of invalid protocols
@return this, for chaining
*/
public Safelist removeProtocols(String tag, String attribute, String... removeProtocols) {
Validate.notEmpty(tag);
Validate.notEmpty(attribute);
Validate.notNull(removeProtocols);
TagName tagName = TagName.valueOf(tag);
AttributeKey attr = AttributeKey.valueOf(attribute);
// make sure that what we're removing actually exists; otherwise can open the tag to any data and that can
// be surprising
Validate.isTrue(protocols.containsKey(tagName), "Cannot remove a protocol that is not set.");
Map<AttributeKey, Set<Protocol>> tagProtocols = protocols.get(tagName);
Validate.isTrue(tagProtocols.containsKey(attr), "Cannot remove a protocol that is not set.");
Set<Protocol> attrProtocols = tagProtocols.get(attr);
for (String protocol : removeProtocols) {
Validate.notEmpty(protocol);
attrProtocols.remove(Protocol.valueOf(protocol));
}
if (attrProtocols.isEmpty()) { // Remove protocol set if empty
tagProtocols.remove(attr);
if (tagProtocols.isEmpty()) // Remove entry for tag if empty
protocols.remove(tagName);
}
return this;
}
/**
* Test if the supplied tag is allowed by this safelist
* @param tag test tag
* @return true if allowed
*/
protected boolean isSafeTag(String tag) {
return tagNames.contains(TagName.valueOf(tag));
}
/**
* Test if the supplied attribute is allowed by this safelist for this tag
* @param tagName tag to consider allowing the attribute in
* @param el element under test, to confirm protocol
* @param attr attribute under test
* @return true if allowed
*/
protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
TagName tag = TagName.valueOf(tagName);
AttributeKey key = AttributeKey.valueOf(attr.getKey());
Set<AttributeKey> okSet = attributes.get(tag);
if (okSet != null && okSet.contains(key)) {
if (protocols.containsKey(tag)) {
Map<AttributeKey, Set<Protocol>> attrProts = protocols.get(tag);
// ok if not defined protocol; otherwise test
return !attrProts.containsKey(key) || testValidProtocol(el, attr, attrProts.get(key));
} else { // attribute found, no protocols defined, so OK
return true;
}
}
// might be an enforced attribute?
Map<AttributeKey, AttributeValue> enforcedSet = enforcedAttributes.get(tag);
if (enforcedSet != null) {
Attributes expect = getEnforcedAttributes(tagName);
String attrKey = attr.getKey();
if (expect.hasKeyIgnoreCase(attrKey)) {
return expect.getIgnoreCase(attrKey).equals(attr.getValue());
}
}
// no attributes defined for tag, try :all tag
return !tagName.equals(":all") && isSafeAttribute(":all", el, attr);
}
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 (prot.equals("#")) { // allows anchor links
if (isValidAnchor(value)) {
return true;
} else {
continue;
}
}
prot += ":";
if (lowerCase(value).startsWith(prot)) {
return true;
}
}
return false;
}
private boolean isValidAnchor(String value) {
return value.startsWith("#") && !value.matches(".*\\s.*");
}
Attributes getEnforcedAttributes(String tagName) {
Attributes attrs = new Attributes();
TagName tag = TagName.valueOf(tagName);
if (enforcedAttributes.containsKey(tag)) {
Map<AttributeKey, AttributeValue> keyVals = enforcedAttributes.get(tag);
for (Map.Entry<AttributeKey, AttributeValue> entry : keyVals.entrySet()) {
attrs.put(entry.getKey().toString(), entry.getValue().toString());
}
}
return attrs;
}
// named types for config. All just hold strings, but here for my sanity.
static class TagName extends TypedValue {
TagName(String value) {
super(value);
}
static TagName valueOf(String value) {
return new TagName(value);
}
}
static class AttributeKey extends TypedValue {
AttributeKey(String value) {
super(value);
}
static AttributeKey valueOf(String value) {
return new AttributeKey(value);
}
}
static class AttributeValue extends TypedValue {
AttributeValue(String value) {
super(value);
}
static AttributeValue valueOf(String value) {
return new AttributeValue(value);
}
}
static class Protocol extends TypedValue {
Protocol(String value) {
super(value);
}
static Protocol valueOf(String value) {
return new Protocol(value);
}
}
abstract static class TypedValue {
private String value;
TypedValue(String value) {
Validate.notNull(value);
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
TypedValue other = (TypedValue) obj;
if (value == null) {
return other.value == null;
} else return value.equals(other.value);
}
@Override
public String toString() {
return value;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/safety/Whitelist.java
|
package org.jsoup.safety;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Element;
/**
@deprecated As of release <code>v1.14.1</code>, this class is deprecated in favour of {@link Safelist}. The name has
been changed with the intent of promoting more inclusive language. {@link Safelist} is a drop-in replacement, and no
further changes other than updating the name in your code are required to cleanly migrate. This class will be
removed in <code>v1.15.1</code>. Until that release, this class acts as a shim to maintain code compatibility
(source and binary).
<p>
For a clear rationale of the removal of this change, please see
<a href="https://tools.ietf.org/html/draft-knodel-terminology-04" title="draft-knodel-terminology-04">Terminology,
Power, and Inclusive Language in Internet-Drafts and RFCs</a> */
@Deprecated
public class Whitelist extends Safelist {
public Whitelist() {
super();
}
public Whitelist(Safelist copy) {
super(copy);
}
static public Whitelist basic() {
return new Whitelist(Safelist.basic());
}
static public Whitelist basicWithImages() {
return new Whitelist(Safelist.basicWithImages());
}
static public Whitelist none() {
return new Whitelist(Safelist.none());
}
static public Whitelist relaxed() {
return new Whitelist(Safelist.relaxed());
}
static public Whitelist simpleText() {
return new Whitelist(Safelist.simpleText());
}
@Override
public Whitelist addTags(String... tags) {
super.addTags(tags);
return this;
}
@Override
public Whitelist removeTags(String... tags) {
super.removeTags(tags);
return this;
}
@Override
public Whitelist addAttributes(String tag, String... attributes) {
super.addAttributes(tag, attributes);
return this;
}
@Override
public Whitelist removeAttributes(String tag, String... attributes) {
super.removeAttributes(tag, attributes);
return this;
}
@Override
public Whitelist addEnforcedAttribute(String tag, String attribute, String value) {
super.addEnforcedAttribute(tag, attribute, value);
return this;
}
@Override
public Whitelist removeEnforcedAttribute(String tag, String attribute) {
super.removeEnforcedAttribute(tag, attribute);
return this;
}
@Override
public Whitelist preserveRelativeLinks(boolean preserve) {
super.preserveRelativeLinks(preserve);
return this;
}
@Override
public Whitelist addProtocols(String tag, String attribute, String... protocols) {
super.addProtocols(tag, attribute, protocols);
return this;
}
@Override
public Whitelist removeProtocols(String tag, String attribute, String... removeProtocols) {
super.removeProtocols(tag, attribute, removeProtocols);
return this;
}
@Override
protected boolean isSafeTag(String tag) {
return super.isSafeTag(tag);
}
@Override
protected boolean isSafeAttribute(String tagName, Element el, Attribute attr) {
return super.isSafeAttribute(tagName, el, attr);
}
@Override
Attributes getEnforcedAttributes(String tagName) {
return super.getEnforcedAttributes(tagName);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/safety/package-info.java
|
/**
Contains the jsoup HTML cleaner, and safelist definitions.
*/
package org.jsoup.safety;
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/Collector.java
|
package org.jsoup.select;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import javax.annotation.Nullable;
import static org.jsoup.select.NodeFilter.FilterResult.CONTINUE;
import static org.jsoup.select.NodeFilter.FilterResult.STOP;
/**
* Collects a list of elements that match the supplied criteria.
*
* @author Jonathan Hedley
*/
public class Collector {
private Collector() {}
/**
Build a list of elements, by visiting root and every descendant of root, and testing it against the evaluator.
@param eval Evaluator to test elements against
@param root root of tree to descend
@return list of matches; empty if none
*/
public static Elements collect (Evaluator eval, Element root) {
Elements elements = new Elements();
NodeTraversor.traverse(new Accumulator(root, elements, eval), root);
return elements;
}
private static class Accumulator implements NodeVisitor {
private final Element root;
private final Elements elements;
private final Evaluator eval;
Accumulator(Element root, Elements elements, Evaluator eval) {
this.root = root;
this.elements = elements;
this.eval = eval;
}
public void head(Node node, int depth) {
if (node instanceof Element) {
Element el = (Element) node;
if (eval.matches(root, el))
elements.add(el);
}
}
public void tail(Node node, int depth) {
// void
}
}
/**
Finds the first Element that matches the Evaluator that descends from the root, and stops the query once that first
match is found.
@param eval Evaluator to test elements against
@param root root of tree to descend
@return the first match; {@code null} if none
*/
public static @Nullable Element findFirst(Evaluator eval, Element root) {
FirstFinder finder = new FirstFinder(eval);
return finder.find(root, root);
}
static class FirstFinder implements NodeFilter {
private @Nullable Element evalRoot = null;
private @Nullable Element match = null;
private final Evaluator eval;
FirstFinder(Evaluator eval) {
this.eval = eval;
}
@Nullable Element find(Element root, Element start) {
evalRoot = root;
match = null;
NodeTraversor.filter(this, start);
return match;
}
@Override
public FilterResult head(Node node, int depth) {
if (node instanceof Element) {
Element el = (Element) node;
if (eval.matches(evalRoot, el)) {
match = el;
return STOP;
}
}
return CONTINUE;
}
@Override
public FilterResult tail(Node node, int depth) {
return CONTINUE;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/CombiningEvaluator.java
|
package org.jsoup.select;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Element;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
* Base combining (and, or) evaluator.
*/
public abstract class CombiningEvaluator extends Evaluator {
final ArrayList<Evaluator> evaluators;
int num = 0;
CombiningEvaluator() {
super();
evaluators = new ArrayList<>();
}
CombiningEvaluator(Collection<Evaluator> evaluators) {
this();
this.evaluators.addAll(evaluators);
updateNumEvaluators();
}
@Nullable Evaluator rightMostEvaluator() {
return num > 0 ? evaluators.get(num - 1) : null;
}
void replaceRightMostEvaluator(Evaluator replacement) {
evaluators.set(num - 1, replacement);
}
void updateNumEvaluators() {
// used so we don't need to bash on size() for every match test
num = evaluators.size();
}
public static final class And extends CombiningEvaluator {
And(Collection<Evaluator> evaluators) {
super(evaluators);
}
And(Evaluator... evaluators) {
this(Arrays.asList(evaluators));
}
@Override
public boolean matches(Element root, Element node) {
for (int i = num - 1; i >= 0; i--) { // process backwards so that :matchText is evaled earlier, to catch parent query. todo - should redo matchText to virtually expand during match, not pre-match (see SelectorTest#findBetweenSpan)
Evaluator s = evaluators.get(i);
if (!s.matches(root, node))
return false;
}
return true;
}
@Override
public String toString() {
return StringUtil.join(evaluators, "");
}
}
public static final class Or extends CombiningEvaluator {
/**
* Create a new Or evaluator. The initial evaluators are ANDed together and used as the first clause of the OR.
* @param evaluators initial OR clause (these are wrapped into an AND evaluator).
*/
Or(Collection<Evaluator> evaluators) {
super();
if (num > 1)
this.evaluators.add(new And(evaluators));
else // 0 or 1
this.evaluators.addAll(evaluators);
updateNumEvaluators();
}
Or(Evaluator... evaluators) { this(Arrays.asList(evaluators)); }
Or() {
super();
}
public void add(Evaluator e) {
evaluators.add(e);
updateNumEvaluators();
}
@Override
public boolean matches(Element root, Element node) {
for (int i = 0; i < num; i++) {
Evaluator s = evaluators.get(i);
if (s.matches(root, node))
return true;
}
return false;
}
@Override
public String toString() {
return StringUtil.join(evaluators, ", ");
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/Elements.java
|
package org.jsoup.select;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
/**
A list of {@link Element}s, with methods that act on every element in the list.
<p>
To get an {@code Elements} object, use the {@link Element#select(String)} method.
</p>
@author Jonathan Hedley, jonathan@hedley.net */
public class Elements extends ArrayList<Element> {
public Elements() {
}
public Elements(int initialCapacity) {
super(initialCapacity);
}
public Elements(Collection<Element> elements) {
super(elements);
}
public Elements(List<Element> elements) {
super(elements);
}
public Elements(Element... elements) {
super(Arrays.asList(elements));
}
/**
* Creates a deep copy of these elements.
* @return a deep copy
*/
@Override
public Elements clone() {
Elements clone = new Elements(size());
for(Element e : this)
clone.add(e.clone());
return clone;
}
// attribute methods
/**
Get an attribute value from the first matched element that has the attribute.
@param attributeKey The attribute key.
@return The attribute value from the first matched element that has the attribute.. If no elements were matched (isEmpty() == true),
or if the no elements have the attribute, returns empty string.
@see #hasAttr(String)
*/
public String attr(String attributeKey) {
for (Element element : this) {
if (element.hasAttr(attributeKey))
return element.attr(attributeKey);
}
return "";
}
/**
Checks if any of the matched elements have this attribute defined.
@param attributeKey attribute key
@return true if any of the elements have the attribute; false if none do.
*/
public boolean hasAttr(String attributeKey) {
for (Element element : this) {
if (element.hasAttr(attributeKey))
return true;
}
return false;
}
/**
* Get the attribute value for each of the matched elements. If an element does not have this attribute, no value is
* included in the result set for that element.
* @param attributeKey the attribute name to return values for. You can add the {@code abs:} prefix to the key to
* get absolute URLs from relative URLs, e.g.: {@code doc.select("a").eachAttr("abs:href")} .
* @return a list of each element's attribute value for the attribute
*/
public List<String> eachAttr(String attributeKey) {
List<String> attrs = new ArrayList<>(size());
for (Element element : this) {
if (element.hasAttr(attributeKey))
attrs.add(element.attr(attributeKey));
}
return attrs;
}
/**
* Set an attribute on all matched elements.
* @param attributeKey attribute key
* @param attributeValue attribute value
* @return this
*/
public Elements attr(String attributeKey, String attributeValue) {
for (Element element : this) {
element.attr(attributeKey, attributeValue);
}
return this;
}
/**
* Remove an attribute from every matched element.
* @param attributeKey The attribute to remove.
* @return this (for chaining)
*/
public Elements removeAttr(String attributeKey) {
for (Element element : this) {
element.removeAttr(attributeKey);
}
return this;
}
/**
Add the class name to every matched element's {@code class} attribute.
@param className class name to add
@return this
*/
public Elements addClass(String className) {
for (Element element : this) {
element.addClass(className);
}
return this;
}
/**
Remove the class name from every matched element's {@code class} attribute, if present.
@param className class name to remove
@return this
*/
public Elements removeClass(String className) {
for (Element element : this) {
element.removeClass(className);
}
return this;
}
/**
Toggle the class name on every matched element's {@code class} attribute.
@param className class name to add if missing, or remove if present, from every element.
@return this
*/
public Elements toggleClass(String className) {
for (Element element : this) {
element.toggleClass(className);
}
return this;
}
/**
Determine if any of the matched elements have this class name set in their {@code class} attribute.
@param className class name to check for
@return true if any do, false if none do
*/
public boolean hasClass(String className) {
for (Element element : this) {
if (element.hasClass(className))
return true;
}
return false;
}
/**
* Get the form element's value of the first matched element.
* @return The form element's value, or empty if not set.
* @see Element#val()
*/
public String val() {
if (size() > 0)
//noinspection ConstantConditions
return first().val(); // first() != null as size() > 0
else
return "";
}
/**
* Set the form element's value in each of the matched elements.
* @param value The value to set into each matched element
* @return this (for chaining)
*/
public Elements val(String value) {
for (Element element : this)
element.val(value);
return this;
}
/**
* Get the combined text of all the matched elements.
* <p>
* Note that it is possible to get repeats if the matched elements contain both parent elements and their own
* children, as the Element.text() method returns the combined text of a parent and all its children.
* @return string of all text: unescaped and no HTML.
* @see Element#text()
* @see #eachText()
*/
public String text() {
StringBuilder sb = StringUtil.borrowBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append(" ");
sb.append(element.text());
}
return StringUtil.releaseBuilder(sb);
}
/**
Test if any matched Element has any text content, that is not just whitespace.
@return true if any element has non-blank text content.
@see Element#hasText()
*/
public boolean hasText() {
for (Element element: this) {
if (element.hasText())
return true;
}
return false;
}
/**
* Get the text content of each of the matched elements. If an element has no text, then it is not included in the
* result.
* @return A list of each matched element's text content.
* @see Element#text()
* @see Element#hasText()
* @see #text()
*/
public List<String> eachText() {
ArrayList<String> texts = new ArrayList<>(size());
for (Element el: this) {
if (el.hasText())
texts.add(el.text());
}
return texts;
}
/**
* Get the combined inner HTML of all matched elements.
* @return string of all element's inner HTML.
* @see #text()
* @see #outerHtml()
*/
public String html() {
StringBuilder sb = StringUtil.borrowBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append("\n");
sb.append(element.html());
}
return StringUtil.releaseBuilder(sb);
}
/**
* Get the combined outer HTML of all matched elements.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
public String outerHtml() {
StringBuilder sb = StringUtil.borrowBuilder();
for (Element element : this) {
if (sb.length() != 0)
sb.append("\n");
sb.append(element.outerHtml());
}
return StringUtil.releaseBuilder(sb);
}
/**
* Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}.
* @return string of all element's outer HTML.
* @see #text()
* @see #html()
*/
@Override
public String toString() {
return outerHtml();
}
/**
* Update (rename) the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do
* {@code doc.select("i").tagName("em");}
*
* @param tagName the new tag name
* @return this, for chaining
* @see Element#tagName(String)
*/
public Elements tagName(String tagName) {
for (Element element : this) {
element.tagName(tagName);
}
return this;
}
/**
* Set the inner HTML of each matched element.
* @param html HTML to parse and set into each matched element.
* @return this, for chaining
* @see Element#html(String)
*/
public Elements html(String html) {
for (Element element : this) {
element.html(html);
}
return this;
}
/**
* Add the supplied HTML to the start of each matched element's inner HTML.
* @param html HTML to add inside each element, before the existing HTML
* @return this, for chaining
* @see Element#prepend(String)
*/
public Elements prepend(String html) {
for (Element element : this) {
element.prepend(html);
}
return this;
}
/**
* Add the supplied HTML to the end of each matched element's inner HTML.
* @param html HTML to add inside each element, after the existing HTML
* @return this, for chaining
* @see Element#append(String)
*/
public Elements append(String html) {
for (Element element : this) {
element.append(html);
}
return this;
}
/**
* Insert the supplied HTML before each matched element's outer HTML.
* @param html HTML to insert before each element
* @return this, for chaining
* @see Element#before(String)
*/
public Elements before(String html) {
for (Element element : this) {
element.before(html);
}
return this;
}
/**
* Insert the supplied HTML after each matched element's outer HTML.
* @param html HTML to insert after each element
* @return this, for chaining
* @see Element#after(String)
*/
public Elements after(String html) {
for (Element element : this) {
element.after(html);
}
return this;
}
/**
Wrap the supplied HTML around each matched elements. For example, with HTML
{@code <p><b>This</b> is <b>Jsoup</b></p>},
<code>doc.select("b").wrap("<i></i>");</code>
becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>}
@param html HTML to wrap around each element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep.
@return this (for chaining)
@see Element#wrap
*/
public Elements wrap(String html) {
Validate.notEmpty(html);
for (Element element : this) {
element.wrap(html);
}
return this;
}
/**
* Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of
* dropping the elements but keeping their children.
* <p>
* This is useful for e.g removing unwanted formatting elements but keeping their contents.
* </p>
*
* E.g. with HTML: <p>{@code <div><font>One</font> <font><a href="/">Two</a></font></div>}</p>
* <p>{@code doc.select("font").unwrap();}</p>
* <p>HTML = {@code <div>One <a href="/">Two</a></div>}</p>
*
* @return this (for chaining)
* @see Node#unwrap
*/
public Elements unwrap() {
for (Element element : this) {
element.unwrap();
}
return this;
}
/**
* Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each
* element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br>
* <code>doc.select("p").empty();</code><br>
* HTML = {@code <div><p></p> <p></p></div>}
* @return this, for chaining
* @see Element#empty()
* @see #remove()
*/
public Elements empty() {
for (Element element : this) {
element.empty();
}
return this;
}
/**
* Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing.
* <p>
* E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br>
* <code>doc.select("p").remove();</code><br>
* HTML = {@code <div> <img /></div>}
* <p>
* Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML.
* @return this, for chaining
* @see Element#empty()
* @see #empty()
*/
public Elements remove() {
for (Element element : this) {
element.remove();
}
return this;
}
// filters
/**
* Find matching elements within this element list.
* @param query A {@link Selector} query
* @return the filtered list of elements, or an empty list if none match.
*/
public Elements select(String query) {
return Selector.select(query, this);
}
/**
* Remove elements from this list that match the {@link Selector} query.
* <p>
* E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br>
* <code>Elements divs = doc.select("div").not(".logo");</code><br>
* Result: {@code divs: [<div>Two</div>]}
* <p>
* @param query the selector query whose results should be removed from these elements
* @return a new elements list that contains only the filtered results
*/
public Elements not(String query) {
Elements out = Selector.select(query, this);
return Selector.filterOut(this, out);
}
/**
* Get the <i>nth</i> matched element as an Elements object.
* <p>
* See also {@link #get(int)} to retrieve an Element.
* @param index the (zero-based) index of the element in the list to retain
* @return Elements containing only the specified element, or, if that element did not exist, an empty list.
*/
public Elements eq(int index) {
return size() > index ? new Elements(get(index)) : new Elements();
}
/**
* Test if any of the matched elements match the supplied query.
* @param query A selector
* @return true if at least one element in the list matches the query.
*/
public boolean is(String query) {
Evaluator eval = QueryParser.parse(query);
for (Element e : this) {
if (e.is(eval))
return true;
}
return false;
}
/**
* Get the immediate next element sibling of each element in this list.
* @return next element siblings.
*/
public Elements next() {
return siblings(null, true, false);
}
/**
* Get the immediate next element sibling of each element in this list, filtered by the query.
* @param query CSS query to match siblings against
* @return next element siblings.
*/
public Elements next(String query) {
return siblings(query, true, false);
}
/**
* Get each of the following element siblings of each element in this list.
* @return all following element siblings.
*/
public Elements nextAll() {
return siblings(null, true, true);
}
/**
* Get each of the following element siblings of each element in this list, that match the query.
* @param query CSS query to match siblings against
* @return all following element siblings.
*/
public Elements nextAll(String query) {
return siblings(query, true, true);
}
/**
* Get the immediate previous element sibling of each element in this list.
* @return previous element siblings.
*/
public Elements prev() {
return siblings(null, false, false);
}
/**
* Get the immediate previous element sibling of each element in this list, filtered by the query.
* @param query CSS query to match siblings against
* @return previous element siblings.
*/
public Elements prev(String query) {
return siblings(query, false, false);
}
/**
* Get each of the previous element siblings of each element in this list.
* @return all previous element siblings.
*/
public Elements prevAll() {
return siblings(null, false, true);
}
/**
* Get each of the previous element siblings of each element in this list, that match the query.
* @param query CSS query to match siblings against
* @return all previous element siblings.
*/
public Elements prevAll(String query) {
return siblings(query, false, true);
}
private Elements siblings(@Nullable String query, boolean next, boolean all) {
Elements els = new Elements();
Evaluator eval = query != null? QueryParser.parse(query) : null;
for (Element e : this) {
do {
Element sib = next ? e.nextElementSibling() : e.previousElementSibling();
if (sib == null) break;
if (eval == null)
els.add(sib);
else if (sib.is(eval))
els.add(sib);
e = sib;
} while (all);
}
return els;
}
/**
* Get all of the parents and ancestor elements of the matched elements.
* @return all of the parents and ancestor elements of the matched elements
*/
public Elements parents() {
HashSet<Element> combo = new LinkedHashSet<>();
for (Element e: this) {
combo.addAll(e.parents());
}
return new Elements(combo);
}
// list-like methods
/**
Get the first matched element.
@return The first matched element, or <code>null</code> if contents is empty.
*/
public @Nullable Element first() {
return isEmpty() ? null : get(0);
}
/**
Get the last matched element.
@return The last matched element, or <code>null</code> if contents is empty.
*/
public @Nullable Element last() {
return isEmpty() ? null : get(size() - 1);
}
/**
* Perform a depth-first traversal on each of the selected elements.
* @param nodeVisitor the visitor callbacks to perform on each node
* @return this, for chaining
*/
public Elements traverse(NodeVisitor nodeVisitor) {
NodeTraversor.traverse(nodeVisitor, this);
return this;
}
/**
* Perform a depth-first filtering on each of the selected elements.
* @param nodeFilter the filter callbacks to perform on each node
* @return this, for chaining
*/
public Elements filter(NodeFilter nodeFilter) {
NodeTraversor.filter(nodeFilter, this);
return this;
}
/**
* Get the {@link FormElement} forms from the selected elements, if any.
* @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain
* no forms.
*/
public List<FormElement> forms() {
ArrayList<FormElement> forms = new ArrayList<>();
for (Element el: this)
if (el instanceof FormElement)
forms.add((FormElement) el);
return forms;
}
/**
* Get {@link Comment} nodes that are direct child nodes of the selected elements.
* @return Comment nodes, or an empty list if none.
*/
public List<Comment> comments() {
return childNodesOfType(Comment.class);
}
/**
* Get {@link TextNode} nodes that are direct child nodes of the selected elements.
* @return TextNode nodes, or an empty list if none.
*/
public List<TextNode> textNodes() {
return childNodesOfType(TextNode.class);
}
/**
* Get {@link DataNode} nodes that are direct child nodes of the selected elements. DataNode nodes contain the
* content of tags such as {@code script}, {@code style} etc and are distinct from {@link TextNode}s.
* @return Comment nodes, or an empty list if none.
*/
public List<DataNode> dataNodes() {
return childNodesOfType(DataNode.class);
}
private <T extends Node> List<T> childNodesOfType(Class<T> tClass) {
ArrayList<T> nodes = new ArrayList<>();
for (Element el: this) {
for (int i = 0; i < el.childNodeSize(); i++) {
Node node = el.childNode(i);
if (tClass.isInstance(node))
nodes.add(tClass.cast(node));
}
}
return nodes;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/Evaluator.java
|
package org.jsoup.select;
import org.jsoup.helper.Validate;
import org.jsoup.internal.StringUtil;
import org.jsoup.nodes.Comment;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.DocumentType;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.PseudoTextElement;
import org.jsoup.nodes.TextNode;
import org.jsoup.nodes.XmlDeclaration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jsoup.internal.Normalizer.lowerCase;
import static org.jsoup.internal.Normalizer.normalize;
import static org.jsoup.internal.StringUtil.normaliseWhitespace;
/**
* Evaluates that an element matches the selector.
*/
public abstract class Evaluator {
protected Evaluator() {
}
/**
* Test if the element meets the evaluator's requirements.
*
* @param root Root of the matching subtree
* @param element tested element
* @return Returns <tt>true</tt> if the requirements are met or
* <tt>false</tt> otherwise
*/
public abstract boolean matches(Element root, Element element);
/**
* Evaluator for tag name
*/
public static final class Tag extends Evaluator {
private final String tagName;
public Tag(String tagName) {
this.tagName = tagName;
}
@Override
public boolean matches(Element root, Element element) {
return (element.normalName().equals(tagName));
}
@Override
public String toString() {
return String.format("%s", tagName);
}
}
/**
* Evaluator for tag name that ends with
*/
public static final class TagEndsWith extends Evaluator {
private final String tagName;
public TagEndsWith(String tagName) {
this.tagName = tagName;
}
@Override
public boolean matches(Element root, Element element) {
return (element.normalName().endsWith(tagName));
}
@Override
public String toString() {
return String.format("%s", tagName);
}
}
/**
* Evaluator for element id
*/
public static final class Id extends Evaluator {
private final String id;
public Id(String id) {
this.id = id;
}
@Override
public boolean matches(Element root, Element element) {
return (id.equals(element.id()));
}
@Override
public String toString() {
return String.format("#%s", id);
}
}
/**
* Evaluator for element class
*/
public static final class Class extends Evaluator {
private final String className;
public Class(String className) {
this.className = className;
}
@Override
public boolean matches(Element root, Element element) {
return (element.hasClass(className));
}
@Override
public String toString() {
return String.format(".%s", className);
}
}
/**
* Evaluator for attribute name matching
*/
public static final class Attribute extends Evaluator {
private final String key;
public Attribute(String key) {
this.key = key;
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key);
}
@Override
public String toString() {
return String.format("[%s]", key);
}
}
/**
* Evaluator for attribute name prefix matching
*/
public static final class AttributeStarting extends Evaluator {
private final String keyPrefix;
public AttributeStarting(String keyPrefix) {
Validate.notEmpty(keyPrefix);
this.keyPrefix = lowerCase(keyPrefix);
}
@Override
public boolean matches(Element root, Element element) {
List<org.jsoup.nodes.Attribute> values = element.attributes().asList();
for (org.jsoup.nodes.Attribute attribute : values) {
if (lowerCase(attribute.getKey()).startsWith(keyPrefix))
return true;
}
return false;
}
@Override
public String toString() {
return String.format("[^%s]", keyPrefix);
}
}
/**
* Evaluator for attribute name/value matching
*/
public static final class AttributeWithValue extends AttributeKeyPair {
public AttributeWithValue(String key, String value) {
super(key, value);
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && value.equalsIgnoreCase(element.attr(key).trim());
}
@Override
public String toString() {
return String.format("[%s=%s]", key, value);
}
}
/**
* Evaluator for attribute name != value matching
*/
public static final class AttributeWithValueNot extends AttributeKeyPair {
public AttributeWithValueNot(String key, String value) {
super(key, value);
}
@Override
public boolean matches(Element root, Element element) {
return !value.equalsIgnoreCase(element.attr(key));
}
@Override
public String toString() {
return String.format("[%s!=%s]", key, value);
}
}
/**
* Evaluator for attribute name/value matching (value prefix)
*/
public static final class AttributeWithValueStarting extends AttributeKeyPair {
public AttributeWithValueStarting(String key, String value) {
super(key, value, false);
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && lowerCase(element.attr(key)).startsWith(value); // value is lower case already
}
@Override
public String toString() {
return String.format("[%s^=%s]", key, value);
}
}
/**
* Evaluator for attribute name/value matching (value ending)
*/
public static final class AttributeWithValueEnding extends AttributeKeyPair {
public AttributeWithValueEnding(String key, String value) {
super(key, value, false);
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && lowerCase(element.attr(key)).endsWith(value); // value is lower case
}
@Override
public String toString() {
return String.format("[%s$=%s]", key, value);
}
}
/**
* Evaluator for attribute name/value matching (value containing)
*/
public static final class AttributeWithValueContaining extends AttributeKeyPair {
public AttributeWithValueContaining(String key, String value) {
super(key, value);
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && lowerCase(element.attr(key)).contains(value); // value is lower case
}
@Override
public String toString() {
return String.format("[%s*=%s]", key, value);
}
}
/**
* Evaluator for attribute name/value matching (value regex matching)
*/
public static final class AttributeWithValueMatching extends Evaluator {
String key;
Pattern pattern;
public AttributeWithValueMatching(String key, Pattern pattern) {
this.key = normalize(key);
this.pattern = pattern;
}
@Override
public boolean matches(Element root, Element element) {
return element.hasAttr(key) && pattern.matcher(element.attr(key)).find();
}
@Override
public String toString() {
return String.format("[%s~=%s]", key, pattern.toString());
}
}
/**
* Abstract evaluator for attribute name/value matching
*/
public abstract static class AttributeKeyPair extends Evaluator {
String key;
String value;
public AttributeKeyPair(String key, String value) {
this(key, value, true);
}
public AttributeKeyPair(String key, String value, boolean trimValue) {
Validate.notEmpty(key);
Validate.notEmpty(value);
this.key = normalize(key);
boolean isStringLiteral = value.startsWith("'") && value.endsWith("'")
|| value.startsWith("\"") && value.endsWith("\"");
if (isStringLiteral) {
value = value.substring(1, value.length()-1);
}
this.value = trimValue ? normalize(value) : normalize(value, isStringLiteral);
}
}
/**
* Evaluator for any / all element matching
*/
public static final class AllElements extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
return true;
}
@Override
public String toString() {
return "*";
}
}
/**
* Evaluator for matching by sibling index number (e {@literal <} idx)
*/
public static final class IndexLessThan extends IndexEvaluator {
public IndexLessThan(int index) {
super(index);
}
@Override
public boolean matches(Element root, Element element) {
return root != element && element.elementSiblingIndex() < index;
}
@Override
public String toString() {
return String.format(":lt(%d)", index);
}
}
/**
* Evaluator for matching by sibling index number (e {@literal >} idx)
*/
public static final class IndexGreaterThan extends IndexEvaluator {
public IndexGreaterThan(int index) {
super(index);
}
@Override
public boolean matches(Element root, Element element) {
return element.elementSiblingIndex() > index;
}
@Override
public String toString() {
return String.format(":gt(%d)", index);
}
}
/**
* Evaluator for matching by sibling index number (e = idx)
*/
public static final class IndexEquals extends IndexEvaluator {
public IndexEquals(int index) {
super(index);
}
@Override
public boolean matches(Element root, Element element) {
return element.elementSiblingIndex() == index;
}
@Override
public String toString() {
return String.format(":eq(%d)", index);
}
}
/**
* Evaluator for matching the last sibling (css :last-child)
*/
public static final class IsLastChild extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
final Element p = element.parent();
return p != null && !(p instanceof Document) && element.elementSiblingIndex() == p.children().size()-1;
}
@Override
public String toString() {
return ":last-child";
}
}
public static final class IsFirstOfType extends IsNthOfType {
public IsFirstOfType() {
super(0,1);
}
@Override
public String toString() {
return ":first-of-type";
}
}
public static final class IsLastOfType extends IsNthLastOfType {
public IsLastOfType() {
super(0,1);
}
@Override
public String toString() {
return ":last-of-type";
}
}
public static abstract class CssNthEvaluator extends Evaluator {
protected final int a, b;
public CssNthEvaluator(int a, int b) {
this.a = a;
this.b = b;
}
public CssNthEvaluator(int b) {
this(0,b);
}
@Override
public boolean matches(Element root, Element element) {
final Element p = element.parent();
if (p == null || (p instanceof Document)) return false;
final int pos = calculatePosition(root, element);
if (a == 0) return pos == b;
return (pos-b)*a >= 0 && (pos-b)%a==0;
}
@Override
public String toString() {
if (a == 0)
return String.format(":%s(%d)",getPseudoClass(), b);
if (b == 0)
return String.format(":%s(%dn)",getPseudoClass(), a);
return String.format(":%s(%dn%+d)", getPseudoClass(),a, b);
}
protected abstract String getPseudoClass();
protected abstract int calculatePosition(Element root, Element element);
}
/**
* css-compatible Evaluator for :eq (css :nth-child)
*
* @see IndexEquals
*/
public static final class IsNthChild extends CssNthEvaluator {
public IsNthChild(int a, int b) {
super(a,b);
}
protected int calculatePosition(Element root, Element element) {
return element.elementSiblingIndex()+1;
}
protected String getPseudoClass() {
return "nth-child";
}
}
/**
* css pseudo class :nth-last-child)
*
* @see IndexEquals
*/
public static final class IsNthLastChild extends CssNthEvaluator {
public IsNthLastChild(int a, int b) {
super(a,b);
}
@Override
protected int calculatePosition(Element root, Element element) {
if (element.parent() == null)
return 0;
return element.parent().children().size() - element.elementSiblingIndex();
}
@Override
protected String getPseudoClass() {
return "nth-last-child";
}
}
/**
* css pseudo class nth-of-type
*
*/
public static class IsNthOfType extends CssNthEvaluator {
public IsNthOfType(int a, int b) {
super(a,b);
}
protected int calculatePosition(Element root, Element element) {
int pos = 0;
if (element.parent() == null)
return 0;
Elements family = element.parent().children();
for (Element el : family) {
if (el.tag().equals(element.tag())) pos++;
if (el == element) break;
}
return pos;
}
@Override
protected String getPseudoClass() {
return "nth-of-type";
}
}
public static class IsNthLastOfType extends CssNthEvaluator {
public IsNthLastOfType(int a, int b) {
super(a, b);
}
@Override
protected int calculatePosition(Element root, Element element) {
int pos = 0;
if (element.parent() == null)
return 0;
Elements family = element.parent().children();
for (int i = element.elementSiblingIndex(); i < family.size(); i++) {
if (family.get(i).tag().equals(element.tag())) pos++;
}
return pos;
}
@Override
protected String getPseudoClass() {
return "nth-last-of-type";
}
}
/**
* Evaluator for matching the first sibling (css :first-child)
*/
public static final class IsFirstChild extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
final Element p = element.parent();
return p != null && !(p instanceof Document) && element.elementSiblingIndex() == 0;
}
@Override
public String toString() {
return ":first-child";
}
}
/**
* css3 pseudo-class :root
* @see <a href="http://www.w3.org/TR/selectors/#root-pseudo">:root selector</a>
*
*/
public static final class IsRoot extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
final Element r = root instanceof Document?root.child(0):root;
return element == r;
}
@Override
public String toString() {
return ":root";
}
}
public static final class IsOnlyChild extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
final Element p = element.parent();
return p!=null && !(p instanceof Document) && element.siblingElements().isEmpty();
}
@Override
public String toString() {
return ":only-child";
}
}
public static final class IsOnlyOfType extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
final Element p = element.parent();
if (p==null || p instanceof Document) return false;
int pos = 0;
Elements family = p.children();
for (Element el : family) {
if (el.tag().equals(element.tag())) pos++;
}
return pos == 1;
}
@Override
public String toString() {
return ":only-of-type";
}
}
public static final class IsEmpty extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
List<Node> family = element.childNodes();
for (Node n : family) {
if (!(n instanceof Comment || n instanceof XmlDeclaration || n instanceof DocumentType)) return false;
}
return true;
}
@Override
public String toString() {
return ":empty";
}
}
/**
* Abstract evaluator for sibling index matching
*
* @author ant
*/
public abstract static class IndexEvaluator extends Evaluator {
int index;
public IndexEvaluator(int index) {
this.index = index;
}
}
/**
* Evaluator for matching Element (and its descendants) text
*/
public static final class ContainsText extends Evaluator {
private final String searchText;
public ContainsText(String searchText) {
this.searchText = lowerCase(normaliseWhitespace(searchText));
}
@Override
public boolean matches(Element root, Element element) {
return lowerCase(element.text()).contains(searchText);
}
@Override
public String toString() {
return String.format(":contains(%s)", searchText);
}
}
/**
* Evaluator for matching Element (and its descendants) data
*/
public static final class ContainsData extends Evaluator {
private final String searchText;
public ContainsData(String searchText) {
this.searchText = lowerCase(searchText);
}
@Override
public boolean matches(Element root, Element element) {
return lowerCase(element.data()).contains(searchText); // not whitespace normalized
}
@Override
public String toString() {
return String.format(":containsData(%s)", searchText);
}
}
/**
* Evaluator for matching Element's own text
*/
public static final class ContainsOwnText extends Evaluator {
private final String searchText;
public ContainsOwnText(String searchText) {
this.searchText = lowerCase(normaliseWhitespace(searchText));
}
@Override
public boolean matches(Element root, Element element) {
return lowerCase(element.ownText()).contains(searchText);
}
@Override
public String toString() {
return String.format(":containsOwn(%s)", searchText);
}
}
/**
* Evaluator for matching Element (and its descendants) text with regex
*/
public static final class Matches extends Evaluator {
private final Pattern pattern;
public Matches(Pattern pattern) {
this.pattern = pattern;
}
@Override
public boolean matches(Element root, Element element) {
Matcher m = pattern.matcher(element.text());
return m.find();
}
@Override
public String toString() {
return String.format(":matches(%s)", pattern);
}
}
/**
* Evaluator for matching Element's own text with regex
*/
public static final class MatchesOwn extends Evaluator {
private final Pattern pattern;
public MatchesOwn(Pattern pattern) {
this.pattern = pattern;
}
@Override
public boolean matches(Element root, Element element) {
Matcher m = pattern.matcher(element.ownText());
return m.find();
}
@Override
public String toString() {
return String.format(":matchesOwn(%s)", pattern);
}
}
public static final class MatchText extends Evaluator {
@Override
public boolean matches(Element root, Element element) {
if (element instanceof PseudoTextElement)
return true;
List<TextNode> textNodes = element.textNodes();
for (TextNode textNode : textNodes) {
PseudoTextElement pel = new PseudoTextElement(
org.jsoup.parser.Tag.valueOf(element.tagName()), element.baseUri(), element.attributes());
textNode.replaceWith(pel);
pel.appendChild(textNode);
}
return false;
}
@Override
public String toString() {
return ":matchText";
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/NodeFilter.java
|
package org.jsoup.select;
import org.jsoup.nodes.Node;
/**
* Node filter interface. Provide an implementing class to {@link NodeTraversor} to iterate through nodes.
* <p>
* This interface provides two methods, {@code head} and {@code tail}. The head method is called when the node is first
* seen, and the tail method when all of the node's children have been visited. As an example, head can be used to
* create a start tag for a node, and tail to create the end tag.
* </p>
* <p>
* For every node, the filter has to decide whether to
* <ul>
* <li>continue ({@link FilterResult#CONTINUE}),</li>
* <li>skip all children ({@link FilterResult#SKIP_CHILDREN}),</li>
* <li>skip node entirely ({@link FilterResult#SKIP_ENTIRELY}),</li>
* <li>remove the subtree ({@link FilterResult#REMOVE}),</li>
* <li>interrupt the iteration and return ({@link FilterResult#STOP}).</li>
* </ul>
* The difference between {@link FilterResult#SKIP_CHILDREN} and {@link FilterResult#SKIP_ENTIRELY} is that the first
* will invoke {@link NodeFilter#tail(Node, int)} on the node, while the latter will not.
* Within {@link NodeFilter#tail(Node, int)}, both are equivalent to {@link FilterResult#CONTINUE}.
* </p>
*/
public interface NodeFilter {
/**
* Filter decision.
*/
enum FilterResult {
/** Continue processing the tree */
CONTINUE,
/** Skip the child nodes, but do call {@link NodeFilter#tail(Node, int)} next. */
SKIP_CHILDREN,
/** Skip the subtree, and do not call {@link NodeFilter#tail(Node, int)}. */
SKIP_ENTIRELY,
/** Remove the node and its children */
REMOVE,
/** Stop processing */
STOP
}
/**
* Callback for when a node is first visited.
* @param node the node being visited.
* @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node of that will have depth 1.
* @return Filter decision
*/
default FilterResult head(Node node, int depth) {
return FilterResult.CONTINUE;
}
/**
* Callback for when a node is last visited, after all of its descendants have been visited.
* @param node the node being visited.
* @param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node of that will have depth 1.
* @return Filter decision
*/
default FilterResult tail(Node node, int depth) {
return FilterResult.CONTINUE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/NodeTraversor.java
|
package org.jsoup.select;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeFilter.FilterResult;
/**
* Depth-first node traversor. Use to iterate through all nodes under and including the specified root node.
* <p>
* This implementation does not use recursion, so a deep DOM does not risk blowing the stack.
* </p>
*/
public class NodeTraversor {
/**
* Start a depth-first traverse of the root and all of its descendants.
* @param visitor Node visitor.
* @param root the root node point to traverse.
*/
public static void traverse(NodeVisitor visitor, Node root) {
Validate.notNull(visitor);
Validate.notNull(root);
Node node = root;
Node parent; // remember parent to find nodes that get replaced in .head
int depth = 0;
while (node != null) {
parent = node.parentNode();
visitor.head(node, depth); // visit current node
if (parent != null && !node.hasParent()) // must have been replaced; find replacement
node = parent.childNode(node.siblingIndex()); // replace ditches parent but keeps sibling index
if (node.childNodeSize() > 0) { // descend
node = node.childNode(0);
depth++;
} else {
while (true) {
assert node != null; // as depth > 0, will have parent
if (!(node.nextSibling() == null && depth > 0)) break;
visitor.tail(node, depth); // when no more siblings, ascend
node = node.parentNode();
depth--;
}
visitor.tail(node, depth);
if (node == root)
break;
node = node.nextSibling();
}
}
}
/**
* Start a depth-first traverse of all elements.
* @param visitor Node visitor.
* @param elements Elements to filter.
*/
public static void traverse(NodeVisitor visitor, Elements elements) {
Validate.notNull(visitor);
Validate.notNull(elements);
for (Element el : elements)
traverse(visitor, el);
}
/**
* Start a depth-first filtering of the root and all of its descendants.
* @param filter Node visitor.
* @param root the root node point to traverse.
* @return The filter result of the root node, or {@link FilterResult#STOP}.
*/
public static FilterResult filter(NodeFilter filter, Node root) {
Node node = root;
int depth = 0;
while (node != null) {
FilterResult result = filter.head(node, depth);
if (result == FilterResult.STOP)
return result;
// Descend into child nodes:
if (result == FilterResult.CONTINUE && node.childNodeSize() > 0) {
node = node.childNode(0);
++depth;
continue;
}
// No siblings, move upwards:
while (true) {
assert node != null; // depth > 0, so has parent
if (!(node.nextSibling() == null && depth > 0)) break;
// 'tail' current node:
if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) {
result = filter.tail(node, depth);
if (result == FilterResult.STOP)
return result;
}
Node prev = node; // In case we need to remove it below.
node = node.parentNode();
depth--;
if (result == FilterResult.REMOVE)
prev.remove(); // Remove AFTER finding parent.
result = FilterResult.CONTINUE; // Parent was not pruned.
}
// 'tail' current node, then proceed with siblings:
if (result == FilterResult.CONTINUE || result == FilterResult.SKIP_CHILDREN) {
result = filter.tail(node, depth);
if (result == FilterResult.STOP)
return result;
}
if (node == root)
return result;
Node prev = node; // In case we need to remove it below.
node = node.nextSibling();
if (result == FilterResult.REMOVE)
prev.remove(); // Remove AFTER finding sibling.
}
// root == null?
return FilterResult.CONTINUE;
}
/**
* Start a depth-first filtering of all elements.
* @param filter Node filter.
* @param elements Elements to filter.
*/
public static void filter(NodeFilter filter, Elements elements) {
Validate.notNull(filter);
Validate.notNull(elements);
for (Element el : elements)
if (filter(filter, el) == FilterResult.STOP)
break;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/NodeVisitor.java
|
package org.jsoup.select;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
/**
* Node visitor interface. Provide an implementing class to {@link NodeTraversor} to iterate through nodes.
* <p>
* This interface provides two methods, {@code head} and {@code tail}. The head method is called when the node is first
* seen, and the tail method when all of the node's children have been visited. As an example, {@code head} can be used to
* emit a start tag for a node, and {@code tail} to create the end tag.
* </p>
*/
public interface NodeVisitor {
/**
Callback for when a node is first visited.
<p>The node may be modified (e.g. {@link Node#attr(String)} or replaced {@link Node#replaceWith(Node)}). If it's
{@code instanceOf Element}, you may cast it to an {@link Element} and access those methods.</p>
<p>Note that nodes may not be removed during traversal using this method; use {@link
NodeTraversor#filter(NodeFilter, Node)} with a {@link NodeFilter.FilterResult#REMOVE} return instead.</p>
@param node the node being visited.
@param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node
of that will have depth 1.
*/
void head(Node node, int depth);
/**
Callback for when a node is last visited, after all of its descendants have been visited.
<p>Note that replacement with {@link Node#replaceWith(Node)}</p> is not supported in {@code tail}.
@param node the node being visited.
@param depth the depth of the node, relative to the root node. E.g., the root node has depth 0, and a child node
of that will have depth 1.
*/
default void tail(Node node, int depth) {}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/QueryParser.java
|
package org.jsoup.select;
import org.jsoup.internal.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.TokenQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.jsoup.internal.Normalizer.normalize;
/**
* Parses a CSS selector into an Evaluator tree.
*/
public class QueryParser {
private final static String[] combinators = {",", ">", "+", "~", " "};
private static final String[] AttributeEvals = new String[]{"=", "!=", "^=", "$=", "*=", "~="};
private final TokenQueue tq;
private final String query;
private final List<Evaluator> evals = new ArrayList<>();
/**
* Create a new QueryParser.
* @param query CSS query
*/
private QueryParser(String query) {
Validate.notEmpty(query);
query = query.trim();
this.query = query;
this.tq = new TokenQueue(query);
}
/**
* Parse a CSS query into an Evaluator.
* @param query CSS query
* @return Evaluator
* @see Selector selector query syntax
*/
public static Evaluator parse(String query) {
try {
QueryParser p = new QueryParser(query);
return p.parse();
} catch (IllegalArgumentException e) {
throw new Selector.SelectorParseException(e.getMessage());
}
}
/**
* Parse the query
* @return Evaluator
*/
Evaluator parse() {
tq.consumeWhitespace();
if (tq.matchesAny(combinators)) { // if starts with a combinator, use root as elements
evals.add(new StructuralEvaluator.Root());
combinator(tq.consume());
} else {
findElements();
}
while (!tq.isEmpty()) {
// hierarchy and extras
boolean seenWhite = tq.consumeWhitespace();
if (tq.matchesAny(combinators)) {
combinator(tq.consume());
} else if (seenWhite) {
combinator(' ');
} else { // E.class, E#id, E[attr] etc. AND
findElements(); // take next el, #. etc off queue
}
}
if (evals.size() == 1)
return evals.get(0);
return new CombiningEvaluator.And(evals);
}
private void combinator(char combinator) {
tq.consumeWhitespace();
String subQuery = consumeSubQuery(); // support multi > childs
Evaluator rootEval; // the new topmost evaluator
Evaluator currentEval; // the evaluator the new eval will be combined to. could be root, or rightmost or.
Evaluator newEval = parse(subQuery); // the evaluator to add into target evaluator
boolean replaceRightMost = false;
if (evals.size() == 1) {
rootEval = currentEval = evals.get(0);
// make sure OR (,) has precedence:
if (rootEval instanceof CombiningEvaluator.Or && combinator != ',') {
currentEval = ((CombiningEvaluator.Or) currentEval).rightMostEvaluator();
assert currentEval != null; // rightMost signature can return null (if none set), but always will have one by this point
replaceRightMost = true;
}
}
else {
rootEval = currentEval = new CombiningEvaluator.And(evals);
}
evals.clear();
// for most combinators: change the current eval into an AND of the current eval and the new eval
switch (combinator) {
case '>':
currentEval = new CombiningEvaluator.And(new StructuralEvaluator.ImmediateParent(currentEval), newEval);
break;
case ' ':
currentEval = new CombiningEvaluator.And(new StructuralEvaluator.Parent(currentEval), newEval);
break;
case '+':
currentEval = new CombiningEvaluator.And(new StructuralEvaluator.ImmediatePreviousSibling(currentEval), newEval);
break;
case '~':
currentEval = new CombiningEvaluator.And(new StructuralEvaluator.PreviousSibling(currentEval), newEval);
break;
case ',':
CombiningEvaluator.Or or;
if (currentEval instanceof CombiningEvaluator.Or) {
or = (CombiningEvaluator.Or) currentEval;
} else {
or = new CombiningEvaluator.Or();
or.add(currentEval);
}
or.add(newEval);
currentEval = or;
break;
default:
throw new Selector.SelectorParseException("Unknown combinator: " + combinator);
}
if (replaceRightMost)
((CombiningEvaluator.Or) rootEval).replaceRightMostEvaluator(currentEval);
else rootEval = currentEval;
evals.add(rootEval);
}
private String consumeSubQuery() {
StringBuilder sq = StringUtil.borrowBuilder();
while (!tq.isEmpty()) {
if (tq.matches("("))
sq.append("(").append(tq.chompBalanced('(', ')')).append(")");
else if (tq.matches("["))
sq.append("[").append(tq.chompBalanced('[', ']')).append("]");
else if (tq.matchesAny(combinators))
if (sq.length() > 0)
break;
else
tq.consume();
else
sq.append(tq.consume());
}
return StringUtil.releaseBuilder(sq);
}
private void findElements() {
if (tq.matchChomp("#"))
byId();
else if (tq.matchChomp("."))
byClass();
else if (tq.matchesWord() || tq.matches("*|"))
byTag();
else if (tq.matches("["))
byAttribute();
else if (tq.matchChomp("*"))
allElements();
else if (tq.matchChomp(":lt("))
indexLessThan();
else if (tq.matchChomp(":gt("))
indexGreaterThan();
else if (tq.matchChomp(":eq("))
indexEquals();
else if (tq.matches(":has("))
has();
else if (tq.matches(":contains("))
contains(false);
else if (tq.matches(":containsOwn("))
contains(true);
else if (tq.matches(":containsData("))
containsData();
else if (tq.matches(":matches("))
matches(false);
else if (tq.matches(":matchesOwn("))
matches(true);
else if (tq.matches(":not("))
not();
else if (tq.matchChomp(":nth-child("))
cssNthChild(false, false);
else if (tq.matchChomp(":nth-last-child("))
cssNthChild(true, false);
else if (tq.matchChomp(":nth-of-type("))
cssNthChild(false, true);
else if (tq.matchChomp(":nth-last-of-type("))
cssNthChild(true, true);
else if (tq.matchChomp(":first-child"))
evals.add(new Evaluator.IsFirstChild());
else if (tq.matchChomp(":last-child"))
evals.add(new Evaluator.IsLastChild());
else if (tq.matchChomp(":first-of-type"))
evals.add(new Evaluator.IsFirstOfType());
else if (tq.matchChomp(":last-of-type"))
evals.add(new Evaluator.IsLastOfType());
else if (tq.matchChomp(":only-child"))
evals.add(new Evaluator.IsOnlyChild());
else if (tq.matchChomp(":only-of-type"))
evals.add(new Evaluator.IsOnlyOfType());
else if (tq.matchChomp(":empty"))
evals.add(new Evaluator.IsEmpty());
else if (tq.matchChomp(":root"))
evals.add(new Evaluator.IsRoot());
else if (tq.matchChomp(":matchText"))
evals.add(new Evaluator.MatchText());
else // unhandled
throw new Selector.SelectorParseException("Could not parse query '%s': unexpected token at '%s'", query, tq.remainder());
}
private void byId() {
String id = tq.consumeCssIdentifier();
Validate.notEmpty(id);
evals.add(new Evaluator.Id(id));
}
private void byClass() {
String className = tq.consumeCssIdentifier();
Validate.notEmpty(className);
evals.add(new Evaluator.Class(className.trim()));
}
private void byTag() {
// todo - these aren't dealing perfectly with case sensitivity. For case sensitive parsers, we should also make
// the tag in the selector case-sensitive (and also attribute names). But for now, normalize (lower-case) for
// consistency - both the selector and the element tag
String tagName = normalize(tq.consumeElementSelector());
Validate.notEmpty(tagName);
// namespaces: wildcard match equals(tagName) or ending in ":"+tagName
if (tagName.startsWith("*|")) {
String plainTag = tagName.substring(2); // strip *|
evals.add(new CombiningEvaluator.Or(
new Evaluator.Tag(plainTag),
new Evaluator.TagEndsWith(tagName.replace("*|", ":")))
);
} else {
// namespaces: if element name is "abc:def", selector must be "abc|def", so flip:
if (tagName.contains("|"))
tagName = tagName.replace("|", ":");
evals.add(new Evaluator.Tag(tagName));
}
}
private void byAttribute() {
TokenQueue cq = new TokenQueue(tq.chompBalanced('[', ']')); // content queue
String key = cq.consumeToAny(AttributeEvals); // eq, not, start, end, contain, match, (no val)
Validate.notEmpty(key);
cq.consumeWhitespace();
if (cq.isEmpty()) {
if (key.startsWith("^"))
evals.add(new Evaluator.AttributeStarting(key.substring(1)));
else
evals.add(new Evaluator.Attribute(key));
} else {
if (cq.matchChomp("="))
evals.add(new Evaluator.AttributeWithValue(key, cq.remainder()));
else if (cq.matchChomp("!="))
evals.add(new Evaluator.AttributeWithValueNot(key, cq.remainder()));
else if (cq.matchChomp("^="))
evals.add(new Evaluator.AttributeWithValueStarting(key, cq.remainder()));
else if (cq.matchChomp("$="))
evals.add(new Evaluator.AttributeWithValueEnding(key, cq.remainder()));
else if (cq.matchChomp("*="))
evals.add(new Evaluator.AttributeWithValueContaining(key, cq.remainder()));
else if (cq.matchChomp("~="))
evals.add(new Evaluator.AttributeWithValueMatching(key, Pattern.compile(cq.remainder())));
else
throw new Selector.SelectorParseException("Could not parse attribute query '%s': unexpected token at '%s'", query, cq.remainder());
}
}
private void allElements() {
evals.add(new Evaluator.AllElements());
}
// pseudo selectors :lt, :gt, :eq
private void indexLessThan() {
evals.add(new Evaluator.IndexLessThan(consumeIndex()));
}
private void indexGreaterThan() {
evals.add(new Evaluator.IndexGreaterThan(consumeIndex()));
}
private void indexEquals() {
evals.add(new Evaluator.IndexEquals(consumeIndex()));
}
//pseudo selectors :first-child, :last-child, :nth-child, ...
private static final Pattern NTH_AB = Pattern.compile("(([+-])?(\\d+)?)n(\\s*([+-])?\\s*\\d+)?", Pattern.CASE_INSENSITIVE);
private static final Pattern NTH_B = Pattern.compile("([+-])?(\\d+)");
private void cssNthChild(boolean backwards, boolean ofType) {
String argS = normalize(tq.chompTo(")"));
Matcher mAB = NTH_AB.matcher(argS);
Matcher mB = NTH_B.matcher(argS);
final int a, b;
if ("odd".equals(argS)) {
a = 2;
b = 1;
} else if ("even".equals(argS)) {
a = 2;
b = 0;
} else if (mAB.matches()) {
a = mAB.group(3) != null ? Integer.parseInt(mAB.group(1).replaceFirst("^\\+", "")) : 1;
b = mAB.group(4) != null ? Integer.parseInt(mAB.group(4).replaceFirst("^\\+", "")) : 0;
} else if (mB.matches()) {
a = 0;
b = Integer.parseInt(mB.group().replaceFirst("^\\+", ""));
} else {
throw new Selector.SelectorParseException("Could not parse nth-index '%s': unexpected format", argS);
}
if (ofType)
if (backwards)
evals.add(new Evaluator.IsNthLastOfType(a, b));
else
evals.add(new Evaluator.IsNthOfType(a, b));
else {
if (backwards)
evals.add(new Evaluator.IsNthLastChild(a, b));
else
evals.add(new Evaluator.IsNthChild(a, b));
}
}
private int consumeIndex() {
String indexS = tq.chompTo(")").trim();
Validate.isTrue(StringUtil.isNumeric(indexS), "Index must be numeric");
return Integer.parseInt(indexS);
}
// pseudo selector :has(el)
private void has() {
tq.consume(":has");
String subQuery = tq.chompBalanced('(', ')');
Validate.notEmpty(subQuery, ":has(selector) subselect must not be empty");
evals.add(new StructuralEvaluator.Has(parse(subQuery)));
}
// pseudo selector :contains(text), containsOwn(text)
private void contains(boolean own) {
tq.consume(own ? ":containsOwn" : ":contains");
String searchText = TokenQueue.unescape(tq.chompBalanced('(', ')'));
Validate.notEmpty(searchText, ":contains(text) query must not be empty");
if (own)
evals.add(new Evaluator.ContainsOwnText(searchText));
else
evals.add(new Evaluator.ContainsText(searchText));
}
// pseudo selector :containsData(data)
private void containsData() {
tq.consume(":containsData");
String searchText = TokenQueue.unescape(tq.chompBalanced('(', ')'));
Validate.notEmpty(searchText, ":containsData(text) query must not be empty");
evals.add(new Evaluator.ContainsData(searchText));
}
// :matches(regex), matchesOwn(regex)
private void matches(boolean own) {
tq.consume(own ? ":matchesOwn" : ":matches");
String regex = tq.chompBalanced('(', ')'); // don't unescape, as regex bits will be escaped
Validate.notEmpty(regex, ":matches(regex) query must not be empty");
if (own)
evals.add(new Evaluator.MatchesOwn(Pattern.compile(regex)));
else
evals.add(new Evaluator.Matches(Pattern.compile(regex)));
}
// :not(selector)
private void not() {
tq.consume(":not");
String subQuery = tq.chompBalanced('(', ')');
Validate.notEmpty(subQuery, ":not(selector) subselect must not be empty");
evals.add(new StructuralEvaluator.Not(parse(subQuery)));
}
@Override
public String toString() {
return query;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/Selector.java
|
package org.jsoup.select;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Element;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.IdentityHashMap;
/**
* CSS-like element selector, that finds elements matching a query.
*
* <h2>Selector syntax</h2>
* <p>
* A selector is a chain of simple selectors, separated by combinators. Selectors are <b>case insensitive</b> (including against
* elements, attributes, and attribute values).
* </p>
* <p>
* The universal selector (*) is implicit when no element selector is supplied (i.e. {@code *.header} and {@code .header}
* is equivalent).
* </p>
* <style>table.syntax tr td {vertical-align: top; padding-right: 2em; padding-top:0.5em; padding-bottom:0.5em; } table.syntax tr:hover{background-color: #eee;} table.syntax {border-spacing: 0px 0px;}</style>
* <table summary="" class="syntax"><colgroup><col span="1" style="width: 20%;"><col span="1" style="width: 40%;"><col span="1" style="width: 40%;"></colgroup>
* <tr><th align="left">Pattern</th><th align="left">Matches</th><th align="left">Example</th></tr>
* <tr><td><code>*</code></td><td>any element</td><td><code>*</code></td></tr>
* <tr><td><code>tag</code></td><td>elements with the given tag name</td><td><code>div</code></td></tr>
* <tr><td><code>*|E</code></td><td>elements of type E in any namespace (including non-namespaced)</td><td><code>*|name</code> finds <code><fb:name></code> and <code><name></code> elements</td></tr>
* <tr><td><code>ns|E</code></td><td>elements of type E in the namespace <i>ns</i></td><td><code>fb|name</code> finds <code><fb:name></code> elements</td></tr>
* <tr><td><code>#id</code></td><td>elements with attribute ID of "id"</td><td><code>div#wrap</code>, <code>#logo</code></td></tr>
* <tr><td><code>.class</code></td><td>elements with a class name of "class"</td><td><code>div.left</code>, <code>.result</code></td></tr>
* <tr><td><code>[attr]</code></td><td>elements with an attribute named "attr" (with any value)</td><td><code>a[href]</code>, <code>[title]</code></td></tr>
* <tr><td><code>[^attrPrefix]</code></td><td>elements with an attribute name starting with "attrPrefix". Use to find elements with HTML5 datasets</td><td><code>[^data-]</code>, <code>div[^data-]</code></td></tr>
* <tr><td><code>[attr=val]</code></td><td>elements with an attribute named "attr", and value equal to "val"</td><td><code>img[width=500]</code>, <code>a[rel=nofollow]</code></td></tr>
* <tr><td><code>[attr="val"]</code></td><td>elements with an attribute named "attr", and value equal to "val"</td><td><code>span[hello="Cleveland"][goodbye="Columbus"]</code>, <code>a[rel="nofollow"]</code></td></tr>
* <tr><td><code>[attr^=valPrefix]</code></td><td>elements with an attribute named "attr", and value starting with "valPrefix"</td><td><code>a[href^=http:]</code></td></tr>
* <tr><td><code>[attr$=valSuffix]</code></td><td>elements with an attribute named "attr", and value ending with "valSuffix"</td><td><code>img[src$=.png]</code></td></tr>
* <tr><td><code>[attr*=valContaining]</code></td><td>elements with an attribute named "attr", and value containing "valContaining"</td><td><code>a[href*=/search/]</code></td></tr>
* <tr><td><code>[attr~=<em>regex</em>]</code></td><td>elements with an attribute named "attr", and value matching the regular expression</td><td><code>img[src~=(?i)\\.(png|jpe?g)]</code></td></tr>
* <tr><td></td><td>The above may be combined in any order</td><td><code>div.header[title]</code></td></tr>
* <tr><td><td colspan="3"><h3>Combinators</h3></td></tr>
* <tr><td><code>E F</code></td><td>an F element descended from an E element</td><td><code>div a</code>, <code>.logo h1</code></td></tr>
* <tr><td><code>E {@literal >} F</code></td><td>an F direct child of E</td><td><code>ol {@literal >} li</code></td></tr>
* <tr><td><code>E + F</code></td><td>an F element immediately preceded by sibling E</td><td><code>li + li</code>, <code>div.head + div</code></td></tr>
* <tr><td><code>E ~ F</code></td><td>an F element preceded by sibling E</td><td><code>h1 ~ p</code></td></tr>
* <tr><td><code>E, F, G</code></td><td>all matching elements E, F, or G</td><td><code>a[href], div, h3</code></td></tr>
* <tr><td><td colspan="3"><h3>Pseudo selectors</h3></td></tr>
* <tr><td><code>:lt(<em>n</em>)</code></td><td>elements whose sibling index is less than <em>n</em></td><td><code>td:lt(3)</code> finds the first 3 cells of each row</td></tr>
* <tr><td><code>:gt(<em>n</em>)</code></td><td>elements whose sibling index is greater than <em>n</em></td><td><code>td:gt(1)</code> finds cells after skipping the first two</td></tr>
* <tr><td><code>:eq(<em>n</em>)</code></td><td>elements whose sibling index is equal to <em>n</em></td><td><code>td:eq(0)</code> finds the first cell of each row</td></tr>
* <tr><td><code>:has(<em>selector</em>)</code></td><td>elements that contains at least one element matching the <em>selector</em></td><td><code>div:has(p)</code> finds <code>div</code>s that contain <code>p</code> elements.<br><code>div:has(> a)</code> selects <code>div</code> elements that have at least one direct child <code>a</code> element.</td></tr>
* <tr><td><code>:not(<em>selector</em>)</code></td><td>elements that do not match the <em>selector</em>. See also {@link Elements#not(String)}</td><td><code>div:not(.logo)</code> finds all divs that do not have the "logo" class.<p><code>div:not(:has(div))</code> finds divs that do not contain divs.</p></td></tr>
* <tr><td><code>:contains(<em>text</em>)</code></td><td>elements that contains the specified text. The search is case insensitive. The text may appear in the found element, or any of its descendants. The text is whitespace normalized. <p>To find content that includes parentheses, escape those with a {@code \}.</p></td><td><code>p:contains(jsoup)</code> finds p elements containing the text "jsoup".<p>{@code p:contains(hello \(there\) finds p elements containing the text "Hello (There)"}</p></td></tr>
* <tr><td><code>:containsOwn(<em>text</em>)</code></td><td>elements that directly contain the specified text. The search is case insensitive. The text must appear in the found element, not any of its descendants.</td><td><code>p:containsOwn(jsoup)</code> finds p elements with own text "jsoup".</td></tr>
* <tr><td><code>:containsData(<em>data</em>)</code></td><td>elements that contains the specified <em>data</em>. The contents of {@code script} and {@code style} elements, and {@code comment} nodes (etc) are considered data nodes, not text nodes. The search is case insensitive. The data may appear in the found element, or any of its descendants.</td><td><code>script:contains(jsoup)</code> finds script elements containing the data "jsoup".</td></tr>
* <tr><td><code>:matches(<em>regex</em>)</code></td><td>elements containing <b>whitespace normalized</b> text that matches the specified regular expression. The text may appear in the found element, or any of its descendants.</td><td><code>td:matches(\\d+)</code> finds table cells containing digits. <code>div:matches((?i)login)</code> finds divs containing the text, case insensitively.</td></tr>
* <tr><td><code>:matchesOwn(<em>regex</em>)</code></td><td>elements whose own text matches the specified regular expression. The text must appear in the found element, not any of its descendants.</td><td><code>td:matchesOwn(\\d+)</code> finds table cells directly containing digits. <code>div:matchesOwn((?i)login)</code> finds divs containing the text, case insensitively.</td></tr>
* <tr><td></td><td>The above may be combined in any order and with other selectors</td><td><code>.light:contains(name):eq(0)</code></td></tr>
* <tr><td><code>:matchText</code></td><td>treats text nodes as elements, and so allows you to match against and select text nodes.<p><b>Note</b> that using this selector will modify the DOM, so you may want to {@code clone} your document before using.</td><td>{@code p:matchText:firstChild} with input {@code <p>One<br />Two</p>} will return one {@link org.jsoup.nodes.PseudoTextElement} with text "{@code One}".</td></tr>
* <tr><td colspan="3"><h3>Structural pseudo selectors</h3></td></tr>
* <tr><td><code>:root</code></td><td>The element that is the root of the document. In HTML, this is the <code>html</code> element</td><td><code>:root</code></td></tr>
* <tr><td><code>:nth-child(<em>a</em>n+<em>b</em>)</code></td><td><p>elements that have <code><em>a</em>n+<em>b</em>-1</code> siblings <b>before</b> it in the document tree, for any positive integer or zero value of <code>n</code>, and has a parent element. For values of <code>a</code> and <code>b</code> greater than zero, this effectively divides the element's children into groups of a elements (the last group taking the remainder), and selecting the <em>b</em>th element of each group. For example, this allows the selectors to address every other row in a table, and could be used to alternate the color of paragraph text in a cycle of four. The <code>a</code> and <code>b</code> values must be integers (positive, negative, or zero). The index of the first child of an element is 1.</p>
* In addition to this, <code>:nth-child()</code> can take <code>odd</code> and <code>even</code> as arguments instead. <code>odd</code> has the same signification as <code>2n+1</code>, and <code>even</code> has the same signification as <code>2n</code>.</td><td><code>tr:nth-child(2n+1)</code> finds every odd row of a table. <code>:nth-child(10n-1)</code> the 9th, 19th, 29th, etc, element. <code>li:nth-child(5)</code> the 5h li</td></tr>
* <tr><td><code>:nth-last-child(<em>a</em>n+<em>b</em>)</code></td><td>elements that have <code><em>a</em>n+<em>b</em>-1</code> siblings <b>after</b> it in the document tree. Otherwise like <code>:nth-child()</code></td><td><code>tr:nth-last-child(-n+2)</code> the last two rows of a table</td></tr>
* <tr><td><code>:nth-of-type(<em>a</em>n+<em>b</em>)</code></td><td>pseudo-class notation represents an element that has <code><em>a</em>n+<em>b</em>-1</code> siblings with the same expanded element name <em>before</em> it in the document tree, for any zero or positive integer value of n, and has a parent element</td><td><code>img:nth-of-type(2n+1)</code></td></tr>
* <tr><td><code>:nth-last-of-type(<em>a</em>n+<em>b</em>)</code></td><td>pseudo-class notation represents an element that has <code><em>a</em>n+<em>b</em>-1</code> siblings with the same expanded element name <em>after</em> it in the document tree, for any zero or positive integer value of n, and has a parent element</td><td><code>img:nth-last-of-type(2n+1)</code></td></tr>
* <tr><td><code>:first-child</code></td><td>elements that are the first child of some other element.</td><td><code>div {@literal >} p:first-child</code></td></tr>
* <tr><td><code>:last-child</code></td><td>elements that are the last child of some other element.</td><td><code>ol {@literal >} li:last-child</code></td></tr>
* <tr><td><code>:first-of-type</code></td><td>elements that are the first sibling of its type in the list of children of its parent element</td><td><code>dl dt:first-of-type</code></td></tr>
* <tr><td><code>:last-of-type</code></td><td>elements that are the last sibling of its type in the list of children of its parent element</td><td><code>tr {@literal >} td:last-of-type</code></td></tr>
* <tr><td><code>:only-child</code></td><td>elements that have a parent element and whose parent element have no other element children</td><td></td></tr>
* <tr><td><code>:only-of-type</code></td><td> an element that has a parent element and whose parent element has no other element children with the same expanded element name</td><td></td></tr>
* <tr><td><code>:empty</code></td><td>elements that have no children at all</td><td></td></tr>
* </table>
*
* <p>A word on using regular expressions in these selectors: depending on the content of the regex, you will need to quote the pattern using <b><code>Pattern.quote("regex")</code></b> for it to parse correclty through both the selector parser and the regex parser. E.g. <code>String query = "div:matches(" + Pattern.quote(regex) + ");"</code>.</p>
*
* @author Jonathan Hedley, jonathan@hedley.net
* @see Element#select(String)
*/
public class Selector {
// not instantiable
private Selector() {}
/**
* Find elements matching selector.
*
* @param query CSS selector
* @param root root element to descend into
* @return matching elements, empty if none
* @throws Selector.SelectorParseException (unchecked) on an invalid CSS query.
*/
public static Elements select(String query, Element root) {
Validate.notEmpty(query);
return select(QueryParser.parse(query), root);
}
/**
* Find elements matching selector.
*
* @param evaluator CSS selector
* @param root root element to descend into
* @return matching elements, empty if none
*/
public static Elements select(Evaluator evaluator, Element root) {
Validate.notNull(evaluator);
Validate.notNull(root);
return Collector.collect(evaluator, root);
}
/**
* Find elements matching selector.
*
* @param query CSS selector
* @param roots root elements to descend into
* @return matching elements, empty if none
*/
public static Elements select(String query, Iterable<Element> roots) {
Validate.notEmpty(query);
Validate.notNull(roots);
Evaluator evaluator = QueryParser.parse(query);
Elements elements = new Elements();
IdentityHashMap<Element, Boolean> seenElements = new IdentityHashMap<>();
// dedupe elements by identity, not equality
for (Element root : roots) {
final Elements found = select(evaluator, root);
for (Element el : found) {
if (seenElements.put(el, Boolean.TRUE) == null) {
elements.add(el);
}
}
}
return elements;
}
// exclude set. package open so that Elements can implement .not() selector.
static Elements filterOut(Collection<Element> elements, Collection<Element> outs) {
Elements output = new Elements();
for (Element el : elements) {
boolean found = false;
for (Element out : outs) {
if (el.equals(out)) {
found = true;
break;
}
}
if (!found)
output.add(el);
}
return output;
}
/**
* Find the first element that matches the query.
* @param cssQuery CSS selector
* @param root root element to descend into
* @return the matching element, or <b>null</b> if none.
*/
public static @Nullable Element selectFirst(String cssQuery, Element root) {
Validate.notEmpty(cssQuery);
return Collector.findFirst(QueryParser.parse(cssQuery), root);
}
public static class SelectorParseException extends IllegalStateException {
public SelectorParseException(String msg, Object... params) {
super(String.format(msg, params));
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/StructuralEvaluator.java
|
package org.jsoup.select;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
/**
* Base structural evaluator.
*/
abstract class StructuralEvaluator extends Evaluator {
Evaluator evaluator;
static class Root extends Evaluator {
public boolean matches(Element root, Element element) {
return root == element;
}
}
static class Has extends StructuralEvaluator {
final Collector.FirstFinder finder;
public Has(Evaluator evaluator) {
this.evaluator = evaluator;
finder = new Collector.FirstFinder(evaluator);
}
public boolean matches(Element root, Element element) {
// for :has, we only want to match children (or below), not the input element. And we want to minimize GCs
for (int i = 0; i < element.childNodeSize(); i++) {
Node node = element.childNode(i);
if (node instanceof Element) {
Element match = finder.find(element, (Element) node);
if (match != null)
return true;
}
}
return false;
}
@Override
public String toString() {
return String.format(":has(%s)", evaluator);
}
}
static class Not extends StructuralEvaluator {
public Not(Evaluator evaluator) {
this.evaluator = evaluator;
}
public boolean matches(Element root, Element node) {
return !evaluator.matches(root, node);
}
@Override
public String toString() {
return String.format(":not(%s)", evaluator);
}
}
static class Parent extends StructuralEvaluator {
public Parent(Evaluator evaluator) {
this.evaluator = evaluator;
}
public boolean matches(Element root, Element element) {
if (root == element)
return false;
Element parent = element.parent();
while (parent != null) {
if (evaluator.matches(root, parent))
return true;
if (parent == root)
break;
parent = parent.parent();
}
return false;
}
@Override
public String toString() {
return String.format("%s ", evaluator);
}
}
static class ImmediateParent extends StructuralEvaluator {
public ImmediateParent(Evaluator evaluator) {
this.evaluator = evaluator;
}
public boolean matches(Element root, Element element) {
if (root == element)
return false;
Element parent = element.parent();
return parent != null && evaluator.matches(root, parent);
}
@Override
public String toString() {
return String.format("%s > ", evaluator);
}
}
static class PreviousSibling extends StructuralEvaluator {
public PreviousSibling(Evaluator evaluator) {
this.evaluator = evaluator;
}
public boolean matches(Element root, Element element) {
if (root == element)
return false;
Element prev = element.previousElementSibling();
while (prev != null) {
if (evaluator.matches(root, prev))
return true;
prev = prev.previousElementSibling();
}
return false;
}
@Override
public String toString() {
return String.format("%s ~ ", evaluator);
}
}
static class ImmediatePreviousSibling extends StructuralEvaluator {
public ImmediatePreviousSibling(Evaluator evaluator) {
this.evaluator = evaluator;
}
public boolean matches(Element root, Element element) {
if (root == element)
return false;
Element prev = element.previousElementSibling();
return prev != null && evaluator.matches(root, prev);
}
@Override
public String toString() {
return String.format("%s + ", evaluator);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup
|
java-sources/ai/platon/pulsar/pulsar-jsoup/1.14.3/org/jsoup/select/package-info.java
|
/**
Packages to support the CSS-style element selector.
{@link org.jsoup.select.Selector Selector defines the query syntax.}
*/
@NonnullByDefault
package org.jsoup.select;
import org.jsoup.internal.NonnullByDefault;
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/HyperlinkPersistable.java
|
package ai.platon.pulsar.persist;
import ai.platon.pulsar.persist.gora.generated.GHypeLink;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
public class HyperlinkPersistable implements Comparable<HyperlinkPersistable> {
private GHypeLink hyperlink;
private HyperlinkPersistable(@NotNull GHypeLink hyperlink) {
this.hyperlink = hyperlink;
}
public HyperlinkPersistable(@NotNull String url) {
this(url, null);
}
public HyperlinkPersistable(@NotNull String url, @Nullable String text) {
this(url, text, 0);
}
public HyperlinkPersistable(@NotNull String url, @Nullable String text, int order) {
Objects.requireNonNull(url);
hyperlink = new GHypeLink();
hyperlink.setUrl(url);
hyperlink.setAnchor(text);
hyperlink.setOrder(order);
}
@NotNull
public static HyperlinkPersistable box(@NotNull GHypeLink hyperlink) {
return new HyperlinkPersistable(hyperlink);
}
@NotNull
public static HyperlinkPersistable parse(@NotNull String link) {
String[] urlText = link.split("\\s+");
if (urlText.length == 1) {
return new HyperlinkPersistable(urlText[0]);
} else {
return new HyperlinkPersistable(urlText[0], urlText[1]);
}
}
public static boolean equals(GHypeLink l, GHypeLink l2) {
return l.getUrl().equals(l2.getUrl());
}
public GHypeLink unbox() {
return hyperlink;
}
public String getUrl() {
return hyperlink.getUrl().toString();
}
public void setUrl(String url) {
hyperlink.setUrl(url);
}
@NotNull
public String getText() {
CharSequence anchor = hyperlink.getAnchor();
return anchor == null ? "" : anchor.toString();
}
public void setText(@Nullable String text) {
hyperlink.setAnchor(text);
}
public int getOrder() {
return hyperlink.getOrder();
}
public void setOrder(int order) {
hyperlink.setOrder(order);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HyperlinkPersistable)) {
return getUrl().equals(o.toString());
}
HyperlinkPersistable other = (HyperlinkPersistable) o;
return getUrl().equals(other.getUrl());
}
@Override
public int hashCode() {
return getUrl().hashCode();
}
@Override
public int compareTo(@NotNull HyperlinkPersistable hyperLink) {
int r = getUrl().compareTo(hyperLink.getUrl());
if (r == 0) {
r = getText().compareTo(hyperLink.getText());
if (r == 0) {
r = getOrder() - hyperLink.getOrder();
}
}
return r;
}
@Override
public String toString() {
return getUrl() + " " + getText() + " odr:" + getOrder();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/JPersistUtils.java
|
package ai.platon.pulsar.persist;
import org.apache.avro.util.Utf8;
import org.jetbrains.annotations.Nullable;
public class JPersistUtils {
/**
* Return a Utf8 string.
* <p>
* Unlike {@link String}, instances are mutable. This is more
* efficient than {@link String} when reading or writing a sequence of values,
* as a single instance may be reused.
*/
@Nullable
public static Utf8 u8(@Nullable String value) {
if (value == null) {
// TODO: return new Utf8.EMPTY?
return null;
}
return new Utf8(value);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/Metadata.java
|
package ai.platon.pulsar.persist;
import ai.platon.pulsar.common.DateTimes;
import ai.platon.pulsar.persist.metadata.Name;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.gora.util.ByteUtils;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.nio.ByteBuffer;
import java.time.Instant;
import java.util.Enumeration;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Created by vincent on 17-7-26.
* Copyright @ 2013-2023 Platon AI. All rights reserved
* <p>
* Unstable fields are persisted as a metadata, they should be moved to a real database field if it's getting stable,
* in which case, the database schema should be changed
* </p>
*
* @author vincent, ivincent.zhang@gmail.com
*/
public class Metadata {
private final Map<CharSequence, ByteBuffer> data;
private Metadata(Map<CharSequence, ByteBuffer> data) {
this.data = data;
}
@Nonnull
public static Metadata box(@Nonnull Map<CharSequence, ByteBuffer> data) {
return new Metadata(data);
}
public Map<CharSequence, ByteBuffer> unbox() {
return data;
}
public void set(Name name, String value) {
set(name.text(), value);
}
public void set(String key, String value) {
data.put(JPersistUtils.u8(key), value == null ? null : ByteBuffer.wrap(value.getBytes()));
}
public void set(Name name, int value) {
set(name, String.valueOf(value));
}
public void set(Name name, long value) {
set(name, String.valueOf(value));
}
public void set(Name name, Instant value) {
set(name, DateTimes.isoInstantFormat(value));
}
public void putAll(Map<String, String> data) {
data.forEach(this::set);
}
/**
* Copy All key-value pairs from properties.
*
* @param properties properties to copy from
*/
public void putAll(Properties properties) {
Enumeration<?> names = properties.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
set(name, properties.getProperty(name));
}
}
public ByteBuffer getByteBuffer(Name name) {
return getByteBuffer(name.text());
}
@Nullable
public ByteBuffer getByteBuffer(String name) {
return data.get(JPersistUtils.u8(name));
}
@Nullable
public String get(Name name) {
return get(name.text());
}
@Nullable
public String get(String name) {
ByteBuffer bvalue = getByteBuffer(name);
return bvalue == null ? null : ByteUtils.toString(bvalue.array());
}
@Nonnull
public Optional<String> getOptional(String name) {
return Optional.ofNullable(get(name));
}
@Nonnull
public Optional<String> getOptional(Name name) {
return Optional.ofNullable(get(name));
}
@Nonnull
public String getOrDefault(Name name, String defaultValue) {
String value = get(name);
return value == null ? defaultValue : value;
}
@Nonnull
public String getOrDefault(String name, String defaultValue) {
String value = get(name);
return value == null ? defaultValue : value;
}
public int getInt(Name name, int defaultValue) {
String s = get(name.text());
return NumberUtils.toInt(s, defaultValue);
}
public long getLong(Name name, long defaultValue) {
String s = get(name.text());
return NumberUtils.toLong(s, defaultValue);
}
public float getFloat(Name name, float defaultValue) {
String s = get(name.text());
return NumberUtils.toFloat(s, defaultValue);
}
public boolean getBoolean(Name name, Boolean defaultValue) {
String s = get(name);
if (s == null) {
return defaultValue;
}
return Boolean.parseBoolean(s);
}
@Nonnull
public Instant getInstant(Name name, Instant defaultValue) {
String value = get(name);
return value == null ? defaultValue : DateTimes.parseInstant(value, defaultValue);
}
public boolean contains(Name name) {
return contains(name.text());
}
public boolean contains(String key) {
return getByteBuffer(key) != null;
}
/**
* Remove a data and all its associated values.
*
* @param name data name to remove
*/
public void remove(String name) {
if (get(name) != null) {
set(name, null);
}
}
public void remove(Name name) {
remove(name.text());
}
public void clear() {
data.clear();
}
public void clear(Predicate<String> filter) {
data.keySet().stream()
.map(Object::toString)
.filter(filter)
.forEach(this::remove);
}
public Map<String, String> asStringMap() {
return data.entrySet().stream()
.filter(e -> e.getValue() != null && e.getValue().hasArray())
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> ByteUtils.toString(e.getValue().array())));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
return o instanceof Metadata && data.equals(((Metadata) o).data);
}
@Override
public String toString() {
return asStringMap().toString();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/ParseStatus.java
|
/**
* Autogenerated by Avro
* <p>
* DO NOT EDIT DIRECTLY
*/
package ai.platon.pulsar.persist;
import ai.platon.pulsar.persist.gora.generated.GParseStatus;
import ai.platon.pulsar.persist.metadata.ParseStatusCodes;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class ParseStatus implements ParseStatusCodes {
public static final HashMap<Short, String> majorCodes = new HashMap<>();
public static final HashMap<Integer, String> minorCodes = new HashMap<>();
static {
majorCodes.put(NOTPARSED, "notparsed");
majorCodes.put(SUCCESS, "success");
majorCodes.put(FAILED, "failed");
minorCodes.put(SC_OK, "ok");
minorCodes.put(SUCCESS_REDIRECT, "redirect");
minorCodes.put(FAILED_EXCEPTION, "exception");
minorCodes.put(FAILED_NOT_SPECIFIED, "not_specified");
minorCodes.put(FAILED_TRUNCATED, "truncated");
minorCodes.put(FAILED_INVALID_FORMAT, "invalid_format");
minorCodes.put(FAILED_MISSING_PARTS, "missing_parts");
minorCodes.put(FAILED_MISSING_CONTENT, "missing_content");
minorCodes.put(FAILED_NO_PARSER, "no_parser");
minorCodes.put(FAILED_MALFORMED_URL, "malformed_url");
minorCodes.put(FAILED_UNKNOWN_ENCODING, "unknown_encoding");
}
private final GParseStatus parseStatus;
public ParseStatus(short majorCode, int minorCode) {
this.parseStatus = GParseStatus.newBuilder().build();
setMajorCode(majorCode);
setMinorCode(minorCode);
}
public ParseStatus(short majorCode, int minorCode, String message) {
this.parseStatus = GParseStatus.newBuilder().build();
setMajorCode(majorCode);
setMinorCode(minorCode);
getArgs().put(getMinorName(minorCode), message == null ? "(unknown)" : message);
}
private ParseStatus(GParseStatus parseStatus) {
this.parseStatus = parseStatus;
}
@Nonnull
public static ParseStatus box(GParseStatus parseStatus) {
Objects.requireNonNull(parseStatus);
return new ParseStatus(parseStatus);
}
public static String getMajorName(short code) {
return majorCodes.getOrDefault(code, "unknown");
}
public static String getMinorName(int code) {
return minorCodes.getOrDefault(code, "unknown");
}
public GParseStatus unbox() {
return parseStatus;
}
public void setCode(short majorCode, int minorCode) {
setMajorCode(majorCode);
setMinorCode(minorCode);
}
public String getMajorName() {
return getMajorName(getMajorCode());
}
public short getMajorCode() {
return parseStatus.getMajorCode().shortValue();
}
public void setMajorCode(short majorCode) {
parseStatus.setMajorCode((int) majorCode);
}
public String getMinorName() {
return getMinorName(getMinorCode());
}
public int getMinorCode() {
return parseStatus.getMinorCode();
}
public void setMinorCode(int minorCode) {
parseStatus.setMinorCode(minorCode);
}
public void setMinorCode(int minorCode, String message) {
setMinorCode(minorCode);
getArgs().put(getMinorName(), message);
}
public Map<CharSequence, CharSequence> getArgs() {
return parseStatus.getArgs();
}
public void setArgs(Map<CharSequence, CharSequence> args) {
parseStatus.setArgs(args);
}
public void setSuccessOK() {
setCode(ParseStatus.SUCCESS, ParseStatus.SC_OK);
}
public void setFailed(int minorCode, String message) {
setMajorCode(FAILED);
setMinorCode(minorCode, message);
}
public boolean isParsed() {
return getMajorCode() != NOTPARSED;
}
public boolean isSuccess() {
return getMajorCode() == SUCCESS;
}
public boolean isFailed() {
return getMajorCode() == FAILED;
}
public boolean isRedirect() {
return isSuccess() && getMinorCode() == SUCCESS_REDIRECT;
}
public String getName() {
return majorCodes.getOrDefault(getMajorCode(), "unknown") + "/"
+ minorCodes.getOrDefault(getMinorCode(), "unknown");
}
public String getArgOrElse(String name, String defaultValue) {
return getArgs().getOrDefault(name, defaultValue).toString();
}
@Override
public String toString() {
String args = getArgs().entrySet().stream()
.map(e -> Pair.of(e.getKey().toString(), e.getValue() == null ? "(null)" : e.getValue().toString()))
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining(", "));
return getName() +
" (" + getMajorCode() + "/" + getMinorCode() + ")" +
", args=[" + args + "]";
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/ProtocolHeaders.java
|
package ai.platon.pulsar.persist;
import ai.platon.pulsar.common.DateTimes;
import ai.platon.pulsar.common.HttpHeaders;
import ai.platon.pulsar.common.SParser;
import com.google.common.collect.Multimap;
import org.apache.oro.text.regex.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Map;
import java.util.stream.Collectors;
public class ProtocolHeaders implements HttpHeaders {
static Perl5Pattern[] patterns = {null, null};
static {
Perl5Compiler compiler = new Perl5Compiler();
try {
patterns[0] = (Perl5Pattern) compiler.compile("\\bfilename=['\"](.+)['\"]");
patterns[1] = (Perl5Pattern) compiler.compile("\\bfilename=(\\S+)\\b");
} catch (MalformedPatternException e) {
}
}
private Map<CharSequence, CharSequence> headers;
private ProtocolHeaders(Map<CharSequence, CharSequence> headers) {
this.headers = headers;
}
public static ProtocolHeaders box(Map<CharSequence, CharSequence> headers) {
return new ProtocolHeaders(headers);
}
public Map<CharSequence, CharSequence> unbox() {
return headers;
}
public String get(String name) {
CharSequence value = headers.get(JPersistUtils.u8(name));
return value == null ? null : value.toString();
}
public String getOrDefault(String name, String defaultValue) {
CharSequence value = headers.get(JPersistUtils.u8(name));
return value == null ? defaultValue : value.toString();
}
public void put(String name, String value) {
headers.put(JPersistUtils.u8(name), JPersistUtils.u8(value));
}
public void putAll(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
put(entry.getKey(), entry.getValue());
}
}
public void putAll(Multimap<String, String> map) {
for (Map.Entry<String, String> entry : map.entries()) {
put(entry.getKey(), entry.getValue());
}
}
public void remove(String name) {
headers.remove(JPersistUtils.u8(name));
}
public Instant getLastModified() {
CharSequence lastModified = get(HttpHeaders.LAST_MODIFIED);
if (lastModified != null) {
return DateTimes.parseHttpDateTime(lastModified.toString(), Instant.EPOCH);
}
return Instant.EPOCH;
}
public int getContentLength() {
String length = get(HttpHeaders.CONTENT_LENGTH);
if (length == null) {
return -1;
}
return SParser.wrap(length.trim()).getInt(-1);
}
public String getDispositionFilename() {
CharSequence contentDisposition = get(HttpHeaders.CONTENT_DISPOSITION);
if (contentDisposition == null) {
return null;
}
PatternMatcher matcher = new Perl5Matcher();
for (Perl5Pattern pattern : patterns) {
if (matcher.contains(contentDisposition.toString(), pattern)) {
return matcher.getMatch().group(1);
}
}
return null;
}
public String getDecodedDispositionFilename() {
try {
return getDecodedDispositionFilename(StandardCharsets.UTF_8);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unexpected unsupported encoding `UTF-8`");
}
}
public String getDecodedDispositionFilename(Charset charset) throws UnsupportedEncodingException {
String filename = getDispositionFilename();
if (filename != null) {
return URLDecoder.decode(filename, charset);
}
return null;
}
public void clear() {
headers.clear();
}
public Map<String, String> asStringMap() {
return headers.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString(), (e, e2) -> e));
}
@Override
public String toString() {
return headers.entrySet().stream()
.map(e -> e.getKey() + ": " + e.getValue())
.collect(Collectors.joining("\n"));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/RetryScope.java
|
package ai.platon.pulsar.persist;
/**
* Retry scope indicates in which scope or subsystem to perform the retrying.
*/
public enum RetryScope {
/**
* Retry in crawl schedule scope
* */
CRAWL,
/**
* Retry in job schedule scope
* */
JOB,
/**
* Retry in fetch protocol scope, ignored in browser emulation mode
* */
PROTOCOL,
/**
* Change the privacy context and retry
* */
PRIVACY,
/**
* Change the proxy ip and retry
* */
PROXY,
/**
* Refresh in the same web driver
* */
WEB_DRIVER,
/**
* Retry in the same browser instance
* */
BROWSER
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/Variables.java
|
package ai.platon.pulsar.persist;
import ai.platon.pulsar.persist.metadata.Name;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Created by vincent on 17-7-26.
* Copyright @ 2013-2023 Platon AI. All rights reserved.
*/
public class Variables {
/**
* Temporary variables, all temporary fields will not persist to storage.
*/
private final Map<String, Object> variables = new ConcurrentHashMap<>();
public Map<String, Object> getVariables() {
return variables;
}
public Object get(Name name) {
return get(name.text());
}
public Object get(String name) {
return variables.get(name);
}
public <T> T get(Name name, T defaultValue) {
return get(name.text(), defaultValue);
}
public <T> T get(String name, T defaultValue) {
Object o = variables.get(name);
return o == null ? defaultValue : (T) o;
}
public String getString(String name) {
return getString(name, "");
}
public String getString(String name, String defaultValue) {
Object value = variables.get(name);
return value == null ? defaultValue : value.toString();
}
public boolean contains(Name name) {
return contains(name.text());
}
public boolean contains(String name) {
return variables.containsKey(name);
}
public void set(Name name, Object value) {
set(name.text(), value);
}
public void set(String name, Object value) {
variables.put(name, value);
}
public Object remove(Name name) {
return remove(name.text());
}
public Object remove(String name) {
return variables.remove(name);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/package-info.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Persist layer of the PulsarRPA system.
*/
package ai.platon.pulsar.persist;
|
0
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist
|
java-sources/ai/platon/pulsar/pulsar-persist/3.0.15/ai/platon/pulsar/persist/gora/GoraStorage.java
|
package ai.platon.pulsar.persist.gora;
import ai.platon.pulsar.common.config.ImmutableConfig;
import ai.platon.pulsar.persist.HadoopUtils;
import ai.platon.pulsar.persist.gora.generated.GWebPage;
import org.apache.gora.mongodb.store.MongoStoreParameters;
import org.apache.gora.persistency.Persistent;
import org.apache.gora.store.DataStore;
import org.apache.gora.store.DataStoreFactory;
import org.apache.gora.util.GoraException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import static ai.platon.pulsar.common.LogsKt.warnForClose;
import static ai.platon.pulsar.common.config.AppConstants.MONGO_STORE_CLASS;
import static ai.platon.pulsar.common.config.AppConstants.WEBPAGE_SCHEMA;
import static ai.platon.pulsar.common.config.CapabilityTypes.*;
import static org.apache.gora.mongodb.store.MongoStoreParameters.PROP_MONGO_SERVERS;
public class GoraStorage {
public static final Logger logger = LoggerFactory.getLogger(GoraStorage.class);
/**
* Loads properties from the `gora.properties` file.
* See org.apache.gora.mongodb.store.MongoStoreParameters#load for property loading details:
* 1. Loads from the `gora.properties` file.
* 2. If `gora.mongodb.override_hadoop_configuration` is false, uses properties from the Hadoop configuration.
* 3. In PulsarRPA, the `gora.properties` file is located at `pulsar-persist/src/main/resources/gora.properties`
*/
public static Properties goraProperties = DataStoreFactory.createProps();
/**
* The dataStores map is used to cache DataStore instances
* */
private static Map<String, Object> dataStores = new HashMap<>();
public synchronized static <K, V extends Persistent> DataStore<K, V>
createDataStore(ImmutableConfig conf, Class<K> keyClass, Class<V> persistentClass)
throws GoraException, ClassNotFoundException {
return createDataStore(HadoopUtils.INSTANCE.toHadoopConfiguration(conf), keyClass, persistentClass);
}
@SuppressWarnings("unchecked")
public synchronized static <K, V extends Persistent> DataStore<K, V>
createDataStore(org.apache.hadoop.conf.Configuration conf, Class<K> keyClass, Class<V> persistentClass)
throws GoraException, ClassNotFoundException {
String className = conf.get(STORAGE_DATA_STORE_CLASS, MONGO_STORE_CLASS);
Class<? extends DataStore<K, V>> dataStoreClass = (Class<? extends DataStore<K, V>>)Class.forName(className);
return createDataStore(conf, keyClass, persistentClass, dataStoreClass);
}
@SuppressWarnings("unchecked")
public synchronized static <K, V extends Persistent> DataStore<K, V>
createDataStore(org.apache.hadoop.conf.Configuration conf,
Class<K> keyClass, Class<V> persistentClass, Class<? extends DataStore<K, V>> dataStoreClass
) throws GoraException {
String crawlId = conf.get(STORAGE_CRAWL_ID, "");
String schemaPrefix = "";
if (!crawlId.isEmpty()) {
schemaPrefix = crawlId + "_";
}
String schema;
if (GWebPage.class.equals(persistentClass)) {
schema = conf.get(STORAGE_SCHEMA_WEBPAGE, WEBPAGE_SCHEMA);
} else {
throw new UnsupportedOperationException("Unable to create storage for class " + persistentClass);
}
Object o = dataStores.get(schema);
if (o == null) {
String realSchema = schemaPrefix + schema;
conf.set(STORAGE_PREFERRED_SCHEMA_NAME, realSchema);
DataStore<K, V> dataStore = DataStoreFactory.createDataStore(dataStoreClass,
keyClass, persistentClass, conf, goraProperties, schema);
dataStores.put(realSchema, dataStore);
String className = dataStore.getClass().getName();
if (className.contains("FileBackendPageStore")) {
logger.info("Backend data store: {}, real schema: {}", className, dataStore.getSchemaName());
logger.info("FileBackendPageStore is only for development and testing, " +
"it is not suitable for production environment");
} else {
logger.info("Backend data store: {}, real schema: {}, storage id: <{}>, " +
"set config `storage.crawl.id` to define the real schema",
className, dataStore.getSchemaName(), schemaPrefix);
}
return dataStore;
}
return (DataStore<K, V>) o;
}
public synchronized static void close() {
dataStores.forEach((schema, store) -> {
if (store instanceof DataStore) {
logger.info("Closing data store <{}>", schema);
try {
((DataStore<?, ?>) store).close();
} catch (Exception e) {
warnForClose(store, e);
}
}
});
dataStores.clear();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.