Example usage for java.io ObjectOutput flush

List of usage examples for java.io ObjectOutput flush

Introduction

In this page you can find the example usage for java.io ObjectOutput flush.

Prototype

public void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:info.magnolia.cms.core.version.BaseVersionManager.java

/**
 * Create version of the specified node and all child nodes based on the given <code>Rule</code>.
 * @param node to be versioned/*www . ja va  2s  .com*/
 * @param rule
 * @param userName
 * @return newly created version node
 * @throws UnsupportedOperationException if repository implementation does not support Versions API
 * @throws javax.jcr.RepositoryException if any repository error occurs
 */
protected Version createVersion(Node node, Rule rule, String userName)
        throws UnsupportedRepositoryOperationException, RepositoryException {
    if (isInvalidMaxVersions()) {
        log.debug("Ignore create version, MaxVersionIndex < 1");
        log.debug("Returning root version of the source node");
        return node.getVersionHistory().getRootVersion();
    }

    CopyUtil.getInstance().copyToversion(node, new RuleBasedNodePredicate(rule));
    Node versionedNode = this.getVersionedNode(node);

    checkAndAddMixin(versionedNode);
    Node systemInfo = this.getSystemNode(versionedNode);
    // add serialized rule which was used to create this version
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        ObjectOutput objectOut = new ObjectOutputStream(out);
        objectOut.writeObject(rule);
        objectOut.flush();
        objectOut.close();
        // PROPERTY_RULE is not a part of MetaData to allow versioning of node types which does NOT support MetaData
        systemInfo.setProperty(PROPERTY_RULE, new String(Base64.encodeBase64(out.toByteArray())));
    } catch (IOException e) {
        throw new RepositoryException("Unable to add serialized Rule to the versioned content");
    }
    // add all system properties for this version
    systemInfo.setProperty(ContentVersion.VERSION_USER, userName);
    systemInfo.setProperty(ContentVersion.NAME, node.getName());

    versionedNode.save();
    // add version
    Version newVersion = versionedNode.checkin();
    versionedNode.checkout();

    try {
        this.setMaxVersionHistory(versionedNode);
    } catch (RepositoryException re) {
        log.error("Failed to limit version history to the maximum configured", re);
        log.error("New version has already been created");
    }

    return newVersion;
}

From source file:cybervillains.ca.KeyStoreManager.java

private synchronized void persistCertMap() {
    try {/*w  w  w . java  2s  .  c om*/
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, CERTMAP_SER_FILE)));
        out.writeObject(_certMap);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        // writing, this shouldn't happen...
        e.printStackTrace();
    } catch (IOException e) {
        // big problem!
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

private synchronized void persistSubjectMap() {
    try {//from w ww .j  a v a2  s.c o m
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, SUBJMAP_SER_FILE)));
        out.writeObject(_subjectMap);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        // writing, this shouldn't happen...
        e.printStackTrace();
    } catch (IOException e) {
        // big problem!
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

private synchronized void persistPublicKeyMap() {
    try {//  w  ww.ja va 2 s .c o m
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, PUB_KEYMAP_SER_FILE)));
        out.writeObject(_mappedPublicKeys);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        // writing, won't happen
        e.printStackTrace();
    } catch (IOException e) {
        // very bad
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:cybervillains.ca.KeyStoreManager.java

private synchronized void persistKeyPairMap() {
    try {//from  www.  j  a  v  a2  s  .  co  m
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(new File(root, KEYMAP_SER_FILE)));
        out.writeObject(_rememberedPrivateKeys);
        out.flush();
        out.close();
    } catch (FileNotFoundException e) {
        // writing, won't happen.
        e.printStackTrace();
    } catch (IOException e) {
        // very bad
        e.printStackTrace();
        throw new Error(e);
    }
}

From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java

/**
 * request body ?//from ww  w  .jav a2 s.  com
 * 
 * <pre>
* 
*     body:
* 
*     byte[] data :  
* 
*          serialize(interface_name, method_name, method_param_desc, method_param_value, attachments_size, attachments_value) 
* 
*   method_param_desc:  for_each (string.append(method_param_interface_name))
* 
*   method_param_value: for_each (method_param_name, method_param_value)
* 
*     attachments_value:  for_each (attachment_name, attachment_value)
* 
* </pre>
 * 
 * @param request
 * @return
 * @throws IOException
 */
private byte[] encodeRequest(Channel channel, Request request) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectOutput output = createOutput(outputStream);
    addMethodInfo(output, request);

    Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
            channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue()));

    if (request.getArguments() != null && request.getArguments().length > 0) {
        for (Object obj : request.getArguments()) {
            serialize(output, obj, serialization);
        }
    }

    if (request.getAttachments() == null || request.getAttachments().isEmpty()) {
        // empty attachments
        output.writeShort(0);
    } else {
        // ?copyattachment????request???
        Map<String, String> attachments = copyMap(request.getAttachments());
        replaceAttachmentParamsBySign(channel, attachments);

        addAttachment(output, attachments);
    }

    output.flush();
    byte[] body = outputStream.toByteArray();

    byte flag = MotanConstants.FLAG_REQUEST;

    output.close();
    Boolean usegz = channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(),
            URLParamType.usegz.getBooleanValue());
    int minGzSize = channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(),
            URLParamType.mingzSize.getIntValue());
    return encode(compress(body, usegz, minGzSize), flag, request.getRequestId());
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

public void writeExternal(ObjectOutput objectOutput) throws IOException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("serializing XFormsFormsProcessorImpl");
    }//w w  w .j  a va  2  s . c o  m
    try {
        if (getXForms().getDocumentElement().hasAttribute("bf:serialized")) {
            objectOutput.writeUTF(DOMUtil.serializeToString(getXForms()));
        } else {
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:baseURI",
                    getBaseURI());
            getXForms().getDocumentElement().setAttributeNS(NamespaceConstants.BETTERFORM_NS, "bf:serialized",
                    "true");

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("....::: XForms before writing ::::....");
                DOMUtil.prettyPrintDOM(getXForms());
            }

            DefaultSerializer serializer = new DefaultSerializer(this);
            Document serializedForm = serializer.serialize();

            StringWriter stringWriter = new StringWriter();
            Transformer transformer = null;
            StreamResult result = new StreamResult(stringWriter);
            try {
                transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                transformer.transform(new DOMSource(serializedForm), result);
            } catch (TransformerConfigurationException e) {
                throw new IOException("TransformerConfiguration invalid: " + e.getMessage());
            } catch (TransformerException e) {
                throw new IOException("Error during serialization transform: " + e.getMessage());
            }
            objectOutput.writeUTF(stringWriter.getBuffer().toString());
        }
    } catch (XFormsException e) {
        throw new IOException("baseURI couldn't be set");
    }

    objectOutput.flush();
    objectOutput.close();

}

From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java

/**
 * response body ?/*from  ww w. j  av  a 2 s  .c  om*/
 * 
 * <pre>
* 
* body:
* 
*     byte[] :  serialize (result) or serialize (exception)
* 
* </pre>
 *
 * @param channel
 * @param value
 * @return
 * @throws IOException
 */
private byte[] encodeResponse(Channel channel, Response value) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ObjectOutput output = createOutput(outputStream);
    Serialization serialization = ExtensionLoader.getExtensionLoader(Serialization.class).getExtension(
            channel.getUrl().getParameter(URLParamType.serialize.getName(), URLParamType.serialize.getValue()));

    byte flag = 0;

    output.writeLong(value.getProcessTime());

    if (value.getException() != null) {
        output.writeUTF(value.getException().getClass().getName());
        serialize(output, value.getException(), serialization);
        flag = MotanConstants.FLAG_RESPONSE_EXCEPTION;
    } else if (value.getValue() == null) {
        flag = MotanConstants.FLAG_RESPONSE_VOID;
    } else {
        output.writeUTF(value.getValue().getClass().getName());
        serialize(output, value.getValue(), serialization);
        // v2?responseattachment
        Map<String, String> attachments = value.getAttachments();
        if (attachments != null) {
            String signed = attachments.get(ATTACHMENT_SIGN);
            String unSigned = attachments.get(UN_ATTACHMENT_SIGN);
            attachments.clear(); // attachment????

            if (StringUtils.isNotBlank(signed)) {
                attachments.put(ATTACHMENT_SIGN, signed);
            }
            if (StringUtils.isNotBlank(unSigned)) {
                attachments.put(UN_ATTACHMENT_SIGN, unSigned);
            }
        }
        if (attachments != null && !attachments.isEmpty()) {// ??
            addAttachment(output, attachments);
        } else {
            // empty attachments
            output.writeShort(0);
        }
        flag = MotanConstants.FLAG_RESPONSE_ATTACHMENT; // v2flag
    }

    output.flush();

    byte[] body = outputStream.toByteArray();

    output.close();
    Boolean usegz = channel.getUrl().getBooleanParameter(URLParamType.usegz.getName(),
            URLParamType.usegz.getBooleanValue());
    int minGzSize = channel.getUrl().getIntParameter(URLParamType.mingzSize.getName(),
            URLParamType.mingzSize.getIntValue());
    return encode(compress(body, usegz, minGzSize), flag, value.getRequestId());
}

From source file:org.apache.cloudstack.saml.SAML2AuthManagerImpl.java

protected boolean initSP() {
    KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
    if (keyStoreVO == null) {
        try {//w w  w  .jav a  2s.  c o m
            KeyPair keyPair = SAMLUtils.generateRandomKeyPair();
            _ksDao.save(SAMLPluginConstants.SAMLSP_KEYPAIR, SAMLUtils.savePrivateKey(keyPair.getPrivate()),
                    SAMLUtils.savePublicKey(keyPair.getPublic()), "samlsp-keypair");
            keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
            s_logger.info("No SAML keystore found, created and saved a new Service Provider keypair");
        } catch (NoSuchProviderException | NoSuchAlgorithmException e) {
            s_logger.error("Unable to create and save SAML keypair: " + e.toString());
        }
    }

    String spId = SAMLServiceProviderID.value();
    String spSsoUrl = SAMLServiceProviderSingleSignOnURL.value();
    String spSloUrl = SAMLServiceProviderSingleLogOutURL.value();
    String spOrgName = SAMLServiceProviderOrgName.value();
    String spOrgUrl = SAMLServiceProviderOrgUrl.value();
    String spContactPersonName = SAMLServiceProviderContactPersonName.value();
    String spContactPersonEmail = SAMLServiceProviderContactEmail.value();
    KeyPair spKeyPair = null;
    X509Certificate spX509Key = null;
    if (keyStoreVO != null) {
        PrivateKey privateKey = SAMLUtils.loadPrivateKey(keyStoreVO.getCertificate());
        PublicKey publicKey = SAMLUtils.loadPublicKey(keyStoreVO.getKey());
        if (privateKey != null && publicKey != null) {
            spKeyPair = new KeyPair(publicKey, privateKey);
            KeystoreVO x509VO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_X509CERT);
            if (x509VO == null) {
                try {
                    spX509Key = SAMLUtils.generateRandomX509Certificate(spKeyPair);
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ObjectOutput out = new ObjectOutputStream(bos);
                    out.writeObject(spX509Key);
                    out.flush();
                    _ksDao.save(SAMLPluginConstants.SAMLSP_X509CERT,
                            Base64.encodeBase64String(bos.toByteArray()), "", "samlsp-x509cert");
                    bos.close();
                } catch (NoSuchAlgorithmException | NoSuchProviderException | CertificateEncodingException
                        | SignatureException | InvalidKeyException | IOException e) {
                    s_logger.error("SAML Plugin won't be able to use X509 signed authentication");
                }
            } else {
                try {
                    ByteArrayInputStream bi = new ByteArrayInputStream(
                            Base64.decodeBase64(x509VO.getCertificate()));
                    ObjectInputStream si = new ObjectInputStream(bi);
                    spX509Key = (X509Certificate) si.readObject();
                    bi.close();
                } catch (IOException | ClassNotFoundException ignored) {
                    s_logger.error(
                            "SAML Plugin won't be able to use X509 signed authentication. Failed to load X509 Certificate from Database.");
                }
            }
        }
    }
    if (spKeyPair != null && spX509Key != null && spId != null && spSsoUrl != null && spSloUrl != null
            && spOrgName != null && spOrgUrl != null && spContactPersonName != null
            && spContactPersonEmail != null) {
        _spMetadata.setEntityId(spId);
        _spMetadata.setOrganizationName(spOrgName);
        _spMetadata.setOrganizationUrl(spOrgUrl);
        _spMetadata.setContactPersonName(spContactPersonName);
        _spMetadata.setContactPersonEmail(spContactPersonEmail);
        _spMetadata.setSsoUrl(spSsoUrl);
        _spMetadata.setSloUrl(spSloUrl);
        _spMetadata.setKeyPair(spKeyPair);
        _spMetadata.setSigningCertificate(spX509Key);
        _spMetadata.setEncryptionCertificate(spX509Key);
        return true;
    }
    return false;
}

From source file:org.apache.geode.internal.InternalDataSerializer.java

/**
 * write an object in java Serializable form with a SERIALIZABLE DSCODE so that it can be
 * deserialized with DataSerializer.readObject()
 * /*from  w  w w . j  a va2s  . c om*/
 * @param o the object to serialize
 * @param out the data output to serialize to
 */
public static void writeSerializableObject(Object o, DataOutput out) throws IOException {
    out.writeByte(SERIALIZABLE);
    if (out instanceof ObjectOutputStream) {
        ((ObjectOutputStream) out).writeObject(o);
    } else {
        OutputStream stream;
        if (out instanceof OutputStream) {
            stream = (OutputStream) out;

        } else {
            final DataOutput out2 = out;
            stream = new OutputStream() {
                @Override
                public void write(int b) throws IOException {
                    out2.write(b);
                }
            };
        }
        boolean wasDoNotCopy = false;
        if (out instanceof HeapDataOutputStream) {
            // To fix bug 52197 disable doNotCopy mode
            // while serialize with an ObjectOutputStream.
            // The problem is that ObjectOutputStream keeps
            // an internal byte array that it reuses while serializing.
            wasDoNotCopy = ((HeapDataOutputStream) out).setDoNotCopy(false);
        }
        try {
            ObjectOutput oos = new ObjectOutputStream(stream);
            if (stream instanceof VersionedDataStream) {
                Version v = ((VersionedDataStream) stream).getVersion();
                if (v != null && v != Version.CURRENT) {
                    oos = new VersionedObjectOutput(oos, v);
                }
            }
            oos.writeObject(o);
            // To fix bug 35568 just call flush. We can't call close because
            // it calls close on the wrapped OutputStream.
            oos.flush();
        } finally {
            if (wasDoNotCopy) {
                ((HeapDataOutputStream) out).setDoNotCopy(true);
            }
        }
    }
}