Example usage for org.apache.commons.lang SerializationUtils deserialize

List of usage examples for org.apache.commons.lang SerializationUtils deserialize

Introduction

In this page you can find the example usage for org.apache.commons.lang SerializationUtils deserialize.

Prototype

public static Object deserialize(byte[] objectData) 

Source Link

Document

Deserializes a single Object from an array of bytes.

Usage

From source file:com.janrain.backplane2.server.dao.redis.RedisBackplaneMessageDAO.java

@Override
public BackplaneMessage get(String id) throws BackplaneServerException {
    byte[] messageBytes = Redis.getInstance().get(getKey(id));
    if (messageBytes != null) {
        return (BackplaneMessage) SerializationUtils.deserialize(messageBytes);
    }/*from   ww  w.ja  v  a  2  s.  c o m*/
    return null;
}

From source file:mazewar.Mazewar.java

/**
 * Listen on socket for more packets from server
 *///from   w w  w.ja v  a2  s .c o  m
@Override
public void run() {
    System.out.println("Listening for packets");
    try {
        while (true) {
            MazePacket packetFromServer = (MazePacket) SerializationUtils.deserialize(subscriber.recv(0));

            /* Received Packet
            System.out.println("Receive action = " + packetFromServer.action
            + ", seq = " + packetFromServer.sequenceNumber); */

            /* Post any other event to Event Bus */
            packetQueue.put(packetFromServer);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:io.pravega.segmentstore.server.host.ZKSegmentContainerMonitorTest.java

@SuppressWarnings("unchecked")
private HashMap<Host, Set<Integer>> deserialize(CuratorFramework zkClient, String path) throws Exception {
    return (HashMap<Host, Set<Integer>>) SerializationUtils.deserialize(zkClient.getData().forPath(path));
}

From source file:edu.illinois.cs.cogcomp.annotation.BasicAnnotatorService.java

@Override
public boolean addView(TextAnnotation ta, String viewName) throws AnnotatorException {
    if (throwExceptionIfNotCached && !annotationCache.isKeyInCache(getCacheKey(ta, viewName)))
        throw new AnnotatorException(
                "No cache entry for TextAnnotation, and throwExceptionIfNotCached is 'true'. " + " Text is: '"
                        + ta.getText());

    long startTime = System.currentTimeMillis();
    logger.debug("starting addView(" + viewName + ")...");

    boolean isUpdateNeeded = true;

    if (!forceUpdate) {
        if (ta.hasView(viewName))
            isUpdateNeeded = false;/*  w w  w.j a  v  a2 s  . co m*/
        else if (!disableCache) {
            String key = getCacheKey(ta, viewName);
            if (annotationCache.isKeyInCache(key)) {
                Element taElem = annotationCache.get(key);
                View view = (View) SerializationUtils.deserialize((byte[]) taElem.getObjectValue());
                ta.addView(viewName, view);
                long endTime = System.currentTimeMillis();
                logger.debug(PrintUtils.printTimeTakenMs("Finished addView(" + viewName + ") with cache hit.",
                        startTime, endTime));
                isUpdateNeeded = false;
            }
        }
    }

    if (isUpdateNeeded) {
        /**
         * at this point, we have to run the annotator b.c. view is not in cache, or cache is
         * disabled, or client forces update
         */
        addViewAndCache(ta, viewName);

        long endTime = System.currentTimeMillis();

        logger.debug(PrintUtils.printTimeTakenMs("Finished addView(" + viewName + ") with cache miss.",
                startTime, endTime));
    }
    return isUpdateNeeded;
}

From source file:com.splicemachine.db.iapi.types.UserType.java

/**
 *
 * Read from a Project Tungsten Format.  Reads the object as a byte[]
 *
 * @see UnsafeRow#getBinary(int)/*from www .j a  v a  2 s .co m*/
 *
 * @param unsafeRow
 * @param ordinal
 * @throws StandardException
  */
@Override
public void read(UnsafeRow unsafeRow, int ordinal) throws StandardException {
    if (unsafeRow.isNullAt(ordinal))
        setToNull();
    else {
        isNull = false;
        value = SerializationUtils.deserialize(unsafeRow.getBinary(ordinal));
    }
}

From source file:io.pravega.controller.store.stream.ZKStream.java

@Override
public CompletableFuture<StreamConfiguration> getConfigurationData() {
    return cache.getCachedData(configurationPath)
            .thenApply(x -> (StreamConfiguration) SerializationUtils.deserialize(x.getData()));
}

From source file:ch.zhaw.ficore.p2abc.services.user.UserServiceGUI.java

@GET()
@Path("/requestResource/")
public Response requestResource() {
    log.entry();/*from w w  w  .j ava 2  s .  c  om*/

    try {
        Html html = UserGUI.getHtmlPramble("Request resource [1]", request);
        Div mainDiv = new Div().setCSSClass("mainDiv");
        html.appendChild(UserGUI.getBody(mainDiv));

        mainDiv.appendChild(new H2().appendChild(new Text("Request resource")));

        mainDiv.appendChild(new P().setCSSClass("info")
                .appendChild(new Text("Please enter the information required for the resource. "
                        + "If the the Verifier field is blank please add an alias for an URL first via the Profile page.")));

        Form f = new Form("./requestResource2").setMethod("post");
        Table tbl = new Table();
        Tr tr = null;

        Select s = new Select().setName("vu");

        List<String> keys = urlStorage.keysAsStrings();
        List<byte[]> values = urlStorage.values();
        List<String> urls = new ArrayList<String>();

        for (byte[] b : values) {
            urls.add((String) SerializationUtils.deserialize(b));
        }

        for (int i = 0; i < keys.size(); i++) {
            Option o = new Option().appendChild(new Text(keys.get(i))).setValue(urls.get(i));
            s.appendChild(o);
        }

        tr = new Tr().appendChild(new Td().appendChild(new Label().appendChild(new Text("Verifier:"))))
                .appendChild(new Td().appendChild(s));
        tbl.appendChild(tr);
        tr = new Tr().appendChild(new Td().appendChild(new Label().appendChild(new Text("Resource:"))))
                .appendChild(new Td().appendChild(new Input().setType("text").setName("r")));
        tbl.appendChild(tr);
        f.appendChild(tbl);
        f.appendChild(new Input().setType("submit").setValue("Request"));
        mainDiv.appendChild(f);
        return log.exit(Response.ok(html.write()).build());
    } catch (Exception e) {
        log.catching(e);
        return log.exit(Response.status(Response.Status.BAD_REQUEST)
                .entity(UserGUI.errorPage(ExceptionDumper.dumpExceptionStr(e, log), request).write()).build());
    }
}

From source file:ch.zhaw.ficore.p2abc.services.user.UserService.java

/**
 * @fiware-rest-path /getSettings///  w  ww  . j  av a  2 s.  com
 * @fiware-rest-method GET
 * @fiware-rest-description Returns the settings of the service as obtained
 *                          from an issuance service. Settings includes
 *                          issuer parameters, credential specifications and
 *                          the system parameters. This method may thus be
 *                          used to retrieve all credential specifications
 *                          stored at the user service and their
 *                          corresponding issuer parameters. The return type
 *                          of this method is <tt>Settings</tt>. The user
 *                          service is capable of downloading settings from
 *                          an issuer (or from anything that provides
 *                          settings). To download settings use
 *                          <tt>/loadSetting?url=...</tt> (
 *                          {@link #loadSettings(String)}).
 * @fiware-rest-response 200 OK
 * @fiware-rest-response 500 ERROR
 * @fiware-rest-return-type Settings
 * 
 * @return Response
 */
@GET()
@Path("/getSettings/")
public Response getSettings() { /* [FLOW TEST] */
    log.entry();

    try {
        this.initializeHelper();

        UserHelper instance = UserHelper.getInstance();

        Settings settings = new Settings();

        List<IssuerParameters> issuerParams = new ArrayList<IssuerParameters>();

        for (URI uri : instance.keyStorage.listUris()) {
            Object obj = SerializationUtils.deserialize(instance.keyStorage.getValue(uri));
            if (obj instanceof IssuerParameters) {
                IssuerParameters ip = (IssuerParameters) obj;

                SystemParameters serializeSp = (ip.getSystemParameters());

                ip.setSystemParameters(serializeSp);

                issuerParams.add(ip);
            }
        }

        List<CredentialSpecification> credSpecs = new ArrayList<CredentialSpecification>();

        for (URI uri : instance.keyStorage.listUris()) {
            Object obj = SerializationUtils.deserialize(instance.keyStorage.getValue(uri));
            if (obj instanceof CredentialSpecification) {
                credSpecs.add((CredentialSpecification) obj);
            }
        }

        settings.credentialSpecifications = credSpecs;
        settings.issuerParametersList = issuerParams;
        try {
            settings.systemParameters = /* SystemParametersUtil.serialize */(instance.keyManager
                    .getSystemParameters());
        } catch (Exception e) {
            log.catching(e);
        }

        return log.exit(Response.ok(settings, MediaType.APPLICATION_XML).build());
    } catch (Exception e) {
        log.catching(e);
        return log.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                .entity(ExceptionDumper.dumpExceptionStr(e, log))).build();
    }
}

From source file:info.raack.appliancelabeler.data.JDBCDatabase.java

@Override
public Map<String, OAuthConsumerToken> getOAuthTokensForUserId(String userId) {

    Map<String, OAuthConsumerToken> tokens = new HashMap<String, OAuthConsumerToken>();

    try {// w  w  w. ja v a  2s.  c o  m
        Blob blob = jdbcTemplate.queryForObject(getAccessTokensForUser, new Object[] { userId }, Blob.class);

        try {
            Object tokenObject = SerializationUtils.deserialize(blob.getBinaryStream());
            tokens = (Map<String, OAuthConsumerToken>) tokenObject;
        } catch (Exception e) {
            throw new RuntimeException("Could not deserialize tokens for user id " + userId, e);
        }
    } catch (EmptyResultDataAccessException e) {
        logger.debug("No oauth tokens for " + userId);
    }

    return tokens;
}

From source file:com.ephesoft.dcma.batch.service.ImportBatchServiceImpl.java

/**
 * Method to import the batch class as specified with the options XML.
 * //from  ww  w.  j  a  va 2  s . c o  m
 * @param optionXML {@link ImportBatchClassOptions}
 * @param isDeployed boolean
 * @param isFromWebService boolean
 * @param userRolesToAssign {@link Set<{@link String}>}
 * @return {@link Map<{@link Boolean}, {@link String}>}
 */
@Override
public Map<Boolean, String> importBatchClass(ImportBatchClassOptions optionXML, boolean isDeployed,
        boolean isFromWebService, Set<String> userRolesToAssign) {
    Map<Boolean, String> resultsMap = new HashMap<Boolean, String>();
    String tempOutputUnZipDir = optionXML.getZipFilePath();
    File originalFolder = new File(tempOutputUnZipDir);
    String serializableFilePath = FileUtils.getFileNameOfTypeFromFolder(tempOutputUnZipDir,
            FileType.SER.getExtensionWithDot());

    InputStream serializableFileStream = null;
    try {
        serializableFileStream = new FileInputStream(serializableFilePath);
        // Import Into Database from the serialized file
        BatchClass importBatchClass = (BatchClass) SerializationUtils.deserialize(serializableFileStream);

        // delete serialization file from folder and create test-extraction folder
        new File(serializableFilePath).delete();
        new File(tempOutputUnZipDir + File.separator + batchSchemaService.getTestKVExtractionFolderName())
                .mkdir();
        new File(tempOutputUnZipDir + File.separator + batchSchemaService.getTestTableFolderName()).mkdir();

        // if from web service, implement workflow content equality check
        if (isFromWebService) {
            boolean isNameExistInDatabase = (batchClassService
                    .getBatchClassByNameIncludingDeleted(optionXML.getName()) != null ? true : false);
            if (!optionXML.isUseExisting() && isNameExistInDatabase) {
                String errorMessg = "Incorrect user input. Please specify another name for workflow while importing a new batch class. Returning from import.";
                resultsMap.put(false, errorMessg);
                LOGGER.error(errorMessg);
                return resultsMap;
            }

            boolean isEqual = isImportWorkflowEqualDeployedWorkflow(importBatchClass, optionXML.getName());
            if (isNameExistInDatabase && !isEqual) {
                String errorMessg = "Incorrect user input. Workflow name specified exists with different configuration. Returning from import.";
                resultsMap.put(false, errorMessg);
                LOGGER.error(errorMessg);
                return resultsMap;
            }

            // verify the contents are equal to the deployed work flow
            if (!optionXML.isImportIfConflict() && !isNameExistInDatabase && isDeployed) {
                String errorMessg = "Zip contains a workflow name that is already deployed but no batch class exists corresponding to this workflow name. It may be possible that the zip contains different configuration. Please specify another name for workflow.";
                resultsMap.put(false, errorMessg);
                LOGGER.error(errorMessg);
                return resultsMap;
            }
        }

        if (optionXML.getName() == null || optionXML.getName().isEmpty()) {
            optionXML.setName(importBatchClass.getName());
        }

        if (optionXML.isUseExisting()) {
            overrideExistingBatchClass(resultsMap, optionXML, tempOutputUnZipDir, originalFolder,
                    importBatchClass, userRolesToAssign);
        } else {
            importNewBatchClass(resultsMap, optionXML, tempOutputUnZipDir, originalFolder,
                    serializableFileStream, importBatchClass, userRolesToAssign);
        }
    } catch (Exception e) {
        String errorMessg = "Error while importing." + e.getMessage();
        resultsMap.put(false, errorMessg);
        LOGGER.error(errorMessg, e);
    }
    return resultsMap;
}