下面列出了org.apache.commons.io.serialization.ValidatingObjectInputStream#java.io.InvalidClassException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Test SharedSecrets checkArray with unmodified ObjectInputStream.
*/
@Test(dataProvider = "Patterns")
public void normalOIS(String pattern, int arraySize, Object[] array) throws IOException {
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
byte[] bytes = SerialFilterTest.writeObjects(array);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
// Check the arraysize against the filter
try {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
SharedSecrets.getJavaOISAccess()
.checkArray(ois, array.getClass(), arraySize);
Assert.assertTrue(array.length >= arraySize,
"Should have thrown InvalidClassException due to array size");
} catch (InvalidClassException ice) {
Assert.assertFalse(array.length > arraySize,
"Should NOT have thrown InvalidClassException due to array size");
}
}
}
private void skipCustomUsingFVD(ValueMember[] fields,
com.sun.org.omg.SendingContext.CodeBase sender)
throws InvalidClassException, StreamCorruptedException,
ClassNotFoundException, IOException
{
readFormatVersion();
boolean calledDefaultWriteObject = readBoolean();
if (calledDefaultWriteObject)
throwAwayData(fields, sender);
if (getStreamFormatVersion() == 2) {
((ValueInputStream)getOrbStream()).start_value();
((ValueInputStream)getOrbStream()).end_value();
}
}
@Test(expected = InvalidClassException.class)
public void testThreadIssue() throws Exception {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream stream = new ObjectOutputStream(bytes)) {
stream.writeObject(42);
}
try (ObjectInputStream stream = new SerialKiller(new ByteArrayInputStream(bytes.toByteArray()), "src/test/resources/blacklist-all.conf")) {
// Create a dummy SK with different config
new SerialKiller(new ByteArrayInputStream(bytes.toByteArray()), "src/test/resources/whitelist-all.conf");
stream.readObject();
fail("All should be blacklisted");
}
}
public static void testReadWrite() {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
testWrite(oos);
oos.flush();
oos.close();
byte buf[] = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
ObjectInputStream ois = new ObjectInputStream(bais);
testRead(ois, true);
} catch (InvalidClassException ice) {
throw new RuntimeException("Object read failed from loopback");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException testing loopback");
}
}
/**
* Test SharedSecrets checkArray with an ObjectInputStream subclassed to
* handle all input stream functions.
*/
@Test(dataProvider = "Patterns")
public void subclassedOIS(String pattern, int arraySize, Object[] array) throws IOException {
byte[] bytes = SerialFilterTest.writeObjects(array);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new MyInputStream(bais)) {
// Check the arraysize against the filter
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
SharedSecrets.getJavaOISAccess()
.checkArray(ois, array.getClass(), arraySize);
Assert.assertTrue(array.length >= arraySize,
"Should have thrown InvalidClassException due to array size");
} catch (InvalidClassException ice) {
Assert.assertFalse(array.length > arraySize,
"Should NOT have thrown InvalidClassException due to array size");
}
}
private static void writeInternal(byte type, Object object, DataOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case ZRULES:
((ZoneRules) object).writeExternal(out);
break;
case ZOT:
((ZoneOffsetTransition) object).writeExternal(out);
break;
case ZOTRULE:
((ZoneOffsetTransitionRule) object).writeExternal(out);
break;
case TZRULES:
((ZoneRules) object).writeExternalTimeZone(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
private void skipCustomUsingFVD(ValueMember[] fields,
com.sun.org.omg.SendingContext.CodeBase sender)
throws InvalidClassException, StreamCorruptedException,
ClassNotFoundException, IOException
{
readFormatVersion();
boolean calledDefaultWriteObject = readBoolean();
if (calledDefaultWriteObject)
throwAwayData(fields, sender);
if (getStreamFormatVersion() == 2) {
((ValueInputStream)getOrbStream()).start_value();
((ValueInputStream)getOrbStream()).end_value();
}
}
/**
* Serialize and deserialize an object using the default process-wide filter
* and check allowed or reject.
*
* @param pattern the pattern
* @param object the test object
* @param allowed the expected result from ObjectInputStream (exception or not)
*/
static void testGlobalPattern(String pattern, Object object, boolean allowed) {
try {
// System.out.printf("global %s pattern: %s, obj: %s%n", (allowed ? "allowed" : "not allowed"), pattern, object);
byte[] bytes = SerialFilterTest.writeObjects(object);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
Object o = ois.readObject();
} catch (EOFException eof) {
// normal completion
} catch (ClassNotFoundException cnf) {
Assert.fail("Deserializing", cnf);
}
Assert.assertTrue(allowed, "filter should have thrown an exception");
} catch (IllegalArgumentException iae) {
Assert.fail("bad format pattern", iae);
} catch (InvalidClassException ice) {
Assert.assertFalse(allowed, "filter should not have thrown an exception: " + ice);
} catch (IOException ioe) {
Assert.fail("Unexpected IOException", ioe);
}
}
private void skipCustomUsingFVD(ValueMember[] fields,
com.sun.org.omg.SendingContext.CodeBase sender)
throws InvalidClassException, StreamCorruptedException,
ClassNotFoundException, IOException
{
readFormatVersion();
boolean calledDefaultWriteObject = readBoolean();
if (calledDefaultWriteObject)
throwAwayData(fields, sender);
if (getStreamFormatVersion() == 2) {
((ValueInputStream)getOrbStream()).start_value();
((ValueInputStream)getOrbStream()).end_value();
}
}
public void runMain(String[] args) throws Exception {
int pos = getMatchingPosition(args, "-dt", "--dataType");
if (pos == -1) {
log.error("no valid options");
log.error("-dt, --dataType Options: [CSV, IMAGE]");
throw new Exception("no valid options");
} else {
transformDataType = TransformDataType.valueOf(args[pos + 1]);
}
switch (transformDataType) {
case CSV:
sparkTransformServer = new CSVSparkTransformServer();
break;
case IMAGE:
sparkTransformServer = new ImageSparkTransformServer();
break;
default:
throw new InvalidClassException("no matching SparkTransform class");
}
sparkTransformServer.runMain(args);
}
@SuppressWarnings("unchecked")
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
//super.readExternal(in);
parent = Factory.getWrapperFactory();
int version = in.readInt();
if (version != EXTERNALVERSIONUID) {
throw new InvalidClassException("Cannot read dataversion " + version);
}
sessionType_ = (SessionType) in.readObject();
username_ = (String) in.readObject();
currentDatabaseApiPath_ = (String) in.readObject();
isAutoMime_ = (AutoMime) in.readObject();
fixes_ = (Set<Fixes>) in.readObject();
eventFactory_ = (IDominoEventFactory) in.readObject();
featureRestricted_ = in.readBoolean();
}
private void skipCustomUsingFVD(ValueMember[] fields,
com.sun.org.omg.SendingContext.CodeBase sender)
throws InvalidClassException, StreamCorruptedException,
ClassNotFoundException, IOException
{
readFormatVersion();
boolean calledDefaultWriteObject = readBoolean();
if (calledDefaultWriteObject)
throwAwayData(fields, sender);
if (getStreamFormatVersion() == 2) {
((ValueInputStream)getOrbStream()).start_value();
((ValueInputStream)getOrbStream()).end_value();
}
}
private static void writeInternal(byte type, Object object, DataOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case ZRULES:
((ZoneRules) object).writeExternal(out);
break;
case ZOT:
((ZoneOffsetTransition) object).writeExternal(out);
break;
case ZOTRULE:
((ZoneOffsetTransitionRule) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
/**
* Test SharedSecrets checkArray with unmodified ObjectInputStream.
*/
@Test(dataProvider = "Patterns")
public void normalOIS(String pattern, int arraySize, Object[] array) throws IOException {
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
byte[] bytes = SerialFilterTest.writeObjects(array);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
// Check the arraysize against the filter
try {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
SharedSecrets.getJavaOISAccess()
.checkArray(ois, array.getClass(), arraySize);
Assert.assertTrue(array.length >= arraySize,
"Should have thrown InvalidClassException due to array size");
} catch (InvalidClassException ice) {
Assert.assertFalse(array.length > arraySize,
"Should NOT have thrown InvalidClassException due to array size");
}
}
}
/**
* Test that returning null from a filter causes deserialization to fail.
*/
@Test(expectedExceptions=InvalidClassException.class)
static void testNullStatus() throws IOException {
byte[] bytes = writeObjects(0); // an Integer
try {
Object o = validate(bytes, new ObjectInputFilter() {
public ObjectInputFilter.Status checkInput(ObjectInputFilter.FilterInfo f) {
return null;
}
});
} catch (InvalidClassException ice) {
System.out.printf("Success exception: %s%n", ice);
throw ice;
}
}
public static XdrString decode(XdrDataInputStream stream, int maxSize) throws IOException {
int size = stream.readInt();
if (size > maxSize) {
throw new InvalidClassException("String length "+size+" exceeds max size "+maxSize);
}
byte[] bytes = new byte[size];
stream.read(bytes);
return new XdrString(bytes);
}
private static void writeInternal(byte type, Object object, ObjectOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case CHRONO_TYPE:
((AbstractChronology) object).writeExternal(out);
break;
case CHRONO_LOCAL_DATE_TIME_TYPE:
((ChronoLocalDateTimeImpl<?>) object).writeExternal(out);
break;
case CHRONO_ZONE_DATE_TIME_TYPE:
((ChronoZonedDateTimeImpl<?>) object).writeExternal(out);
break;
case JAPANESE_DATE_TYPE:
((JapaneseDate) object).writeExternal(out);
break;
case JAPANESE_ERA_TYPE:
((JapaneseEra) object).writeExternal(out);
break;
case HIJRAH_DATE_TYPE:
((HijrahDate) object).writeExternal(out);
break;
case MINGUO_DATE_TYPE:
((MinguoDate) object).writeExternal(out);
break;
case THAIBUDDHIST_DATE_TYPE:
((ThaiBuddhistDate) object).writeExternal(out);
break;
case CHRONO_PERIOD_TYPE:
((ChronoPeriodImpl) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
/**
* Test:
* "global filter reject" + "specific ObjectInputStream filter is empty" => should reject
* "global filter reject" + "specific ObjectInputStream filter allow" => should allow
*/
@Test(dataProvider="Patterns")
public void testRejectedInGlobal(Object toDeserialized, String pattern, boolean allowed) throws Exception {
byte[] bytes = SerialFilterTest.writeObjects(toDeserialized);
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
assertTrue(allowed, "filter should have thrown an exception");
} catch (InvalidClassException ice) {
assertFalse(allowed, "filter should have thrown an exception");
}
}
private static ObjectStreamClass checkForCompatibility(ObjectStreamClass descriptor, ObjectStreamClass substitution) throws InvalidClassException {
if (descriptor.getSerialVersionUID() != substitution.getSerialVersionUID()) {
throw new InvalidClassException(substitution.getName(),
"substitute class incompatible: " +
"stream classdesc serialVersionUID = " + descriptor.getSerialVersionUID() +
", substitute class serialVersionUID = " + substitution.getSerialVersionUID());
} else {
LOGGER.debug("Shading Auto-Substitution: {} -> {}", descriptor, substitution);
return substitution;
}
}
private static Object deserialize(byte[] objectData, ClassLoader classLoader) throws InvalidClassException {
if (objectData == null) {
throw new IllegalArgumentException("The byte[] must not be null");
}
ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
return deserialize(bais, classLoader);
}
private static void writeInternal(byte type, Object object, ObjectOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case CHRONO_TYPE:
((AbstractChronology) object).writeExternal(out);
break;
case CHRONO_LOCAL_DATE_TIME_TYPE:
((ChronoLocalDateTimeImpl<?>) object).writeExternal(out);
break;
case CHRONO_ZONE_DATE_TIME_TYPE:
((ChronoZonedDateTimeImpl<?>) object).writeExternal(out);
break;
case JAPANESE_DATE_TYPE:
((JapaneseDate) object).writeExternal(out);
break;
case JAPANESE_ERA_TYPE:
((JapaneseEra) object).writeExternal(out);
break;
case HIJRAH_DATE_TYPE:
((HijrahDate) object).writeExternal(out);
break;
case MINGUO_DATE_TYPE:
((MinguoDate) object).writeExternal(out);
break;
case THAIBUDDHIST_DATE_TYPE:
((ThaiBuddhistDate) object).writeExternal(out);
break;
case CHRONO_PERIOD_TYPE:
((ChronoPeriodImpl) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
/**
* Reads the "cause" field from the stream.
* And initializes the "cause" if it wasn't
* done before.
*
* @param in stream used for deserialization
* @throws IOException thrown by <code>ObjectInputStream</code>
* @throws ClassNotFoundException thrown by <code>ObjectInputStream</code>
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
ObjectInputStream.GetField fields = in.readFields();
Throwable scause = (Throwable) fields.get("cause", null);
if (super.getCause() == null && scause != null) {
try {
super.initCause(scause);
} catch(IllegalStateException e) {
throw new InvalidClassException("Inconsistent state: two causes");
}
}
}
/**
* Test that returning null from a filter causes deserialization to fail.
*/
@Test(expectedExceptions=InvalidClassException.class)
static void testNullStatus() throws IOException {
byte[] bytes = writeObjects(0); // an Integer
try {
Object o = validate(bytes, new ObjectInputFilter() {
public ObjectInputFilter.Status checkInput(ObjectInputFilter.FilterInfo f) {
return null;
}
});
} catch (InvalidClassException ice) {
System.out.printf("Success exception: %s%n", ice);
throw ice;
}
}
/**
* Create a filter from a pattern and API factory, then serialize and
* deserialize an object and check allowed or reject.
*
* @param pattern the pattern
* @param object the test object
* @param allowed the expected result from ObjectInputStream (exception or not)
*/
static void testPatterns(String pattern, Object object, boolean allowed) {
try {
byte[] bytes = SerialFilterTest.writeObjects(object);
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
validate(bytes, filter);
Assert.assertTrue(allowed, "filter should have thrown an exception");
} catch (IllegalArgumentException iae) {
Assert.fail("bad format pattern", iae);
} catch (InvalidClassException ice) {
Assert.assertFalse(allowed, "filter should not have thrown an exception: " + ice);
} catch (IOException ioe) {
Assert.fail("Unexpected IOException", ioe);
}
}
/**
* Test:
* "global filter reject" + "specific ObjectInputStream filter is empty" => should reject
* "global filter reject" + "specific ObjectInputStream filter allow" => should allow
*/
@Test(dataProvider="Patterns")
public void testRejectedInGlobal(Object toDeserialized, String pattern, boolean allowed) throws Exception {
byte[] bytes = SerialFilterTest.writeObjects(toDeserialized);
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(pattern);
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
Object o = ois.readObject();
assertTrue(allowed, "filter should have thrown an exception");
} catch (InvalidClassException ice) {
assertFalse(allowed, "filter should have thrown an exception");
}
}
public void testSerialVersionUidChange() throws Exception {
// this was created by serializing a SerialVersionUidChanged with serialVersionUID = 0L
String s = "aced0005737200396c6962636f72652e6a6176612e696f2e53657269616c697a6174696f6e54657"
+ "3742453657269616c56657273696f6e5569644368616e67656400000000000000000200014900016"
+ "1787000000003";
try {
SerializationTester.deserializeHex(s);
fail();
} catch (InvalidClassException expected) {
}
}
void readFields(java.util.Map fieldToValueMap)
throws InvalidClassException, StreamCorruptedException,
ClassNotFoundException, IOException {
if (mustUseRemoteValueMembers()) {
inputRemoteMembersForReadFields(fieldToValueMap);
} else
inputCurrentClassFieldsForReadFields(fieldToValueMap);
}
private static void writeInternal(byte type, Object object, ObjectOutput out) throws IOException {
out.writeByte(type);
switch (type) {
case CHRONO_TYPE:
((AbstractChronology) object).writeExternal(out);
break;
case CHRONO_LOCAL_DATE_TIME_TYPE:
((ChronoLocalDateTimeImpl<?>) object).writeExternal(out);
break;
case CHRONO_ZONE_DATE_TIME_TYPE:
((ChronoZonedDateTimeImpl<?>) object).writeExternal(out);
break;
case JAPANESE_DATE_TYPE:
((JapaneseDate) object).writeExternal(out);
break;
case JAPANESE_ERA_TYPE:
((JapaneseEra) object).writeExternal(out);
break;
case HIJRAH_DATE_TYPE:
((HijrahDate) object).writeExternal(out);
break;
case MINGUO_DATE_TYPE:
((MinguoDate) object).writeExternal(out);
break;
case THAIBUDDHIST_DATE_TYPE:
((ThaiBuddhistDate) object).writeExternal(out);
break;
case CHRONO_PERIOD_TYPE:
((ChronoPeriodImpl) object).writeExternal(out);
break;
default:
throw new InvalidClassException("Unknown serialized type");
}
}
/**
* Test that returning null from a filter causes deserialization to fail.
*/
@Test(expectedExceptions=InvalidClassException.class)
static void testNullStatus() throws IOException {
byte[] bytes = writeObjects(0); // an Integer
try {
Object o = validate(bytes, new ObjectInputFilter() {
public ObjectInputFilter.Status checkInput(ObjectInputFilter.FilterInfo f) {
return null;
}
});
} catch (InvalidClassException ice) {
System.out.printf("Success exception: %s%n", ice);
throw ice;
}
}
public GraphSimilarity getSimilarityBetween(Object oFirst, Object oSecond) throws InvalidClassException {
if (!((oFirst instanceof NGramDocument) && (oSecond instanceof NGramDocument)))
throw new InvalidClassException("Both operands should be Documents (" + NGramDocument.class.getName() +
" class)");
NGramDocument dFirst = (NGramDocument)oFirst;
NGramDocument dSecond = (NGramDocument)oSecond;
NGramCachedGraphComparator gcComparator = new NGramCachedGraphComparator();
NGramHistogramComparator hcComparator = new NGramHistogramComparator();
GraphSimilarity[] saSimil = new GraphSimilarity[2];
//gcComparator.setNotificationListener(this); // Set this to listener
// Graph GraphSimilarity
saSimil[0] = gcComparator.getSimilarityBetween(dFirst.getDocumentGraph(), dSecond.getDocumentGraph());
sGraph = saSimil[0];
// Histogram GraphSimilarity
saSimil[1] = hcComparator.getSimilarityBetween(dFirst.getDocumentHistogram(), dSecond.getDocumentHistogram());
sHistogram = saSimil[1];
GraphSimilarity sSimil = new GraphSimilarity();
sSimil.ContainmentSimilarity = saSimil[0].ContainmentSimilarity * GraphImportance +
saSimil[1].ContainmentSimilarity * (1 - GraphImportance);
sSimil.ValueSimilarity = saSimil[0].ValueSimilarity * GraphImportance +
saSimil[1].ValueSimilarity * (1 - GraphImportance);
sSimil.SizeSimilarity = saSimil[0].SizeSimilarity * GraphImportance +
saSimil[1].SizeSimilarity * (1 - GraphImportance);
return sSimil;
}