Example usage for java.io ObjectOutputStream flush

List of usage examples for java.io ObjectOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.apache.geode.internal.net.SSLSocketIntegrationTest.java

@Test
public void securedSocketTransmissionShouldWork() throws Exception {
    this.serverSocket = this.socketCreator.createServerSocket(0, 0, this.localHost);
    this.serverThread = startServer(this.serverSocket);

    int serverPort = this.serverSocket.getLocalPort();
    this.clientSocket = this.socketCreator.connectForServer(this.localHost, serverPort);

    // transmit expected string from Client to Server
    ObjectOutputStream output = new ObjectOutputStream(this.clientSocket.getOutputStream());
    output.writeObject(MESSAGE);/*  ww w.j a  v  a2  s .  c o m*/
    output.flush();

    // this is the real assertion of this test
    await().atMost(1, TimeUnit.MINUTES)
            .until(() -> assertThat(this.messageFromClient.get()).isEqualTo(MESSAGE));
}

From source file:com.feedzai.fos.impl.weka.utils.Cloner.java

/**
 * Creates a clonner from the given object.
 *
 * @param serializable the object to clone
 * @throws IOException when there were problems serializing the object
 *///from   w  ww.  ja v  a2  s  .  c  o m
public Cloner(T serializable) throws IOException {
    checkNotNull(serializable, "The serialized object cannot be null");

    ObjectOutputStream oos = null;
    ByteArrayOutputStream baos = null;

    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(serializable);
        oos.flush();

        this.serializedObject = baos.toByteArray();
    } finally {
        IOUtils.closeQuietly(baos);
        IOUtils.closeQuietly(oos);
    }
}

From source file:org.openspaces.itest.remoting.simple.plain.SimpleRemotingTests.java

@Test
public void testSerializationOfAsyncRemotingEntry() throws IOException, ClassNotFoundException {
    SpaceRemotingEntryFactory remotingEntryFactory = new SpaceRemotingEntryMetadataFactory();
    HashedSpaceRemotingEntry entry = remotingEntryFactory.createHashEntry();
    entry = entry.buildInvocation("test", "test", null, null);
    entry.setOneWay(true);/*w w  w.jav  a  2  s  .  co  m*/
    entry.setMetaArguments(new Object[] { new Integer(1) });
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(byteArrayOutputStream);
    oos.writeObject(entry);
    oos.flush();
    byte[] bytes = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream);
    SpaceRemotingEntry invocation = (SpaceRemotingEntry) ois.readObject();
    compareAsyncInvocationNullableFields(entry, invocation);

    entry = (HashedSpaceRemotingEntry) entry.buildResult("result");
    entry.setInstanceId(1);
    byteArrayOutputStream = new ByteArrayOutputStream();
    oos = new ObjectOutputStream(byteArrayOutputStream);
    oos.writeObject(entry);
    oos.flush();
    bytes = byteArrayOutputStream.toByteArray();
    byteArrayInputStream = new ByteArrayInputStream(bytes);
    ois = new ObjectInputStream(byteArrayInputStream);
    SpaceRemotingEntry invocationResult = (SpaceRemotingEntry) ois.readObject();
    compareAsyncResultNullableFields(entry, invocationResult);
}

From source file:com.threerings.cast.bundle.tools.MetadataBundlerTask.java

/**
 * Performs the actual work of the task.
 *//*from   w ww .  j  av  a  2s .  c o m*/
@Override
public void execute() throws BuildException {
    // make sure everythign was set up properly
    ensureSet(_actionDef, "Must specify the action sequence " + "definitions via the 'actiondef' attribute.");
    ensureSet(_classDef, "Must specify the component class definitions " + "via the 'classdef' attribute.");
    ensureSet(_target, "Must specify the path to the target bundle " + "file via the 'target' attribute.");

    // make sure we can write to the target bundle file
    OutputStream fout = null;
    try {

        // parse our metadata
        Tuple<Map<String, ActionSequence>, Map<String, TileSet>> tuple = parseActions();
        Map<String, ActionSequence> actions = tuple.left;
        Map<String, TileSet> actionSets = tuple.right;
        Map<String, ComponentClass> classes = parseClasses();

        fout = createOutputStream(_target);

        // throw the serialized actions table in there
        fout = nextEntry(fout, BundleUtil.ACTIONS_PATH);
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(actions);
        oout.flush();

        // throw the serialized action tilesets table in there
        fout = nextEntry(fout, BundleUtil.ACTION_SETS_PATH);
        oout = new ObjectOutputStream(fout);
        oout.writeObject(actionSets);
        oout.flush();

        // throw the serialized classes table in there
        fout = nextEntry(fout, BundleUtil.CLASSES_PATH);
        oout = new ObjectOutputStream(fout);
        oout.writeObject(classes);
        oout.flush();

        // close it up and we're done
        fout.close();

    } catch (IOException ioe) {
        String errmsg = "Unable to output to target bundle " + "[path=" + _target.getPath() + "].";
        throw new BuildException(errmsg, ioe);

    } finally {
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException ioe) {
                // nothing to complain about here
            }
        }
    }
}

From source file:org.apache.ojb.broker.locking.LockManagerServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // update counter
    numRequests++;/*from w w w . ja  v  a  2 s . c o  m*/

    try {
        // read request:
        LockManagerRemoteImpl.LockInfo info = (LockManagerRemoteImpl.LockInfo) buildObjectFromRequest(request);
        Object result = null;
        // now execute the command specified by the selector
        try {
            switch (info.methodName) {
            case LockManagerRemoteImpl.METHOD_READ_LOCK: {
                result = new Boolean(lockmanager.readLock(info.key, info.resourceId, info.isolationLevel));
                break;
            }
            case LockManagerRemoteImpl.METHOD_RELEASE_SINGLE_LOCK: {
                result = new Boolean(lockmanager.releaseLock(info.key, info.resourceId));
                break;
            }
            case LockManagerRemoteImpl.METHOD_RELEASE_LOCKS: {
                lockmanager.releaseLocks(info.key);
                result = Boolean.TRUE;
                break;
            }
            case LockManagerRemoteImpl.METHOD_WRITE_LOCK: {
                result = new Boolean(lockmanager.writeLock(info.key, info.resourceId, info.isolationLevel));
                break;
            }
            case LockManagerRemoteImpl.METHOD_UPGRADE_LOCK: {
                result = new Boolean(lockmanager.upgradeLock(info.key, info.resourceId, info.isolationLevel));
                break;
            }
            case LockManagerRemoteImpl.METHOD_CHECK_READ: {
                result = new Boolean(lockmanager.hasRead(info.key, info.resourceId));
                break;
            }
            case LockManagerRemoteImpl.METHOD_CHECK_WRITE: {
                result = new Boolean(lockmanager.hasWrite(info.key, info.resourceId));
                break;
            }
            case LockManagerRemoteImpl.METHOD_CHECK_UPGRADE: {
                result = new Boolean(lockmanager.hasUpgrade(info.key, info.resourceId));
                break;
            }
            case LockManagerRemoteImpl.METHOD_LOCK_INFO: {
                result = lockmanager.getLockInfo();
                break;
            }
            case LockManagerRemoteImpl.METHOD_LOCK_TIMEOUT: {
                result = new Long(lockmanager.getLockTimeout());
                break;
            }
            case LockManagerRemoteImpl.METHOD_BLOCK_TIMEOUT: {
                result = new Long(lockmanager.getBlockTimeout());
                break;
            }
            //                    case LockManagerRemoteImpl.METHOD_LOCK_TIMEOUT_SET:
            //                        {
            //                            lockmanager.setLockTimeout(info.lockTimeout);
            //                            break;
            //                        }
            //
            //                    case LockManagerRemoteImpl.METHOD_BLOCK_TIMEOUT_SET:
            //                        {
            //                            lockmanager.setBlockTimeout(info.blockTimeout);
            //                            break;
            //                        }
            default: {
                throw new LockRuntimeException("Unknown command:" + info.methodName);
            }
            }
        } catch (RuntimeException e) {
            result = new LockRuntimeException("Error while invoke specified method in servlet.", e);
        }

        ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
        oos.writeObject(result);
        oos.flush();
        oos.close();
    } catch (Throwable t) {
        lastError = t;
        t.printStackTrace();
    }
}

From source file:com.limegroup.gnutella.licenses.LicenseCache.java

/**
 * Write cache so that we only have to calculate them once.
 *///  w  ww.ja v a2s  .  com
public synchronized void persistCache() {
    if (!dirty)
        return;

    ObjectOutputStream oos = null;
    try {
        oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(CACHE_FILE)));
        oos.writeObject(licenses);
        oos.writeObject(data);
        oos.flush();
    } catch (IOException e) {
        ErrorService.error(e);
    } finally {
        IOUtils.close(oos);
    }

    dirty = false;
}

From source file:org.pentaho.reporting.libraries.fonts.encoding.generator.EncodingGenerator.java

public void generatedFormatA(final Properties specifications, final BufferedReader input,
        final OutputStream output) throws IOException {
    if (input == null) {
        throw new NullPointerException();
    }/*from   w  w  w  .j  a v a 2s . c  o  m*/
    if (output == null) {
        throw new NullPointerException();
    }
    if (specifications == null) {
        throw new NullPointerException();
    }

    final Integer[] data = new Integer[256];
    data[0] = ZERO;

    String s = input.readLine();
    while (s != null) {
        if (s.length() > 0 && s.charAt(0) == '#') {
            s = input.readLine();
            continue;
        }

        final StringTokenizer strtok = new StringTokenizer(s);
        if (strtok.hasMoreTokens() == false) {
            s = input.readLine();
            continue;
        }
        final String sourceChar = strtok.nextToken().trim();
        if (sourceChar.length() == 0) {
            s = input.readLine();
            continue;
        }

        final Integer sourceVal = Integer.decode(sourceChar);
        if (strtok.hasMoreTokens()) {
            final String targetChar = strtok.nextToken();
            if ((targetChar.length() > 0 && targetChar.charAt(0) == '#') == false) {
                data[sourceVal.intValue()] = Integer.decode(targetChar);
            }
        }

        s = input.readLine();
    }

    final int[] indices = new int[256];
    final int[] values = new int[256];

    int index = 0;
    int prevIdx = 0;
    for (int i = 1; i < data.length; i++) {
        final Integer integer = data[i];
        if (integer == null) {
            // no entry ... this means, we use the standard mapping ..
            continue;
        }

        final Integer prev = data[prevIdx];
        values[index] = integer.intValue() - prev.intValue();
        indices[index] = i - prevIdx;

        prevIdx = i;
        index += 1;
    }

    final ObjectOutputStream oout = new ObjectOutputStream(output);
    oout.writeObject(new External8BitEncodingData(indices, values));
    oout.flush();
}

From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java

/**
 * Converts cart object into a String tuple.
 *
 * @param serializable cart// w w  w.j av a  2s  .c  o  m
 *
 * @return string
 *
 * @throws CartTuplizationException when cannot convert to string tuple
 */
protected String toToken(final Serializable serializable) throws CartTuplizationException {

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    synchronized (desCipher) {
        Base64OutputStream base64EncoderStream = new Base64OutputStream(byteArrayOutputStream, true,
                Integer.MAX_VALUE, null); //will be split manually
        CipherOutputStream cipherOutputStream = new CipherOutputStream(base64EncoderStream, desCipher);
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(cipherOutputStream);
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (Throwable ioe) {
            LOG.error(MessageFormat.format("Unable to serialize object {0}", serializable), ioe);
            throw new CartTuplizationException(ioe);
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                cipherOutputStream.close();
                base64EncoderStream.close();
                byteArrayOutputStream.close();
            } catch (IOException e) {
                LOG.error("Can not close stream", e);
            }
        }
    }

    return byteArrayOutputStream.toString();

}

From source file:com.mvdb.etl.dao.impl.JdbcGenericDAO.java

private boolean writeMetadata(Metadata metadata, File snapshotDirectory) {
    try {/*from w ww. ja  v  a2 s  .c o  m*/
        String structFileName = "schema-" + metadata.getTableName() + ".dat";
        snapshotDirectory.mkdirs();
        File structFile = new File(snapshotDirectory, structFileName);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(metadata);
        oos.flush();
        FileUtils.writeByteArrayToFile(structFile, baos.toByteArray());
        return true;
    } catch (Throwable t) {
        t.printStackTrace();
        return false;
    }

}

From source file:org.apache.directory.fortress.realm.J2eePolicyMgrImpl.java

/**
 * Utility to write any object into a Base64 string.  Used by this class to serialize {@link TcPrincipal} object to be returned by its toString method..
 *///from  www  .ja v a 2 s . co m
private String serialize(Object obj) throws SecurityException {
    String szRetVal = null;

    if (obj != null) {
        try {
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream so = new ObjectOutputStream(bo);
            so.writeObject(obj);
            so.flush();

            // This encoding induces a bijection between byte[] and String (unlike UTF-8)
            szRetVal = bo.toString("ISO-8859-1");
        } catch (IOException ioe) {
            String error = "serialize caught IOException: " + ioe;
            throw new SecurityException(
                    org.apache.directory.fortress.realm.GlobalIds.CONTEXT_SERIALIZATION_FAILED, error, ioe);
        }
    }

    return szRetVal;
}