Example usage for java.lang Thread interrupt

List of usage examples for java.lang Thread interrupt

Introduction

In this page you can find the example usage for java.lang Thread interrupt.

Prototype

public void interrupt() 

Source Link

Document

Interrupts this thread.

Usage

From source file:org.rdv.rbnb.RBNBController.java

public boolean connect(boolean block) {
    if (isConnected()) {
        return true;
    }/*from   ww  w .  j  av a2  s  .  c o m*/

    if (block) {
        final Thread object = Thread.currentThread();
        ConnectionListener listener = new ConnectionListener() {
            public void connecting() {
            }

            public void connected() {
                synchronized (object) {
                    object.notify();
                }
            }

            public void connectionFailed() {
                object.interrupt();
            }
        };
        addConnectionListener(listener);

        synchronized (object) {
            setState(STATE_STOPPED);

            try {
                object.wait();
            } catch (InterruptedException e) {
                return false;
            }
        }

        removeConnectionListener(listener);
    } else {
        setState(STATE_STOPPED);
    }

    return true;
}

From source file:com.yahoo.ycsb.webservice.rest.RestClient.java

private int httpExecute(HttpEntityEnclosingRequestBase request, String data) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();/*from www .  ja v  a 2 s.  c  o m*/
    int responseCode = 200;
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data.getBytes()),
            ContentType.APPLICATION_FORM_URLENCODED);
    reqEntity.setChunked(true);
    request.setEntity(reqEntity);
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    // If null entity don't bother about connection release.
    if (responseEntity != null) {
        InputStream stream = responseEntity.getContent();
        if (compressedResponse) {
            stream = new GZIPInputStream(stream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer responseContent = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (requestTimedout.isSatisfied()) {
                // Must avoid memory leak.
                reader.close();
                stream.close();
                EntityUtils.consumeQuietly(responseEntity);
                response.close();
                client.close();
                throw new TimeoutException();
            }
            responseContent.append(line);
        }
        timer.interrupt();
        // Closing the input stream will trigger connection release.
        stream.close();
    }
    EntityUtils.consumeQuietly(responseEntity);
    response.close();
    client.close();
    return responseCode;
}

From source file:fm.smart.r1.activity.ItemActivity.java

public void addToList(final String item_id) {
    final ProgressDialog myOtherProgressDialog = new ProgressDialog(this);
    myOtherProgressDialog.setTitle("Please Wait ...");
    myOtherProgressDialog.setMessage("Adding item to study list ...");
    myOtherProgressDialog.setIndeterminate(true);
    myOtherProgressDialog.setCancelable(true);

    final Thread add = new Thread() {
        public void run() {
            ItemActivity.add_item_result = addItemToList(Main.default_study_list_id, item_id,
                    ItemActivity.this);

            myOtherProgressDialog.dismiss();
            ItemActivity.this.runOnUiThread(new Thread() {
                public void run() {
                    final AlertDialog dialog = new AlertDialog.Builder(ItemActivity.this).create();
                    dialog.setTitle(ItemActivity.add_item_result.getTitle());
                    dialog.setMessage(ItemActivity.add_item_result.getMessage());
                    ItemActivity.add_item_result = null;
                    dialog.setButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        }//from w ww .  ja v  a 2 s .c o  m
                    });

                    dialog.show();
                }
            });

        }
    };
    myOtherProgressDialog.setButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            add.interrupt();
        }
    });
    OnCancelListener ocl = new OnCancelListener() {
        public void onCancel(DialogInterface arg0) {
            add.interrupt();
        }
    };
    myOtherProgressDialog.setOnCancelListener(ocl);
    closeMenu();
    myOtherProgressDialog.show();
    add.start();
}

From source file:com.yahoo.ycsb.webservice.rest.RestClient.java

private int httpGet(String endpoint, HashMap<String, ByteIterator> result) throws IOException {
    requestTimedout.setIsSatisfied(false);
    Thread timer = new Thread(new Timer(execTimeout, requestTimedout));
    timer.start();/*w  w  w.  j  a  va  2s  .  c o  m*/
    int responseCode = 200;
    HttpGet request = new HttpGet(endpoint);
    for (int i = 0; i < headers.length; i = i + 2) {
        request.setHeader(headers[i], headers[i + 1]);
    }
    CloseableHttpResponse response = client.execute(request);
    responseCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    // If null entity don't bother about connection release.
    if (responseEntity != null) {
        InputStream stream = responseEntity.getContent();
        /*
         * TODO: Gzip Compression must be supported in the future. Header[]
         * header = response.getAllHeaders();
         * if(response.getHeaders("Content-Encoding")[0].getValue().contains
         * ("gzip")) stream = new GZIPInputStream(stream);
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer responseContent = new StringBuffer();
        String line = "";
        while ((line = reader.readLine()) != null) {
            if (requestTimedout.isSatisfied()) {
                // Must avoid memory leak.
                reader.close();
                stream.close();
                EntityUtils.consumeQuietly(responseEntity);
                response.close();
                client.close();
                throw new TimeoutException();
            }
            responseContent.append(line);
        }
        timer.interrupt();
        result.put("response", new StringByteIterator(responseContent.toString()));
        // Closing the input stream will trigger connection release.
        stream.close();
    }
    EntityUtils.consumeQuietly(responseEntity);
    response.close();
    client.close();
    return responseCode;
}

From source file:org.apache.bookkeeper.replication.TestLedgerUnderreplicationManager.java

/**
 * Test enabling the ledger re-replication. After enableLedegerReplication,
 * should continue getLedgerToRereplicate() task
 *///w w  w  .  jav  a2 s . c  o m
@Test(timeout = 20000)
public void testEnableLedgerReplication() throws Exception {
    isLedgerReplicationDisabled = true;
    final LedgerUnderreplicationManager replicaMgr = lmf1.newLedgerUnderreplicationManager();

    // simulate few urLedgers before disabling
    final Long ledgerA = 0xfeadeefdacL;
    final String missingReplica = "localhost:3181";
    try {
        replicaMgr.markLedgerUnderreplicated(ledgerA, missingReplica);
    } catch (UnavailableException e) {
        LOG.debug("Unexpected exception while marking urLedger", e);
        fail("Unexpected exception while marking urLedger" + e.getMessage());
    }

    // disabling replication
    replicaMgr.disableLedgerReplication();
    LOG.debug("Disabled Ledeger Replication");

    String znodeA = getUrLedgerZnode(ledgerA);
    final CountDownLatch znodeLatch = new CountDownLatch(2);
    String urledgerA = StringUtils.substringAfterLast(znodeA, "/");
    String urLockLedgerA = basePath + "/locks/" + urledgerA;
    zkc1.exists(urLockLedgerA, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (event.getType() == EventType.NodeCreated) {
                znodeLatch.countDown();
                LOG.debug("Recieved node creation event for the zNodePath:" + event.getPath());
            }

        }
    });
    // getLedgerToRereplicate is waiting until enable rereplication
    Thread thread1 = new Thread() {
        @Override
        public void run() {
            try {
                Long lA = replicaMgr.getLedgerToRereplicate();
                assertEquals("Should be the ledger I just marked", lA, ledgerA);
                isLedgerReplicationDisabled = false;
                znodeLatch.countDown();
            } catch (UnavailableException e) {
                LOG.debug("Unexpected exception while marking urLedger", e);
                isLedgerReplicationDisabled = false;
            }
        }
    };
    thread1.start();

    try {
        assertFalse("shouldn't complete", znodeLatch.await(1, TimeUnit.SECONDS));
        assertTrue("Ledger replication is not disabled!", isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 2, znodeLatch.getCount());

        replicaMgr.enableLedgerReplication();
        znodeLatch.await(5, TimeUnit.SECONDS);
        LOG.debug("Enabled Ledeger Replication");
        assertTrue("Ledger replication is not disabled!", !isLedgerReplicationDisabled);
        assertEquals("Failed to disable ledger replication!", 0, znodeLatch.getCount());
    } finally {
        thread1.interrupt();
    }
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

protected void doAny(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = null;/*from w w  w .j  a v a  2 s .com*/
    Object result = null;

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}

From source file:org.hyperic.hq.agent.server.session.AgentSynchronizer.java

private void executeJob(final StatefulAgentDataTransferJob job) throws InterruptedException {
    final String name = Thread.currentThread().getName() + "-" + executorNum.getAndIncrement();
    final Thread thread = new Thread(name) {
        @Override/*www  . jav a2  s  .c o m*/
        public void run() {
            job.setLastRuntime();
            if (agentIsPingable(job)) {
                try {
                    job.execute();
                } catch (Throwable e) {
                    if (e instanceof InterruptedException) {
                        log.warn("jobdesc=" + job.getJobDescription() + " was interrupted: " + e);
                        log.debug(e, e);
                    } else {
                        log.error(e, e);
                    }
                }
                return;
            } else {
                log.warn("Could not ping agent in order to run job " + getJobInfo(job));
            }
        }
    };
    thread.start();
    thread.join(WAIT_TIME);
    // if the thread is alive just try to interrupt it and keep going
    final boolean threadIsAlive = thread.isAlive();
    final boolean jobWasSuccessful = job.wasSuccessful();
    final AvailabilityManager availabilityManager = ctx.getBean(AvailabilityManager.class);
    final boolean platformIsAvailable = availabilityManager.platformIsAvailableOrUnknown(job.getAgentId())
            || isInRestartState(job.getAgentId());
    if (jobWasSuccessful) {
        // do nothing, this is good!
        return;
    } else if (platformIsAvailable) {
        if (threadIsAlive) {
            thread.interrupt();
        }
        job.incrementFailures();

        if (log.isDebugEnabled()) {
            log.debug("executeJob, number of failures for execute job=" + getJobInfo(job) + " RuntimeId: "
                    + job.getRuntimeTime() + " " + job.getNumberOfFailures());
        }
        if (job.discardJob()) {
            job.onFailure(
                    "Too many failures on agent " + job.getAgentId() + " RuntimeId: " + job.getRuntimeTime());
        } else {
            reAddJob(job);
            if (threadIsAlive) {
                log.warn("AgentDataTransferJob=" + getJobInfo(job) + " has take more than "
                        + WAIT_TIME / 1000 / 60
                        + " minutes to run.  The agent appears alive so therefore the job was"
                        + " interrupted and requeued.  Job threadName={" + thread.getName() + "}");
            } else {
                log.warn("AgentDataTransferJob=" + getJobInfo(job)
                        + " died and was not successful.  The agent appears alive and"
                        + " therefore the job was requeued. " + " Job threadName={" + thread.getName() + "}"
                        + " RuntimeId: " + job.getRuntimeTime());
            }
        }
    } else {
        if (threadIsAlive) {
            thread.interrupt();
            log.warn("AgentDataTransferJob=" + getJobInfo(job) + " has take more than " + WAIT_TIME / 1000 / 60
                    + " minutes to run.  Discarding job threadName={" + thread.getName() + "}");
        }
        // Can't ping agent and platform availability is down, therefore agent must be down
        job.onFailure("Platform associated with agent " + job.getAgentId() + " is not available");
    }
}

From source file:org.silverpeas.core.process.io.file.TestHandledFile.java

@Test
public void testWaitForWithSuccessFileCreationInTime() throws Exception {
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));

    final Thread create = new Thread(new Runnable() {

        @Override//from  ww  w.  j av  a 2s .  c  om
        public void run() {
            try {
                Thread.sleep(450);
                touch(getFile(sessionComponentPath, "file"));
            } catch (final Exception e) {
            }
        }
    });
    final RunnableTest<Boolean> waitForRun = new RunnableTest<Boolean>() {
        @Override
        public void run() {
            result = false;
            result = getHandledFile(realComponentPath, "file").waitFor(1);
        }
    };
    final Thread waitFor = new Thread(waitForRun);

    try {
        create.start();
        waitFor.start();
        Thread.sleep(200);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(400);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(true));
        assertThat(waitForRun.getResult(), is(true));
        Thread.sleep(500);
    } finally {
        create.interrupt();
        waitFor.interrupt();
    }
    assertThat(waitForRun.getResult(), is(true));
    assertThat(getFile(sessionComponentPath, "file").exists(), is(true));
}

From source file:org.silverpeas.core.process.io.file.TestHandledFile.java

@Test
public void testWaitForForWithFailFileCreationInTime() throws Exception {
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));

    final Thread create = new Thread(new Runnable() {

        @Override// w ww. j  a  va 2 s .  c o m
        public void run() {
            try {
                Thread.sleep(1200);
                touch(getFile(sessionComponentPath, "file"));
            } catch (final Exception e) {
            }
        }
    });
    final RunnableTest<Boolean> waitForRun = new RunnableTest<Boolean>() {
        @Override
        public void run() {
            result = false;
            result = getHandledFile(realComponentPath, "file").waitFor(1);
        }
    };
    final Thread waitFor = new Thread(waitForRun);

    try {
        create.start();
        waitFor.start();
        Thread.sleep(200);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(400);
        assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
        assertThat(waitForRun.getResult(), is(false));
        Thread.sleep(500);
    } finally {
        create.interrupt();
        waitFor.interrupt();
    }
    assertThat(waitForRun.getResult(), is(false));
    assertThat(getFile(sessionComponentPath, "file").exists(), is(false));
}

From source file:com.streamsets.pipeline.stage.origin.hdfs.cluster.ClusterHDFSSourceIT.java

@Test(timeout = 30000)
public void testProduceDelimitedIgnoreHeader() throws Exception {
    ClusterHdfsConfigBean conf = new ClusterHdfsConfigBean();
    conf.hdfsUri = miniDFS.getURI().toString();
    conf.hdfsDirLocations = Arrays.asList(dir.toUri().getPath());
    conf.hdfsConfigs = new HashMap<>();
    conf.hdfsKerberos = false;/*from  w  ww. j av a2s.  c  o  m*/
    conf.hdfsConfDir = hadoopConfDir;
    conf.recursive = false;
    conf.produceSingleRecordPerMessage = false;
    conf.dataFormat = DataFormat.DELIMITED;
    conf.dataFormatConfig.csvFileFormat = CsvMode.CSV;
    conf.dataFormatConfig.csvHeader = CsvHeader.IGNORE_HEADER;
    conf.dataFormatConfig.csvMaxObjectLen = 4096;
    conf.dataFormatConfig.csvRecordType = CsvRecordType.LIST;
    conf.dataFormatConfig.csvSkipStartLines = 0;

    SourceRunner sourceRunner = new SourceRunner.Builder(ClusterHdfsDSource.class, createSource(conf))
            .addOutputLane("lane").setExecutionMode(ExecutionMode.CLUSTER_BATCH).setResourcesDir(resourcesDir)
            .build();

    sourceRunner.runInit();

    List<Map.Entry> list = new ArrayList<>();
    list.add(new Pair("path::0::0", new String("A,B\na,b")));
    list.add(new Pair("path::1::1", new String("C,D\nc,d")));

    Thread th = createThreadForAddingBatch(sourceRunner, list);
    try {
        StageRunner.Output output = sourceRunner.runProduce(null, 5);

        String newOffset = output.getNewOffset();
        Assert.assertEquals("path::1::1", newOffset);
        List<Record> records = output.getRecords().get("lane");
        Assert.assertEquals(2, records.size());
        Record record = records.get(0);
        Assert.assertEquals("C",
                record.get().getValueAsList().get(0).getValueAsMap().get("value").getValueAsString());
        Assert.assertFalse(record.has("[0]/header"));
        Assert.assertEquals("D",
                record.get().getValueAsList().get(1).getValueAsMap().get("value").getValueAsString());
        Assert.assertFalse(record.has("[1]/header"));
        record = records.get(1);
        Assert.assertEquals("c",
                record.get().getValueAsList().get(0).getValueAsMap().get("value").getValueAsString());
        Assert.assertFalse(record.has("[0]/header"));
        Assert.assertEquals("d",
                record.get().getValueAsList().get(1).getValueAsMap().get("value").getValueAsString());
        Assert.assertFalse(record.has("[1]/header"));

        if (sourceRunner != null) {
            sourceRunner.runDestroy();
        }
    } finally {
        th.interrupt();
    }
}