All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.java.truelicense.xml.XmlCodec Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (C) 2005-2013 Schlichtherle IT Services.
 * All rights reserved. Use is subject to license terms.
 */
package net.java.truelicense.xml;

import java.beans.*;
import java.io.*;
import javax.annotation.*;
import javax.annotation.concurrent.*;
import net.java.truelicense.core.codec.Codec;
import net.java.truelicense.core.io.*;
import net.java.truelicense.obfuscate.Obfuscate;

/**
 * A codec which encodes/decodes XML with an
 * {@link XMLEncoder}/{@link XMLDecoder}.
 *
 * @author Christian Schlichtherle
 */
@Immutable
public class XmlCodec implements Codec {

    @Obfuscate
    private static final String CONTENT_TYPE = "application/xml; charset=utf-8";

    @Obfuscate
    private static final String CONTENT_TRANSFER_ENCODING = "8bit";

    /**
     * {@inheritDoc}
     * 

* The implementation in the class {@link XmlCodec} * returns {@code "application/xml; charset=utf-8"}. * * @see RFC 3023 */ @Override public final String contentType() { return CONTENT_TYPE; } /** * {@inheritDoc} *

* The implementation in the class {@link XmlCodec} * returns {@code "8bit"}. * * @see RFC 3023 */ @Override public final String contentTransferEncoding() { return CONTENT_TRANSFER_ENCODING; } @Override public void encode(final Sink sink, final @CheckForNull Object obj) throws Exception { final ZeroToleranceListener ztl = new ZeroToleranceListener(); final XMLEncoder enc = encoder(sink.output()); try { enc.setExceptionListener(ztl); enc.writeObject(obj); } finally { enc.close(); // may pass exception to ztl! } ztl.check(); } protected XMLEncoder encoder(OutputStream out) { return new XMLEncoder(out); } @Override public @Nullable Object decode(final Source source) throws Exception { final Object obj; final ZeroToleranceListener ztl = new ZeroToleranceListener(); final XMLDecoder dec = decoder(source.input()); try { dec.setExceptionListener(ztl); obj = dec.readObject(); } finally { dec.close(); // may pass exception to ztl! } ztl.check(); return obj; } protected XMLDecoder decoder(InputStream in) { return new XMLDecoder(in); } @NotThreadSafe private static class ZeroToleranceListener implements ExceptionListener { Exception ex; @Override public void exceptionThrown(final Exception ex) { assert null != ex; if (null == this.ex) this.ex = ex; // don't overwrite prior exception } void check() throws Exception { if (null != ex) throw ex; } } // ZeroToleranceListener }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy