Example usage for org.apache.commons.io.input ClassLoaderObjectInputStream ClassLoaderObjectInputStream

List of usage examples for org.apache.commons.io.input ClassLoaderObjectInputStream ClassLoaderObjectInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input ClassLoaderObjectInputStream ClassLoaderObjectInputStream.

Prototype

public ClassLoaderObjectInputStream(ClassLoader classLoader, InputStream inputStream)
        throws IOException, StreamCorruptedException 

Source Link

Document

Constructs a new ClassLoaderObjectInputStream.

Usage

From source file:com.app.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;//from w w  w. j  a  v a  2  s.c  o m
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //log.info("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:org.apache.carbondata.core.metadata.blocklet.BlockletInfo.java

private DataChunk deserializeDataChunk(byte[] bytes) throws IOException {
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    ObjectInputStream inputStream = new ClassLoaderObjectInputStream(
            Thread.currentThread().getContextClassLoader(), stream);
    DataChunk dataChunk = null;//from w  w w .  java2  s  . c  om
    try {
        dataChunk = (DataChunk) inputStream.readObject();
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    }
    inputStream.close();
    return dataChunk;
}

From source file:org.apache.carbondata.core.util.ObjectSerializationUtil.java

/**
 * Converts Base64 string to object.//from   www. j  ava 2  s .com
 *
 * @param objectString serialized object in string format
 * @return Object after convert string to object
 * @throws IOException
 */
public static Object convertStringToObject(String objectString) throws IOException {
    if (objectString == null) {
        return null;
    }

    byte[] bytes = CarbonUtil.decodeStringToBytes(objectString);

    ByteArrayInputStream bais = null;
    GZIPInputStream gis = null;
    ObjectInputStream ois = null;

    try {
        bais = new ByteArrayInputStream(bytes);
        gis = new GZIPInputStream(bais);
        ois = new ClassLoaderObjectInputStream(Thread.currentThread().getContextClassLoader(), gis);
        return ois.readObject();
    } catch (ClassNotFoundException e) {
        throw new IOException("Could not read object", e);
    } finally {
        try {
            if (ois != null) {
                ois.close();
            }
            if (gis != null) {
                gis.close();
            }
            if (bais != null) {
                bais.close();
            }
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
    }
}

From source file:org.apache.pig.impl.util.ObjectSerializer.java

public static Object deserialize(String str) throws IOException {
    if (str == null || str.length() == 0)
        return null;
    ObjectInputStream objStream = null;
    try {/* w w  w.  java2s.co m*/
        ByteArrayInputStream serialObj = new ByteArrayInputStream(decodeBytes(str));
        objStream = new ClassLoaderObjectInputStream(Thread.currentThread().getContextClassLoader(),
                new InflaterInputStream(serialObj));
        return objStream.readObject();
    } catch (Exception e) {
        throw new IOException("Deserialization error: " + e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(objStream);
    }
}

From source file:org.apache.storm.utils.Utils.java

public static <T> T javaDeserialize(byte[] serialized, Class<T> clazz) {
    try {//from   w w w.j  a  va  2  s .c o m
        ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
        ObjectInputStream ois = null;
        if (null == Utils.cl) {
            ois = new ObjectInputStream(bis);
        } else {
            // Use custom class loader set in testing environment
            ois = new ClassLoaderObjectInputStream(Utils.cl, bis);
        }
        Object ret = ois.readObject();
        ois.close();
        return (T) ret;
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.streams.util.SerializationUtil.java

/**
 * deserialize byte array as Object.//from w  w w  .ja va2s  .  co m
 *
 * <p/>
 * BORROwED FROM APACHE STORM PROJECT
 *
 * @param serialized byte[]
 * @return Object
 */
public static Object deserialize(byte[] serialized) {
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(serialized);
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        ObjectInputStream ois = new ClassLoaderObjectInputStream(classLoader, bis);
        Object ret = ois.readObject();
        ois.close();
        return ret;
    } catch (IOException | ClassNotFoundException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:org.freezedry.serialization.ObjectSerializer.java

@Override
public synchronized <T> T deserialize(final InputStream input, final Class<T> clazz) {
    // read the input stream into an object. we use the the (apache commons-io) ClassLoaderObjectInputStream
    // to read the object because we need to be able to use the same class loader that loaded the class in
    // the first place (for example, the RestfulClassLoader).
    T object;//  w  w  w.  j av a2  s  . c o m
    try (final ClassLoaderObjectInputStream in = new ClassLoaderObjectInputStream(clazz.getClassLoader(),
            input)) {
        object = clazz.cast(in.readObject());
    } catch (IOException | ClassNotFoundException e) {
        final StringBuilder message = new StringBuilder();
        message.append("Unable to serialize object to output stream:").append(Constants.NEW_LINE);
        message.append("  Input Stream Type: ").append(input.getClass().getName()).append(Constants.NEW_LINE);
        message.append("  Object Type: ").append(clazz.getName()).append(Constants.NEW_LINE);
        LOGGER.error(message.toString(), e);
        throw new IllegalArgumentException(message.toString(), e);
    }
    return object;
}

From source file:org.jbpm.executor.impl.AbstractAvailableJobsExecutor.java

public void executeGivenJob(RequestInfo request) {

    try {/*from  w w  w .jav  a 2 s . c o m*/
        if (request != null) {
            boolean processReoccurring = false;
            Command cmd = null;
            CommandContext ctx = null;
            List<CommandCallback> callbacks = null;
            ClassLoader cl = getClassLoader(request.getDeploymentId());
            try {

                logger.debug("Processing Request Id: {}, status {} command {}", request.getId(),
                        request.getStatus(), request.getCommandName());

                byte[] reqData = request.getRequestData();
                if (reqData != null) {
                    ObjectInputStream in = null;
                    try {
                        in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(reqData));
                        ctx = (CommandContext) in.readObject();
                    } catch (IOException e) {
                        logger.warn("Exception while serializing context data", e);
                        return;
                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                for (Map.Entry<String, Object> entry : contextData.entrySet()) {
                    ctx.setData(entry.getKey(), entry.getValue());
                }
                // add class loader so internally classes can be created with valid (kjar) deployment
                ctx.setData("ClassLoader", cl);

                cmd = classCacheManager.findCommand(request.getCommandName(), cl);
                ExecutionResults results = cmd.execute(ctx);

                callbacks = classCacheManager.buildCommandCallback(ctx, cl);

                for (CommandCallback handler : callbacks) {

                    handler.onCommandDone(ctx, results);
                }

                if (results != null) {
                    try {
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        ObjectOutputStream out = new ObjectOutputStream(bout);
                        out.writeObject(results);
                        byte[] respData = bout.toByteArray();
                        request.setResponseData(respData);
                    } catch (IOException e) {
                        request.setResponseData(null);
                    }
                }

                request.setStatus(STATUS.DONE);

                executorStoreService.updateRequest(request);
                processReoccurring = true;

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Throwable e) {
                callbacks = classCacheManager.buildCommandCallback(ctx, cl);

                processReoccurring = handleException(request, e, ctx, callbacks);
            } finally {
                handleCompletion(processReoccurring, cmd, ctx);
            }
        }
    } catch (Exception e) {
        logger.warn("Unexpected error while processin executor's job {}", e.getMessage(), e);
    }
}

From source file:org.jbpm.executor.impl.AvailableJobsExecutor.java

@SuppressWarnings("unchecked")

public void executeJob() {
    logger.debug("Executor Thread {} Waking Up!!!", this.toString());
    try {/*  ww  w  . j  ava  2 s .com*/
        RequestInfo request = (RequestInfo) queryService.getRequestForProcessing();
        if (request != null) {
            boolean processReoccurring = false;
            Command cmd = null;
            CommandContext ctx = null;
            List<CommandCallback> callbacks = null;
            ClassLoader cl = getClassLoader(request.getDeploymentId());
            try {

                logger.debug("Processing Request Id: {}, status {} command {}", request.getId(),
                        request.getStatus(), request.getCommandName());

                byte[] reqData = request.getRequestData();
                if (reqData != null) {
                    ObjectInputStream in = null;
                    try {
                        in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(reqData));
                        ctx = (CommandContext) in.readObject();
                    } catch (IOException e) {
                        logger.warn("Exception while serializing context data", e);
                        return;
                    } finally {
                        if (in != null) {
                            in.close();
                        }
                    }
                }
                for (Map.Entry<String, Object> entry : contextData.entrySet()) {
                    ctx.setData(entry.getKey(), entry.getValue());
                }
                // add class loader so internally classes can be created with valid (kjar) deployment
                ctx.setData("ClassLoader", cl);

                cmd = classCacheManager.findCommand(request.getCommandName(), cl);
                ExecutionResults results = cmd.execute(ctx);

                callbacks = classCacheManager.buildCommandCallback(ctx, cl);

                for (CommandCallback handler : callbacks) {

                    handler.onCommandDone(ctx, results);
                }

                if (results != null) {
                    try {
                        ByteArrayOutputStream bout = new ByteArrayOutputStream();
                        ObjectOutputStream out = new ObjectOutputStream(bout);
                        out.writeObject(results);
                        byte[] respData = bout.toByteArray();
                        request.setResponseData(respData);
                    } catch (IOException e) {
                        request.setResponseData(null);
                    }
                }

                request.setStatus(STATUS.DONE);

                executorStoreService.updateRequest(request);
                processReoccurring = true;

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Throwable e) {
                callbacks = classCacheManager.buildCommandCallback(ctx, cl);
                logger.warn("Error during command {} execution {}", request.getCommandName(), e.getMessage());

                ErrorInfo errorInfo = new ErrorInfo(e.getMessage(),
                        ExceptionUtils.getFullStackTrace(e.fillInStackTrace()));
                errorInfo.setRequestInfo(request);

                ((List<ErrorInfo>) request.getErrorInfo()).add(errorInfo);
                logger.debug("Error Number: {}", request.getErrorInfo().size());
                if (request.getRetries() > 0) {
                    request.setStatus(STATUS.RETRYING);
                    request.setRetries(request.getRetries() - 1);
                    request.setExecutions(request.getExecutions() + 1);
                    logger.debug("Retrying ({}) still available!", request.getRetries());

                    executorStoreService.updateRequest(request);
                } else {
                    logger.debug("Error no retries left!");
                    request.setStatus(STATUS.ERROR);
                    request.setExecutions(request.getExecutions() + 1);

                    executorStoreService.updateRequest(request);

                    if (callbacks != null) {
                        for (CommandCallback handler : callbacks) {
                            handler.onCommandError(ctx, e);
                        }
                    }
                    processReoccurring = true;
                }

            } finally {
                if (processReoccurring && cmd != null && cmd instanceof Reoccurring) {
                    Date current = new Date();
                    Date nextScheduleTime = ((Reoccurring) cmd).getScheduleTime();

                    if (nextScheduleTime != null && nextScheduleTime.after(current)) {
                        String businessKey = (String) ctx.getData("businessKey");
                        RequestInfo requestInfo = new RequestInfo();
                        requestInfo.setCommandName(cmd.getClass().getName());
                        requestInfo.setKey(businessKey);
                        requestInfo.setStatus(STATUS.QUEUED);
                        requestInfo.setTime(nextScheduleTime);
                        requestInfo.setMessage("Rescheduled reoccurring job");
                        requestInfo.setDeploymentId((String) ctx.getData("deploymentId"));
                        requestInfo.setOwner((String) ctx.getData("owner"));
                        if (ctx.getData("retries") != null) {
                            requestInfo.setRetries(Integer.valueOf(String.valueOf(ctx.getData("retries"))));
                        } else {
                            requestInfo.setRetries(retries);
                        }
                        if (ctx != null) {
                            try {
                                // remove transient data
                                ctx.getData().remove("ClassLoader");

                                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                                ObjectOutputStream oout = new ObjectOutputStream(bout);
                                oout.writeObject(ctx);
                                requestInfo.setRequestData(bout.toByteArray());
                            } catch (IOException e) {
                                logger.warn("Error serializing context data", e);
                                requestInfo.setRequestData(null);
                            }
                        }

                        executorStoreService.persistRequest(requestInfo);
                    }
                }
            }
        }
    } catch (Exception e) {
        logger.warn("Unexpected error while processin executor's job {}", e.getMessage(), e);
    }
}

From source file:org.jbpm.executor.impl.ExecutorImpl.java

@Override
public void updateRequestData(Long requestId, Map<String, Object> data) {
    logger.debug("About to update request {} data with following {}", requestId, data);

    RequestInfo request = (RequestInfo) executorStoreService.findRequest(requestId);
    if (request.getStatus().equals(STATUS.CANCELLED) || request.getStatus().equals(STATUS.DONE)
            || request.getStatus().equals(STATUS.RUNNING)) {
        throw new IllegalStateException(
                "Request data can't be updated when request is in status " + request.getStatus());
    }/* w  w  w.  j a  va2s.co m*/

    CommandContext ctx = null;
    ClassLoader cl = getClassLoader(request.getDeploymentId());
    try {

        logger.debug("Processing Request Id: {}, status {} command {}", request.getId(), request.getStatus(),
                request.getCommandName());
        byte[] reqData = request.getRequestData();
        if (reqData != null) {
            ObjectInputStream in = null;
            try {
                in = new ClassLoaderObjectInputStream(cl, new ByteArrayInputStream(reqData));
                ctx = (CommandContext) in.readObject();
            } catch (IOException e) {
                logger.warn("Exception while serializing context data", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }
        }
    } catch (Exception e) {
        logger.error("Unexpected error when reading request data", e);
        throw new RuntimeException(e);
    }

    if (ctx == null) {
        ctx = new CommandContext();
    }

    WorkItem workItem = (WorkItem) ctx.getData("workItem");
    if (workItem != null) {
        logger.debug("Updating work item {} parameters with data {}", workItem, data);
        for (Entry<String, Object> entry : data.entrySet()) {
            workItem.setParameter(entry.getKey(), entry.getValue());
        }
    } else {
        logger.debug("Updating request context with data {}", data);
        for (Entry<String, Object> entry : data.entrySet()) {
            ctx.setData(entry.getKey(), entry.getValue());
        }
    }

    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oout = new ObjectOutputStream(bout);
        oout.writeObject(ctx);
        request.setRequestData(bout.toByteArray());
    } catch (IOException e) {
        throw new RuntimeException("Unable to save updated request data", e);
    }

    executorStoreService.updateRequest(request, null);
    logger.debug("Request {} data updated successfully", requestId);
}