Example usage for java.io ObjectInputStream ObjectInputStream

List of usage examples for java.io ObjectInputStream ObjectInputStream

Introduction

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

Prototype

public ObjectInputStream(InputStream in) throws IOException 

Source Link

Document

Creates an ObjectInputStream that reads from the specified InputStream.

Usage

From source file:majordodo.worker.TaskModeAwareExecutorFactory.java

@Override
public TaskExecutor createTaskExecutor(String taskType, Map<String, Object> parameters) {
    String mode = (String) parameters.getOrDefault("mode", Task.MODE_DEFAULT);
    if (mode.equals(Task.MODE_EXECUTE_FACTORY)) {
        return inner.createTaskExecutor(taskType, parameters);
    }/* w w  w. ja  v  a2 s.  c o  m*/
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        String parameter = (String) parameters.getOrDefault("parameter", "");
        if (parameter.startsWith("base64:")) {
            parameter = parameter.substring("base64:".length());
            byte[] serializedObjectData = Base64.getDecoder().decode(parameter);
            ByteArrayInputStream ii = new ByteArrayInputStream(serializedObjectData);
            ObjectInputStream is = new ObjectInputStream(ii) {
                @Override
                public Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
                    try {
                        return tccl.loadClass(desc.getName());
                    } catch (Exception e) {
                    }
                    return super.resolveClass(desc);
                }

            };
            TaskExecutor res = (TaskExecutor) is.readUnshared();
            return res;
        } else if (parameter.startsWith("newinstance:")) {
            parameter = parameter.substring("newinstance:".length());
            URLClassLoader cc = (URLClassLoader) tccl;
            Class clazz = Class.forName(parameter, true, tccl);
            TaskExecutor res = (TaskExecutor) clazz.newInstance();
            return res;
        } else {
            throw new RuntimeException("bad parameter: " + parameter);
        }
    } catch (Exception err) {
        return new TaskExecutor() {
            @Override
            public String executeTask(Map<String, Object> parameters) throws Exception {
                throw err;
            }

        };
    }

}

From source file:com.sec.ose.osi.sdk.protexsdk.component.ComponentAPIWrapper.java

public static void init() {
    ObjectInputStream ois;/*  ww w.ja v a  2s. com*/
    try {
        ois = new ObjectInputStream(new FileInputStream(new File(COMPONENT_FILE_PATH)));
        ComponentInfo componentInfoTmp = null;
        while ((componentInfoTmp = (ComponentInfo) ois.readObject()) != null) {
            globalComponentManager.addComponent(componentInfoTmp);
        }
        ois.close();
    } catch (FileNotFoundException e) {
        return;
    } catch (IOException e) {
        return;
    } catch (ClassNotFoundException e) {
        return;
    }
}

From source file:com.kyne.webby.bukkit.RTKModuleSocket.java

@Override
public void run() {
    LogHelper.info("Webby Socket (BukkitPlugin) is listening on port : " + this.serverSocket.getLocalPort());
    while (!this.serverSocket.isClosed()) {
        //         this.requestCount++;
        Socket clientSocket = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;
        try {//from w ww. j  a  v a  2 s  .  c om
            clientSocket = this.serverSocket.accept();
            ois = new ObjectInputStream(clientSocket.getInputStream());
            oos = new ObjectOutputStream(clientSocket.getOutputStream());

            final WebbyLocalData request = (WebbyLocalData) ois.readObject();
            final WebbyLocalData response = this.handleRequest(request);
            oos.writeObject(response);
        } catch (final SocketException e) {
            LogHelper.warn("Socket has been closed. If bukkit is stopping or restarting, this is normal");
        } catch (final IOException e) {
            LogHelper.error("An error occured while waiting for connections", e);
        } catch (final ClassNotFoundException e) {
            LogHelper.error("Unsupported object was sent to Webby ", e);
        } finally {
            IOUtils.closeQuietly(ois);
            IOUtils.closeQuietly(oos);
            IOUtils.closeQuietly(clientSocket);
        }
    }
}

From source file:de.alpharogroup.io.SerializedObjectExtensions.java

/**
 * Copys the given Object and returns the copy from the object or null if the object can't be
 * serialized./*from  ww  w  .  jav  a 2  s  . c om*/
 *
 * @param <T>
 *            the generic type of the given object
 * @param orig
 *            The object to copy.
 * @return Returns a copy from the original object.
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws ClassNotFoundException
 *             is thrown when a class is not found in the classloader or no definition for the
 *             class with the specified name could be found.
 */
@SuppressWarnings("unchecked")
public static <T extends Serializable> T copySerializedObject(final T orig)
        throws IOException, ClassNotFoundException {
    T object = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    ObjectOutputStream objectOutputStream = null;
    try {
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(orig);
        objectOutputStream.flush();
        objectOutputStream.close();
        final ByteArrayInputStream bis = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        final ObjectInputStream ois = new ObjectInputStream(bis);
        object = (T) ois.readObject();
    } finally {
        StreamExtensions.closeOutputStream(byteArrayOutputStream);
        StreamExtensions.closeOutputStream(objectOutputStream);
    }
    return object;
}

From source file:com.joliciel.talismane.machineLearning.ExternalResourceFinderImpl.java

@Override
public void addExternalResources(File externalResourceFile) {
    try {/*from w  ww . j  a  v  a2  s. c om*/
        if (externalResourceFile.isDirectory()) {
            File[] files = externalResourceFile.listFiles();
            for (File resourceFile : files) {
                LOG.debug("Reading " + resourceFile.getName());
                if (resourceFile.getName().endsWith(".zip")) {
                    ZipInputStream zis = new ZipInputStream(new FileInputStream(resourceFile));
                    zis.getNextEntry();
                    ObjectInputStream ois = new ObjectInputStream(zis);
                    ExternalResource<?> externalResource = (ExternalResource<?>) ois.readObject();
                    this.addExternalResource(externalResource);
                } else {
                    TextFileResource textFileResource = new TextFileResource(resourceFile);
                    this.addExternalResource(textFileResource);
                }
            }
        } else {
            LOG.debug("Reading " + externalResourceFile.getName());
            if (externalResourceFile.getName().endsWith(".zip")) {
                ZipInputStream zis = new ZipInputStream(new FileInputStream(externalResourceFile));
                zis.getNextEntry();
                ObjectInputStream ois = new ObjectInputStream(zis);
                ExternalResource<?> externalResource = (ExternalResource<?>) ois.readObject();
                this.addExternalResource(externalResource);
            } else {
                TextFileResource textFileResource = new TextFileResource(externalResourceFile);
                this.addExternalResource(textFileResource);
            }
        }
    } catch (IOException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        LogUtils.logError(LOG, e);
        throw new RuntimeException(e);
    }
}

From source file:com.gdc.nms.web.mibquery.wizard.ciscavate.cjwizard.FlatWizardSettings.java

/**
 * Deserialize a {@link FlatWizardSettings} object from the specified file.
 * //from   w  ww .ja  va2  s.c  o m
 * @param filename
 *           The filename.
 * @return The deserialized {@link FlatWizardSettings}.
 */
static public FlatWizardSettings deserialize(String filename) {
    ObjectInputStream in = null;
    FileInputStream fin = null;
    try {
        fin = new FileInputStream(filename);
        in = new ObjectInputStream(fin);
        return (FlatWizardSettings) in.readObject();
    } catch (IOException ioe) {
        log.error("Error reading settings", ioe);
    } catch (ClassNotFoundException cnfe) {
        log.error("Couldn't instantiate seralized class", cnfe);
    } finally {
        if (null != in) {
            try {
                in.close();
            } catch (IOException ioe) {
                log.error("Error closing inputstream", ioe);
            }
        }
        if (null != fin) {
            try {
                fin.close();
            } catch (IOException ioe) {
                log.error("Error closing file", ioe);
            }
        }
    }
    return null;
}

From source file:MLModelUsageSample.java

/**
 * Deserialize to MLModel object//from   w w  w. j  av a  2  s .  c  o  m
 * @return A {@link org.wso2.carbon.ml.commons.domain.MLModel} object
 * @throws IOException
 * @throws ClassNotFoundException
 * @throws URISyntaxException
 */
private MLModel deserializeMLModel(String pathToDownloadedModel)
        throws IOException, ClassNotFoundException, URISyntaxException {

    FileInputStream fileInputStream = new FileInputStream(pathToDownloadedModel);
    ObjectInputStream in = new ObjectInputStream(fileInputStream);
    MLModel mlModel = (MLModel) in.readObject();

    logger.info("Algorithm Type : " + mlModel.getAlgorithmClass());
    logger.info("Algorithm Name : " + mlModel.getAlgorithmName());
    logger.info("Response Variable : " + mlModel.getResponseVariable());
    logger.info("Features : " + mlModel.getFeatures());
    return mlModel;
}

From source file:de.tudarmstadt.ukp.dkpro.core.io.bincas.BinaryCasReader.java

@Override
public void getNext(CAS aCAS) throws IOException, CollectionException {
    Resource res = nextFile();//w  w  w . j  a  v  a 2s .  co m
    InputStream is = null;
    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        BufferedInputStream bis = new BufferedInputStream(is);

        TypeSystemImpl ts = null;

        // Check if this is original UIMA CAS format or DKPro Core format
        bis.mark(10);
        DataInputStream dis = new DataInputStream(bis);
        byte[] dkproHeader = new byte[] { 'D', 'K', 'P', 'r', 'o', '1' };
        byte[] header = new byte[dkproHeader.length];
        dis.read(header);

        // If it is DKPro Core format, read the type system
        if (Arrays.equals(header, dkproHeader)) {
            ObjectInputStream ois = new ObjectInputStream(bis);
            CASMgrSerializer casMgrSerializer = (CASMgrSerializer) ois.readObject();
            ts = casMgrSerializer.getTypeSystem();
            ts.commit();
        } else {
            bis.reset();
        }

        if (ts == null) {
            // Check if this is a UIMA binary CAS stream
            byte[] uimaHeader = new byte[] { 'U', 'I', 'M', 'A' };

            byte[] header4 = new byte[uimaHeader.length];
            System.arraycopy(header, 0, header4, 0, header4.length);

            if (header4[0] != 'U') {
                ArrayUtils.reverse(header4);
            }

            // If it is not a UIMA binary CAS stream, assume it is output from
            // SerializedCasWriter
            if (!Arrays.equals(header4, uimaHeader)) {
                ObjectInputStream ois = new ObjectInputStream(bis);
                CASCompleteSerializer serializer = (CASCompleteSerializer) ois.readObject();
                deserializeCASComplete(serializer, (CASImpl) aCAS);
            } else {
                // Since there was no type system, it must be type 0 or 4
                deserializeCAS(aCAS, bis);
            }
        } else {
            // Only format 6 can have type system information
            deserializeCAS(aCAS, bis, ts, null);
        }
    } catch (ResourceInitializationException e) {
        throw new IOException(e);
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    } finally {
        closeQuietly(is);
    }
}

From source file:com.collabnet.ccf.pi.qc.QCReaderOutputVerificator.java

@SuppressWarnings("unchecked")
public Object[] processXMLDocuments(Object data, String fileName) {

    int runStatus = 1;
    List<String> failure = new ArrayList<String>();
    List<String> success = new ArrayList<String>();

    String passStatus = "Run Passed";
    success.add(passStatus);// ww w  .  j av a2 s  . c  o m
    String failStatus = "Run Failed";
    failure.add(failStatus);

    List<Document> incomingDocumentList = (List<Document>) data;

    try {
        FileInputStream in = new FileInputStream(fileName);
        ObjectInputStream s = new ObjectInputStream(in);

        PrintWriter out1 = new PrintWriter(new FileWriter("inDoc.xml"));
        PrintWriter out2 = new PrintWriter(new FileWriter("retDoc.xml"));

        List<List<Document>> retObj = (List<List<Document>>) s.readObject();
        List<Document> retrievedDocumentList = (List<Document>) retObj.get(0);
        if (incomingDocumentList.equals((List<Document>) retrievedDocumentList))
            return success.toArray();

        int retrievedSize = retrievedDocumentList.size();
        int incomingSize = incomingDocumentList.size();

        if (retrievedSize != incomingSize)
            return failure.toArray();

        for (int cnt = 0; cnt < retrievedSize; cnt++) {
            Document inDoc = incomingDocumentList.get(cnt);
            Document retDoc = retrievedDocumentList.get(cnt);

            String inRecord = inDoc.asXML();
            String retRecord = retDoc.asXML();
            //inDoc.
            if (inRecord.equals(retRecord))
                runStatus = 1;
            else
                runStatus = 0;

            out1.write(inDoc.asXML());
            out2.write(retDoc.asXML());
        }
    } catch (IOException e) {
        System.out.println("File handling exception" + e);
    } catch (ClassNotFoundException e) {
        System.out.println("Class not found exception" + e);
    }

    if (runStatus == 0)
        return failure.toArray();
    return success.toArray();
}

From source file:com.github.stephanarts.cas.ticket.registry.provider.UpdateMethod.java

/**
 * Execute the JSONRPCFunction./*from  w  ww  .jav  a  2  s . c o m*/
 *
 * @param params    JSONRPC Method Parameters.
 *
 * @return          JSONRPC result object
 *
 * @throws JSONRPCException implementors can throw JSONRPCExceptions containing the error.
 */
public JSONObject execute(final JSONObject params) throws JSONRPCException {
    JSONObject result = new JSONObject();

    Ticket ticket;

    String ticketId = null;
    String serializedTicket = null;

    logger.debug("Update Ticket {}", ticketId);

    if (params.length() != 2) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }
    if (!(params.has("ticket-id") && params.has("ticket"))) {
        throw new JSONRPCException(-32602, "Invalid Params");
    }

    try {
        ticketId = params.getString("ticket-id");
        serializedTicket = params.getString("ticket");

        ByteArrayInputStream bi = new ByteArrayInputStream(
                DatatypeConverter.parseBase64Binary(serializedTicket));
        ObjectInputStream si = new ObjectInputStream(bi);

        ticket = (Ticket) si.readObject();

        if (ticket.isExpired()) {
            logger.info("Ticket Expired {}", ticketId);
        }

        if (!this.map.containsKey(ticket.hashCode())) {
            logger.warn("Missing Key {}", ticketId);
        }

        this.map.put(ticketId.hashCode(), ticket);
    } catch (final Exception e) {
        throw new JSONRPCException(-32501, "Could not decode Ticket");
    }

    logger.debug("Ticket-ID '{}'", ticketId);

    return result;
}