Example usage for java.io ObjectOutput writeObject

List of usage examples for java.io ObjectOutput writeObject

Introduction

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

Prototype

public void writeObject(Object obj) throws IOException;

Source Link

Document

Write an object to the underlying storage or stream.

Usage

From source file:edu.ucsb.cs.cs185.easytrade.MainActivity.java

@Override
public void onStop() {
    super.onStop();
    //Write Database to disk
    sortData();/*from   w  w w .j  a v  a2 s  . c o m*/
    EasyTradeDataBase.setITEMID_LOWER_BOUND(EasyTradeDataBase.getITEMID_LOWER_BOUND() + 1);
    try {
        File outFile = new File(Environment.getExternalStorageDirectory(), "EasyTradeDataBase.ser");
        ObjectOutput out = new ObjectOutputStream(new FileOutputStream(outFile));
        out.writeObject(EasyTradeDataBase);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.splicemachine.orc.predicate.SpliceORCPredicate.java

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    ArrayUtil.writeIntArray(out, baseColumnMap);
    out.writeBoolean(qualifiers != null);
    if (qualifiers != null) {
        out.writeInt(qualifiers.length);
        out.writeInt(qualifiers[0].length);
        for (int i = 0; i < qualifiers[0].length; i++) {
            out.writeObject(qualifiers[0][i]);
        }//www  .  j  av  a  2  s . com
        for (int and_idx = 1; and_idx < qualifiers.length; and_idx++) {
            out.writeInt(qualifiers[and_idx].length);
            for (int or_idx = 0; or_idx < qualifiers[and_idx].length; or_idx++) {
                out.writeObject(qualifiers[and_idx][or_idx]);
            }
        }
    }
    out.writeObject(structType.json());
}

From source file:org.grails.ignite.DeferredStartIgniteSpringBean.java

/**
 * {@inheritDoc}// w  w  w . ja v a 2  s  . c o m
 */
@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(g);
}

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//  ww  w  .  j av  a2s.co  m
 * @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:com.github.naoghuman.abclist.model.Exercise.java

@Override
public void writeExternal(ObjectOutput out) throws IOException {
    out.writeLong(this.getId());
    out.writeLong(this.getTopicId());
    out.writeLong(this.getGenerationTime());
    out.writeLong(this.getFinishedTime());
    out.writeBoolean(this.isConsolidated());
    out.writeBoolean(this.isReady());
    out.writeObject(this.getChoosenTime());
}

From source file:com.angrygiant.mule.mqtt.MqttModule.java

/**
 * Publish processor - used to publish a message to a given topic on the MQTT broker.
 * <p/>/*from   w w  w  . j  ava  2s. c om*/
 * <p/>
 * {@sample.xml ../../../doc/mqtt-connector.xml.sample mqtt:publish}
 *
 * @param topicName       topic to publish message to
 * @param message         string message to publish (if blank/null, uses messagePayload)
 * @param qos             qos level to use when publishing message
 * @param messagePayload  injects passed payload into this object (for possible use)
 * @param outboundHeaders injected outbound headers map so we can set them prior to leaving
 * @return delivered byte[] payload of MqttMessage
 */
@Processor
public byte[] publish(String topicName, String message, @Optional @Default("1") int qos,
        @Payload Object messagePayload, @OutboundHeaders Map<String, Object> outboundHeaders)
        throws MqttException, IOException {
    byte[] payloadBytes;

    logger.debug("Connecting to Broker...");
    if (!this.client.isConnected()) {
        this.client.connect();
        logger.info(
                "Connected to " + getBrokerHostName() + " on port " + getBrokerPort() + " as " + getClientId());
    } else {
        logger.debug("Already connected to Broker");
    }

    if (qos < 0 || qos > 2) {
        logger.warn("QOS is invalid, setting to default value of 2");
        qos = 2;
    }

    logger.debug("Decipher whether we're using String or Message payload");
    if (StringUtils.isNotBlank(message)) {
        logger.debug("Using the string message...");
        payloadBytes = message.getBytes();
    } else if (messagePayload instanceof byte[]) {
        logger.debug("Message payload is a byte array, using it directly...");
        payloadBytes = (byte[]) messagePayload;
    } else {
        logger.info("Converting message payload to a byte array...");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(bos);

        try {
            out.writeObject(messagePayload);
            payloadBytes = bos.toByteArray();
        } finally {
            bos.close();
            out.close();
        }
    }

    logger.debug("Retrieving topic '" + topicName + "'");
    MqttTopic topic = this.client.getTopic(topicName);

    logger.debug("Preparing message...");
    MqttMessage mqttMessage = new MqttMessage(payloadBytes);
    mqttMessage.setQos(qos);

    logger.debug("publishing message to broker...");
    MqttDeliveryToken token = topic.publish(mqttMessage);

    logger.trace("Waiting for default timeout of 5minutes...");
    token.waitForCompletion(900000);

    if (outboundHeaders == null) {
        outboundHeaders = new HashMap<String, Object>();
    }

    outboundHeaders.put(MqttTopicListener.TOPIC_NAME, topic.getName());
    outboundHeaders.put(MqttTopicListener.MESSAGE_DUPLICATE, mqttMessage.isDuplicate());
    outboundHeaders.put(MqttTopicListener.MESSAGE_RETAIN, mqttMessage.isRetained());
    outboundHeaders.put(MqttTopicListener.MESSAGE_QOS, mqttMessage.getQos());
    outboundHeaders.put(MqttTopicListener.CLIENT_ID, this.client.getClientId());
    outboundHeaders.put(MqttTopicListener.CLIENT_URI, this.client.getServerURI());

    return mqttMessage.getPayload();
}

From source file:com.conwet.silbops.model.Subscription.java

@Override
public void writeExternal(ObjectOutput output) throws IOException {

    output.writeObject(id);
    output.writeObject(contextFunction);

    // write the attributes size
    output.writeInt(constraints.size());

    for (Entry<Attribute, Set<Constraint>> entry : constraints.entrySet()) {

        // write the attribute
        Attribute attribute = entry.getKey();
        attributeExt.writeExternal(output, attribute);

        // write constraints size and their values
        Set<Constraint> constrSet = entry.getValue();
        output.writeInt(constrSet.size());

        for (Constraint constraint : constrSet) {

            constraintExt.writeExternal(output, constraint);
        }//from ww w  . j av  a  2s  .  co  m
    }
}

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

protected boolean initSP() {
    KeystoreVO keyStoreVO = _ksDao.findByName(SAMLPluginConstants.SAMLSP_KEYPAIR);
    if (keyStoreVO == null) {
        try {/*from w ww.  ja  v a  2 s .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.springframework.webflow.engine.impl.FlowExecutionImpl.java

public void writeExternal(ObjectOutput out) throws IOException {
    out.writeObject(status);
    out.writeObject(flowSessions);
}

From source file:org.fosstrak.epcis.repository.query.QuerySubscription.java

/**
 * Updates the subscription in the database. This is required in order to
 * correctly re-initialize the subscriptions, especially the
 * lastTimeExecuted field, after a context restart.
 * <p>//  ww  w  . j  a  v a  2s.  c o  m
 * TODO: This is a back-end method: move this method to the
 * QueryOperationsBackend and delegate to it (thus we would need a reference
 * to the QueryOperationsBackend in this class).
 * 
 * @param lastTimeExecuted
 *            The new lastTimeExecuted.
 */
private void updateSubscription(final Calendar lastTimeExecuted) {
    String jndiName = getProperties().getProperty("jndi.datasource.name", "java:comp/env/jdbc/EPCISDB");
    try {
        // open a database connection
        Context ctx = new InitialContext();
        DataSource db = (DataSource) ctx.lookup(jndiName);
        Connection dbconnection = db.getConnection();

        // update the subscription in the database
        String update = "UPDATE subscription SET lastexecuted=(?), params=(?)" + " WHERE subscriptionid=(?);";
        PreparedStatement stmt = dbconnection.prepareStatement(update);
        LOG.debug("SQL: " + update);
        Timestamp ts = new Timestamp(lastTimeExecuted.getTimeInMillis());
        String time = ts.toString();
        stmt.setString(1, time);
        LOG.debug("       query param 1: " + time);
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        ObjectOutput out = new ObjectOutputStream(outStream);
        out.writeObject(queryParams);
        ByteArrayInputStream inStream = new ByteArrayInputStream(outStream.toByteArray());
        stmt.setBinaryStream(2, inStream, inStream.available());
        LOG.debug("       query param 2: [" + inStream.available() + " bytes]");
        stmt.setString(3, subscriptionID);
        LOG.debug("       query param 3: " + subscriptionID);
        stmt.executeUpdate();
        dbconnection.commit();

        // close the database connection
        dbconnection.close();
    } catch (SQLException e) {
        String msg = "An SQL error occurred while updating the subscriptions in the database.";
        LOG.error(msg, e);
    } catch (IOException e) {
        String msg = "Unable to update the subscription in the database: " + e.getMessage();
        LOG.error(msg, e);
    } catch (NamingException e) {
        String msg = "Unable to find JNDI data source with name " + jndiName;
        LOG.error(msg, e);
    }
}