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.impetus.ankush.common.domain.NodeMonitoring.java

/**
 * Method to sset graph view data./* www.j a v a2 s .  co  m*/
 * 
 * @return
 */
@Transient
public HashMap getGraphViewData() {
    // if graphViewData is not null.
    if (this.graphView != null) {
        try {
            return (HashMap) SerializationUtils.deserialize(this.getGraphView());
        } catch (Exception e) {
            return new HashMap();
        }
    }
    return new HashMap();
}

From source file:co.cask.cdap.internal.app.runtime.schedule.store.DatasetBasedTimeScheduleStore.java

private void readSchedulesFromPersistentStore() throws Exception {

    final List<JobDetail> jobs = Lists.newArrayList();
    final List<OperableTrigger> triggers = Lists.newArrayList();

    factory.createExecutor(ImmutableList.of((TransactionAware) table))
            .execute(new TransactionExecutor.Subroutine() {
                @Override//  ww  w . j a  va 2  s  .co  m
                public void apply() throws Exception {
                    Row result = table.get(JOB_KEY);
                    if (!result.isEmpty()) {
                        for (byte[] bytes : result.getColumns().values()) {
                            JobDetail jobDetail = (JobDetail) SerializationUtils.deserialize(bytes);
                            LOG.debug("Schedule: Job with key {} found", jobDetail.getKey());
                            jobs.add(jobDetail);
                        }
                    } else {
                        LOG.debug("Schedule: No Jobs found in Job store");
                    }

                    result = table.get(TRIGGER_KEY);
                    if (!result.isEmpty()) {
                        for (byte[] bytes : result.getColumns().values()) {
                            TriggerStatus trigger = (TriggerStatus) SerializationUtils.deserialize(bytes);
                            if (trigger.state.equals(Trigger.TriggerState.NORMAL)) {
                                triggers.add(trigger.trigger);
                                LOG.debug("Schedule: trigger with key {} added", trigger.trigger.getKey());
                            } else {
                                LOG.debug("Schedule: trigger with key {} and state {} skipped",
                                        trigger.trigger.getKey(), trigger.state.toString());
                            }
                        }
                    } else {
                        LOG.debug("Schedule: No triggers found in job store");
                    }
                }
            });

    for (JobDetail job : jobs) {
        super.storeJob(job, true);
    }

    for (OperableTrigger trigger : triggers) {
        super.storeTrigger(trigger, true);
    }
}

From source file:co.cask.cdap.internal.app.runtime.schedule.DataSetBasedScheduleStore.java

private void readSchedulesFromPersistentStore() throws Exception {

    final List<JobDetail> jobs = Lists.newArrayList();
    final List<OperableTrigger> triggers = Lists.newArrayList();

    factory.createExecutor(ImmutableList.of((TransactionAware) table))
            .execute(new TransactionExecutor.Subroutine() {
                @Override/*from   w  w  w .  ja v  a  2s .  c o m*/
                public void apply() throws Exception {
                    Map<byte[], byte[]> result = table.get(JOB_KEY);
                    if (!result.isEmpty()) {
                        for (byte[] bytes : result.values()) {
                            JobDetail jobDetail = (JobDetail) SerializationUtils.deserialize(bytes);
                            LOG.debug("Schedule: Job with key {} found", jobDetail.getKey());
                            jobs.add(jobDetail);
                        }
                    } else {
                        LOG.debug("Schedule: No Jobs found in Job store");
                    }

                    result = table.get(TRIGGER_KEY);
                    if (!result.isEmpty()) {
                        for (byte[] bytes : result.values()) {
                            TriggerStatus trigger = (TriggerStatus) SerializationUtils.deserialize(bytes);
                            if (trigger.state.equals(Trigger.TriggerState.NORMAL)) {
                                triggers.add(trigger.trigger);
                                LOG.debug("Schedule: trigger with key {} added", trigger.trigger.getKey());
                            } else {
                                LOG.debug("Schedule: trigger with key {} and state {} skipped",
                                        trigger.trigger.getKey(), trigger.state.toString());
                            }
                        }
                    } else {
                        LOG.debug("Schedule: No triggers found in job store");
                    }
                }
            });

    for (JobDetail job : jobs) {
        super.storeJob(job, true);
    }

    for (OperableTrigger trigger : triggers) {
        super.storeTrigger(trigger, true);
    }
}

From source file:com.janrain.backplane.server.redisdao.RedisBackplaneMessageDAO.java

@Override
public List<BackplaneMessage> getMessagesByBus(String bus, String since, String sticky)
        throws SimpleDBException, BackplaneServerException {

    Jedis jedis = null;//from w  ww  . j a  v  a 2s.c  o  m

    try {

        jedis = Redis.getInstance().getReadJedis();

        double sinceInMs = 0;
        if (StringUtils.isNotBlank(since)) {
            sinceInMs = BackplaneMessage.getDateFromId(since).getTime();
        }

        // every message has a unique timestamp - which serves as a key for indexing
        Set<byte[]> messageIdBytes = Redis.getInstance().zrangebyscore(RedisBackplaneMessageDAO.getBusKey(bus),
                sinceInMs, Double.POSITIVE_INFINITY);

        List<BackplaneMessage> messages = new ArrayList<BackplaneMessage>();

        Pipeline pipeline = jedis.pipelined();
        List<Response<byte[]>> responses = new ArrayList<Response<byte[]>>();

        if (messageIdBytes != null) {
            for (byte[] b : messageIdBytes) {
                responses.add(pipeline.get(getKey(new String(b))));
            }
            pipeline.sync();
            for (Response<byte[]> response : responses) {
                byte[] bytes = response.get();
                if (bytes != null) {
                    BackplaneMessage backplaneMessage = (BackplaneMessage) SerializationUtils
                            .deserialize(bytes);
                    messages.add(backplaneMessage);
                }
            }
        }

        filterAndSort(messages, since, sticky);
        return messages;

    } finally {
        Redis.getInstance().releaseToPool(jedis);
    }

}

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

public List<BackplaneMessage> getMessagesByBus(String bus, String since, String sticky)
        throws SimpleDBException, BackplaneServerException {

    Jedis jedis = null;//from ww  w  .  j a va 2 s. c  o  m

    try {

        jedis = Redis.getInstance().getReadJedis();

        double sinceInMs = 0;
        if (StringUtils.isNotBlank(since)) {
            sinceInMs = BackplaneMessage.getDateFromId(since).getTime();
        }

        // every message has a unique timestamp - which serves as a key for indexing
        Set<byte[]> messageIdBytes = Redis.getInstance().zrangebyscore(RedisBackplaneMessageDAO.getBusKey(bus),
                sinceInMs, Double.POSITIVE_INFINITY);

        List<BackplaneMessage> messages = new ArrayList<BackplaneMessage>();

        Pipeline pipeline = jedis.pipelined();
        List<Response<byte[]>> responses = new ArrayList<Response<byte[]>>();

        if (messageIdBytes != null) {
            for (byte[] b : messageIdBytes) {
                responses.add(pipeline.get(getKey(new String(b))));
            }
            pipeline.sync();
            for (Response<byte[]> response : responses) {
                byte[] bytes = response.get();
                if (bytes != null) {
                    BackplaneMessage backplaneMessage = (BackplaneMessage) SerializationUtils
                            .deserialize(bytes);
                    messages.add(backplaneMessage);
                }
            }
        }

        filterAndSort(messages, since, sticky);
        return messages;

    } finally {
        Redis.getInstance().releaseToPool(jedis);
    }

}

From source file:at.gv.egovernment.moa.id.protocols.pvp2x.SingleLogOutAction.java

@Override
public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq,
        HttpServletResponse httpResp, IAuthData authData) throws MOAIDException {

    PVPTargetConfiguration pvpReq = (PVPTargetConfiguration) req;

    if (pvpReq.getRequest() instanceof MOARequest
            && ((MOARequest) pvpReq.getRequest()).getSamlRequest() instanceof LogoutRequest) {
        Logger.debug("Process Single LogOut request");
        MOARequest samlReq = (MOARequest) pvpReq.getRequest();
        LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest();

        AuthenticationSession session = AuthenticationSessionStoreage.searchMOASessionWithNameIDandOAID(
                logOutReq.getIssuer().getValue(), logOutReq.getNameID().getValue());

        if (session == null) {
            Logger.warn("Can not find active SSO session with nameID " + logOutReq.getNameID().getValue()
                    + " and OA " + logOutReq.getIssuer().getValue());
            Logger.info("Search active SSO session with SSO session cookie");
            SSOManager ssomanager = SSOManager.getInstance();
            String ssoID = ssomanager.getSSOSessionID(httpReq);
            if (MiscUtil.isEmpty(ssoID)) {
                Logger.warn("Can not find active Session. Single LogOut not possible!");
                SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq);
                //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI);
                LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null);
                Logger.info("Sending SLO success message to requester ...");
                SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp,
                        samlReq.getRelayState());
                return null;

            } else {
                String moasession = ssomanager.getMOASession(ssoID);
                try {
                    session = AuthenticationSessionStoreage.getSession(moasession);

                } catch (MOADatabaseException e) {
                    Logger.warn("Can not find active Session. Single LogOut not possible!");
                    SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq);
                    //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI);
                    LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq,
                            null);//  w  w  w. j ava  2  s  .  com
                    Logger.info("Sending SLO success message to requester ...");
                    SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp,
                            samlReq.getRelayState());
                    return null;

                }
            }
        }

        AuthenticationManager authManager = AuthenticationManager.getInstance();
        authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq);

    } else if (pvpReq.getRequest() instanceof MOAResponse
            && ((MOAResponse) pvpReq.getRequest()).getResponse() instanceof LogoutResponse) {
        Logger.debug("Process Single LogOut response");
        LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse) pvpReq.getRequest()).getResponse();

        Transaction tx = null;

        try {
            String relayState = pvpReq.getRequest().getRelayState();
            if (MiscUtil.isEmpty(relayState)) {
                Logger.warn(
                        "SLO Response from " + logOutResp.getIssuer().getValue() + " has no SAML2 RelayState.");
                throw new SLOException("pvp2.19", null);

            }

            Session session = MOASessionDBUtils.getCurrentSession();
            boolean storageSuccess = false;
            int counter = 0;

            //TODO: add counter to prevent deadlock

            while (!storageSuccess) {
                tx = session.beginTransaction();

                List result;
                Query query = session.getNamedQuery("getAssertionWithArtifact");
                query.setParameter("artifact", relayState);
                result = query.list();
                Logger.trace("Found entries: " + result.size());

                //Assertion requires an unique artifact
                if (result.size() != 1) {
                    Logger.trace("No entries found.");
                    throw new MOADatabaseException("No sessioninformation found with this ID");
                }

                AssertionStore element = (AssertionStore) result.get(0);
                Object data = SerializationUtils.deserialize(element.getAssertion());

                if (data instanceof SLOInformationContainer) {
                    SLOInformationContainer sloContainer = (SLOInformationContainer) data;

                    //check status
                    SingleLogOutBuilder.checkStatusCode(sloContainer, logOutResp);

                    if (sloContainer.hasFrontChannelOA()) {
                        try {
                            //some response are open
                            byte[] serializedSLOContainer = SerializationUtils
                                    .serialize((Serializable) sloContainer);
                            element.setAssertion(serializedSLOContainer);
                            element.setType(sloContainer.getClass().getName());

                            session.saveOrUpdate(element);
                            tx.commit();

                            //sloContainer could be stored to database
                            storageSuccess = true;

                        } catch (HibernateException e) {
                            tx.rollback();

                            counter++;
                            Logger.debug(
                                    "SLOContainter could not stored to database. Wait some time and restart storage process ... ");
                            java.util.Random rand = new java.util.Random();

                            try {
                                Thread.sleep(rand.nextInt(20) * 10);

                            } catch (InterruptedException e1) {
                                Logger.warn("Thread could not stopped. ReStart storage process immediately",
                                        e1);
                            }
                        }

                    } else {
                        //last response received.
                        try {
                            session.delete(element);
                            tx.commit();

                        } catch (HibernateException e) {
                            tx.rollback();
                            Logger.error("SLOContainter could not deleted from database. ");

                        }

                        storageSuccess = true;
                        String redirectURL = null;
                        if (sloContainer.getSloRequest() != null) {
                            //send SLO response to SLO request issuer
                            SingleLogoutService sloService = SingleLogOutBuilder
                                    .getResponseSLODescriptor(sloContainer.getSloRequest());
                            LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService,
                                    sloContainer.getSloRequest(), sloContainer.getSloFailedOAs());
                            redirectURL = SingleLogOutBuilder.getFrontChannelSLOMessageURL(sloService, message,
                                    httpReq, httpResp,
                                    sloContainer.getSloRequest().getRequest().getRelayState());

                        } else {
                            //print SLO information directly
                            redirectURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix()
                                    + "/idpSingleLogout";

                            String artifact = Random.nextRandom();

                            String statusCode = null;
                            if (sloContainer.getSloFailedOAs() == null
                                    || sloContainer.getSloFailedOAs().size() == 0)
                                statusCode = SLOSTATUS_SUCCESS;
                            else
                                statusCode = SLOSTATUS_ERROR;

                            AssertionStorage.getInstance().put(artifact, statusCode);
                            redirectURL = addURLParameter(redirectURL, PARAM_SLOSTATUS, artifact);

                        }
                        //redirect to Redirect Servlet
                        String url = AuthConfigurationProvider.getInstance().getPublicURLPrefix()
                                + "/RedirectServlet";
                        url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL,
                                URLEncoder.encode(redirectURL, "UTF-8"));
                        url = httpResp.encodeRedirectURL(url);

                        httpResp.setContentType("text/html");
                        httpResp.setStatus(302);
                        httpResp.addHeader("Location", url);

                    }
                } else {
                    Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + relayState);
                    throw new MOADatabaseException("Sessioninformation Cast-Exception");

                }
            }

        } catch (MOADatabaseException e) {
            Logger.error("MOA AssertionDatabase ERROR", e);
            throw new SLOException("pvp2.19", null);

        } catch (UnsupportedEncodingException e) {
            Logger.error("Finale SLO redirct not possible.", e);
            throw new AuthenticationException("pvp2.13", new Object[] {});

        } finally {
            if (tx != null && !tx.wasCommitted()) {
                tx.commit();

            }
        }

    } else {
        Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse.");
        throw new MOAIDException("pvp2.13", null);

    }

    return null;
}

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

@Override
public List<BackplaneMessage> retrieveMessagesByChannel(String channel) throws BackplaneServerException {

    Jedis jedis = null;/*from   w  w w  .j  av  a 2s  .c  om*/

    try {

        jedis = Redis.getInstance().getReadJedis();

        List<BackplaneMessage> messages = new ArrayList<BackplaneMessage>();
        Set<byte[]> messageIdBytes = jedis.zrange(getChannelKey(channel), 0, -1);

        Pipeline pipeline = jedis.pipelined();
        List<Response<byte[]>> responses = new ArrayList<Response<byte[]>>();

        if (messageIdBytes != null) {
            for (byte[] b : messageIdBytes) {
                responses.add(pipeline.get(getKey(new String(b))));
            }
            pipeline.sync();
            for (Response<byte[]> response : responses) {
                if (response.get() != null) {
                    BackplaneMessage backplaneMessage = (BackplaneMessage) SerializationUtils
                            .deserialize(response.get());
                    messages.add(backplaneMessage);
                } else {
                    logger.warn("failed to retrieve a message");
                }
            }
        }

        Collections.sort(messages, new Comparator<BackplaneMessage>() {
            @Override
            public int compare(BackplaneMessage backplaneMessage, BackplaneMessage backplaneMessage1) {
                return backplaneMessage.getIdValue().compareTo(backplaneMessage1.getIdValue());
            }
        });

        return messages;

    } finally {
        Redis.getInstance().releaseToPool(jedis);
    }

}

From source file:com.impetus.ankush.common.domain.Cluster.java

@Transient
public ClusterConfig getClusterConfig() {
    if (getConfBytes() == null) {
        return null;
    }//from   w  ww.j  a va 2  s  . com
    return (ClusterConfig) SerializationUtils.deserialize(getConfBytes());
}

From source file:gov.nih.nci.firebird.test.nes.NesTestDataLoader.java

private void deserializeCacheFile() {
    FileInputStream fis = null;/*ww  w  .ja  v  a2 s  .com*/
    try {
        fis = new FileInputStream(getCacheFile());
        dataSource = (ExternalEntityTestDataSource) SerializationUtils.deserialize(fis);
    } catch (FileNotFoundException e) {
        throw new IllegalArgumentException(getCacheFile() + " not found", e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

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

private Set<Integer> getDesiredContainerList() {
    log.debug("Fetching the latest container assignment from ZooKeeper.");
    if (hostContainerMapNode.getCurrentData() != null) { //Check if path exists.
        //read data from zk.
        byte[] containerToHostMapSer = hostContainerMapNode.getCurrentData().getData();
        if (containerToHostMapSer != null) {
            @SuppressWarnings("unchecked")
            val controlMapping = (Map<Host, Set<Integer>>) SerializationUtils
                    .deserialize(containerToHostMapSer);
            return controlMapping.entrySet().stream().filter(ep -> ep.getKey().equals(this.host))
                    .map(Map.Entry::getValue).findFirst().orElse(Collections.emptySet());
        }//from  w  w  w  . ja v a  2s .  c  o  m
    }

    return null;
}