下面列出了怎么用java.io.NotSerializableException的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected URI internalNewURI(ServerLocator bean) throws Exception {
DiscoveryGroupConfiguration dgc = bean.getDiscoveryGroupConfiguration();
BroadcastEndpointFactory endpoint = dgc.getBroadcastEndpointFactory();
String auth;
if (endpoint instanceof JGroupsFileBroadcastEndpointFactory) {
auth = ((JGroupsFileBroadcastEndpointFactory) endpoint).getChannelName();
} else if (endpoint instanceof JGroupsPropertiesBroadcastEndpointFactory) {
auth = ((JGroupsPropertiesBroadcastEndpointFactory) endpoint).getChannelName();
} else {
throw new NotSerializableException(endpoint + "not serializable");
}
String query = BeanSupport.getData(null, bean, dgc, endpoint);
dgc.setBroadcastEndpointFactory(endpoint);
return new URI(SchemaConstants.JGROUPS, null, auth, -1, null, query, null);
}
/**
* @param node Grid node.
* @param cache Node cache.
* @param txConcurrency Transaction concurrency.
* @param txIsolation Transaction isolation.
*/
@SuppressWarnings({"unchecked", "ThrowableNotThrown"})
private void checkTxInvoke(Ignite node, IgniteCache cache, TransactionConcurrency txConcurrency,
TransactionIsolation txIsolation) {
try (final Transaction tx = node.transactions().txStart(txConcurrency, txIsolation)) {
cache.put(KEY, WRONG_VALUE);
cache.invoke(KEY, new NonSerialazibleEntryProcessor());
GridTestUtils.assertThrowsWithCause(new Callable<Object>() {
@Override public Object call() {
tx.commit();
return null;
}
}, NotSerializableException.class);
}
}
@Override
public void fromData(DataInput in) throws IOException, ClassNotFoundException {
super.fromData(in);
this.msgNum = in.readInt();
this.processorId = in.readInt();
try {
this.result = DataSerializer.readObject(in);
byte flags = in.readByte();
this.lastMsg = (flags & IS_LAST) != 0;
if ((flags & HAS_TX_CHANGES) != 0) {
this.txChanges = TXChanges.fromData(in);
}
}
catch (Exception e) { // bug fix 40670
// Seems odd to throw a NonSerializableEx when it has already been
// serialized and we are failing because we can't deserialize.
NotSerializableException ioEx = new NotSerializableException();
ioEx.initCause(e);
throw ioEx;
}
}
/**
* <p>
* Remove the transient data from and then create a serialized <code>java.util.ByteArrayOutputStream</code>
* version of a <code>{@link org.quartz.JobDataMap}</code>.
* </p>
*
* @param data
* the JobDataMap to serialize
* @return the serialized ByteArrayOutputStream
* @throws IOException
* if serialization causes an error
*/
protected ByteArrayOutputStream serializeJobData(JobDataMap data)
throws IOException {
if (canUseProperties()) {
return serializeProperties(data);
}
try {
return serializeObject(data);
} catch (NotSerializableException e) {
throw new NotSerializableException(
"Unable to serialize JobDataMap for insertion into " +
"database because the value of property '" +
getKeyOfNonSerializableValue(data) +
"' is not serializable: " + e.getMessage());
}
}
public void testBasicAll() throws IOException, ClassNotFoundException {
BasicAllFieldTypes v1 = new BasicAllFieldTypes(0x1020304050607080L, false);
try {
serializeAndDeserialize(v1);
fail("expected NotSerializableException");
} catch (NotSerializableException expected) {
}
this.c.setPdxSerializer(new BasicAllFieldTypesPdxSerializer());
try {
BasicAllFieldTypes v2 = (BasicAllFieldTypes) serializeAndDeserialize(v1);
assertEquals(v1, v2);
} finally {
this.c.setPdxSerializer(null);
}
}
/**
* @return list of recipients who did not receive the message because
* they left the view (null if all received it or it was sent to
* {@link DistributionMessage#ALL_RECIPIENTS}).
* @throws NotSerializableException
* If content cannot be serialized
*/
public Set send(InternalDistributedMember[] destinations,
DistributionMessage content,
DistributionManager dm, DistributionStats stats)
throws NotSerializableException {
if (membershipManager == null) {
logger.warning(LocalizedStrings.DistributionChannel_ATTEMPTING_A_SEND_TO_A_DISCONNECTED_DISTRIBUTIONMANAGER);
if (destinations.length == 1
&& destinations[0] == DistributionMessage.ALL_RECIPIENTS)
return null;
HashSet result = new HashSet();
for (int i = 0; i < destinations.length; i ++)
result.add(destinations[i]);
return result;
}
return membershipManager.send(destinations, content, stats);
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
private void manageSavingIssue(TestIssue testIssue, String workingFolderPath, IllegalStateException illegalStateException) {
Throwable cause = illegalStateException.getCause();
if (cause instanceof NotSerializableException) {
TestIssue serializableTestIssue =
TestIssue.buildSerializableTestIssueFrom(testIssue);
save(serializableTestIssue, workingFolderPath);
} else {
throw illegalStateException;
}
}
private void assertNotSerial(Predicate<String> p, Consumer<Predicate<String>> asserter)
throws IOException, ClassNotFoundException {
asserter.accept(p);
try {
byte[] bytes = serialize(p);
fail("Expected serialization failure");
}
catch (NotSerializableException e) {
// success
}
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
private void writeObject(java.io.ObjectOutputStream stream) throws IOException {
throw new NotSerializableException(
"PipelineOptions objects are not serializable and should not be embedded into transforms "
+ "(did you capture a PipelineOptions object in a field or in an anonymous class?). "
+ "Instead, if you're using a DoFn, access PipelineOptions at runtime "
+ "via ProcessContext/StartBundleContext/FinishBundleContext.getPipelineOptions(), "
+ "or pre-extract necessary fields from PipelineOptions "
+ "at pipeline construction time.");
}
public static void main(String[] args) throws Exception {
System.err.println("\nRegression test for bug 6332349\n");
Ping impl = new PingImpl();
Reference<?> ref = new WeakReference<Ping>(impl);
try {
Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0);
Object notSerializable = new Object();
stub.ping(impl, null);
try {
stub.ping(impl, notSerializable);
} catch (MarshalException e) {
if (e.getCause() instanceof NotSerializableException) {
System.err.println("ping invocation failed as expected");
} else {
throw e;
}
}
} finally {
UnicastRemoteObject.unexportObject(impl, true);
}
impl = null;
// Might require multiple calls to System.gc() for weak-references
// processing to be complete. If the weak-reference is not cleared as
// expected we will hang here until timed out by the test harness.
while (true) {
System.gc();
Thread.sleep(20);
if (ref.get() == null) {
break;
}
}
System.err.println("TEST PASSED");
}
private NotificationResult fetchNotifs() {
try {
NotificationResult nr = ClientNotifForwarder.this.
fetchNotifs(clientSequenceNumber,maxNotifications,
timeout);
if (logger.traceOn()) {
logger.trace("NotifFetcher-run",
"Got notifications from the server: "+nr);
}
return nr;
} catch (ClassNotFoundException | NotSerializableException | UnmarshalException e) {
logger.trace("NotifFetcher.fetchNotifs", e);
return fetchOneNotif();
} catch (IOException ioe) {
if (!shouldStop()) {
logger.error("NotifFetcher-run",
"Failed to fetch notification, " +
"stopping thread. Error is: " + ioe, ioe);
logger.debug("NotifFetcher-run",ioe);
}
// no more fetching
return null;
}
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
private NotificationResult fetchNotifs() {
try {
NotificationResult nr = ClientNotifForwarder.this.
fetchNotifs(clientSequenceNumber,maxNotifications,
timeout);
if (logger.traceOn()) {
logger.trace("NotifFetcher-run",
"Got notifications from the server: "+nr);
}
return nr;
} catch (ClassNotFoundException | NotSerializableException | UnmarshalException e) {
logger.trace("NotifFetcher.fetchNotifs", e);
return fetchOneNotif();
} catch (IOException ioe) {
if (!shouldStop()) {
logger.error("NotifFetcher-run",
"Failed to fetch notification, " +
"stopping thread. Error is: " + ioe, ioe);
logger.debug("NotifFetcher-run",ioe);
}
// no more fetching
return null;
}
}
@Override
protected void setContentsNative(Transferable contents) {
FlavorTable flavorMap = getDefaultFlavorTable();
// Don't use delayed Clipboard rendering for the Transferable's data.
// If we did that, we would call Transferable.getTransferData on
// the Toolkit thread, which is a security hole.
//
// Get all of the target formats into which the Transferable can be
// translated. Then, for each format, translate the data and post
// it to the Clipboard.
DataTransferer dataTransferer = DataTransferer.getInstance();
long[] formatArray = dataTransferer.getFormatsForTransferableAsArray(contents, flavorMap);
declareTypes(formatArray, this);
Map<Long, DataFlavor> formatMap = dataTransferer.getFormatsForTransferable(contents, flavorMap);
for (Map.Entry<Long, DataFlavor> entry : formatMap.entrySet()) {
long format = entry.getKey();
DataFlavor flavor = entry.getValue();
try {
byte[] bytes = DataTransferer.getInstance().translateTransferable(contents, flavor, format);
setData(bytes, format);
} catch (IOException e) {
// Fix 4696186: don't print exception if data with
// javaJVMLocalObjectMimeType failed to serialize.
// May remove this if-check when 5078787 is fixed.
if (!(flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType) &&
e instanceof NotSerializableException)) {
e.printStackTrace();
}
}
}
notifyChanged();
}
public static void main(String[] args) throws Exception {
System.err.println("\nRegression test for bug 6332349\n");
Ping impl = new PingImpl();
Reference<?> ref = new WeakReference<Ping>(impl);
try {
Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0);
Object notSerializable = new Object();
stub.ping(impl, null);
try {
stub.ping(impl, notSerializable);
} catch (MarshalException e) {
if (e.getCause() instanceof NotSerializableException) {
System.err.println("ping invocation failed as expected");
} else {
throw e;
}
}
} finally {
UnicastRemoteObject.unexportObject(impl, true);
}
impl = null;
// Might require multiple calls to System.gc() for weak-references
// processing to be complete. If the weak-reference is not cleared as
// expected we will hang here until timed out by the test harness.
while (true) {
System.gc();
Thread.sleep(20);
if (ref.get() == null) {
break;
}
}
System.err.println("TEST PASSED");
}
/**
* Throws NotSerializableException, since InvalidPropertiesFormatException
* objects are not intended to be serializable.
*/
@java.io.Serial
private void writeObject(java.io.ObjectOutputStream out)
throws NotSerializableException
{
throw new NotSerializableException("Not serializable.");
}
protected Object writeReplace() throws ObjectStreamException {
if (this.serializationId != null) {
return new SerializedBeanFactoryReference(this.serializationId);
}
else {
throw new NotSerializableException("DefaultListableBeanFactory has no serialization id");
}
}
/**
* WriteObject is called to save the state of this permission to a stream.
* The actions are serialized, and the superclass takes care of the name.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException {
if (endpoint != null) {
throw new NotSerializableException("cannot serialize");
}
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null) {
getActions();
}
s.defaultWriteObject();
}
@Override
protected void setContentsNative(Transferable contents) {
FlavorTable flavorMap = getDefaultFlavorTable();
// Don't use delayed Clipboard rendering for the Transferable's data.
// If we did that, we would call Transferable.getTransferData on
// the Toolkit thread, which is a security hole.
//
// Get all of the target formats into which the Transferable can be
// translated. Then, for each format, translate the data and post
// it to the Clipboard.
DataTransferer dataTransferer = DataTransferer.getInstance();
long[] formatArray = dataTransferer.getFormatsForTransferableAsArray(contents, flavorMap);
declareTypes(formatArray, this);
Map<Long, DataFlavor> formatMap = dataTransferer.getFormatsForTransferable(contents, flavorMap);
for (Map.Entry<Long, DataFlavor> entry : formatMap.entrySet()) {
long format = entry.getKey();
DataFlavor flavor = entry.getValue();
try {
byte[] bytes = DataTransferer.getInstance().translateTransferable(contents, flavor, format);
setData(bytes, format);
} catch (IOException e) {
// Fix 4696186: don't print exception if data with
// javaJVMLocalObjectMimeType failed to serialize.
// May remove this if-check when 5078787 is fixed.
if (!(flavor.isMimeTypeEqual(DataFlavor.javaJVMLocalObjectMimeType) &&
e instanceof NotSerializableException)) {
e.printStackTrace();
}
}
}
notifyChanged();
}
/**
* Replaces the {@code CertPath} to be serialized with a
* {@code CertPathRep} object.
*
* @return the {@code CertPathRep} to be serialized
*
* @throws ObjectStreamException if a {@code CertPathRep} object
* representing this certification path could not be created
*/
protected Object writeReplace() throws ObjectStreamException {
try {
return new CertPathRep(type, getEncoded());
} catch (CertificateException ce) {
NotSerializableException nse =
new NotSerializableException
("java.security.cert.CertPath: " + type);
nse.initCause(ce);
throw nse;
}
}
/**
* WriteObject is called to save the state of this permission to a stream.
* The actions are serialized, and the superclass takes care of the name.
*/
private synchronized void writeObject(java.io.ObjectOutputStream s) throws IOException {
if (bundle != null) {
throw new NotSerializableException("cannot serialize");
}
// Write out the actions. The superclass takes care of the name
// call getActions to make sure actions field is initialized
if (actions == null)
getActions();
s.defaultWriteObject();
}
public static void main(String[] args) throws Exception {
System.err.println("\nRegression test for bug 6332349\n");
Ping impl = new PingImpl();
Reference<?> ref = new WeakReference<Ping>(impl);
try {
Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0);
Object notSerializable = new Object();
stub.ping(impl, null);
try {
stub.ping(impl, notSerializable);
} catch (MarshalException e) {
if (e.getCause() instanceof NotSerializableException) {
System.err.println("ping invocation failed as expected");
} else {
throw e;
}
}
} finally {
UnicastRemoteObject.unexportObject(impl, true);
}
impl = null;
// Might require multiple calls to System.gc() for weak-references
// processing to be complete. If the weak-reference is not cleared as
// expected we will hang here until timed out by the test harness.
while (true) {
System.gc();
Thread.sleep(20);
if (ref.get() == null) {
break;
}
}
System.err.println("TEST PASSED");
}
protected Object writeReplace() throws ObjectStreamException {
if (this.beanFactory != null && this.beanName != null) {
return new SerializedEntityManagerFactoryBeanReference(this.beanFactory, this.beanName);
}
else {
throw new NotSerializableException("EntityManagerFactoryBean does not run within a BeanFactory");
}
}
public static void main(String[] args) throws Exception {
System.err.println("\nRegression test for bug 6332349\n");
Ping impl = new PingImpl();
Reference<?> ref = new WeakReference<Ping>(impl);
try {
Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0);
Object notSerializable = new Object();
stub.ping(impl, null);
try {
stub.ping(impl, notSerializable);
} catch (MarshalException e) {
if (e.getCause() instanceof NotSerializableException) {
System.err.println("ping invocation failed as expected");
} else {
throw e;
}
}
} finally {
UnicastRemoteObject.unexportObject(impl, true);
}
impl = null;
// Might require multiple calls to System.gc() for weak-references
// processing to be complete. If the weak-reference is not cleared as
// expected we will hang here until timed out by the test harness.
while (true) {
System.gc();
Thread.sleep(20);
if (ref.get() == null) {
break;
}
}
System.err.println("TEST PASSED");
}
@Override
public void deserialize(final Fields fields) throws StreamCorruptedException, NotSerializableException {
final String r = fields.getAndRemoveObject("region", String.class);
fields.setFields(this);
WorldGuardPlatform platform = WorldGuard.getInstance().getPlatform();
ProtectedRegion region = platform.getRegionContainer().get(BukkitAdapter.adapt(world)).getRegion(r);
if (region == null)
throw new StreamCorruptedException("Invalid region " + r + " in world " + world);
this.region = region;
}
private static ObjectMapper getMapperOrThrows(final HttpContentType contentType) {
switch (contentType) {
case ORION:
return jsonObjectMapper;
case JSON:
return jsonObjectMapper;
case CBOR:
return cborObjectMapper;
default:
throw new OrionException(OrionErrorCode.OBJECT_UNSUPPORTED_TYPE, new NotSerializableException());
}
}