Example usage for java.lang InterruptedException toString

List of usage examples for java.lang InterruptedException toString

Introduction

In this page you can find the example usage for java.lang InterruptedException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.streamsets.pipeline.stage.origin.spooldir.SpoolDirSource.java

@Override
public String produce(String lastSourceOffset, int maxBatchSize, BatchMaker batchMaker) throws StageException {
    int batchSize = Math.min(conf.batchSize, maxBatchSize);
    // if lastSourceOffset is NULL (beginning of source) it returns NULL
    String file = getFileFromSourceOffset(lastSourceOffset);
    // if lastSourceOffset is NULL (beginning of source) it returns 0
    String offset = getOffsetFromSourceOffset(lastSourceOffset);
    if (hasToFetchNextFileFromSpooler(file, offset)) {
        currentFile = null;/*from  w ww  .ja va2 s . co  m*/
        try {
            File nextAvailFile = null;
            do {
                if (nextAvailFile != null) {
                    LOG.warn("Ignoring file '{}' in spool directory as is lesser than offset file '{}'",
                            nextAvailFile.getName(), file);
                }
                nextAvailFile = getSpooler().poolForFile(conf.poolingTimeoutSecs, TimeUnit.SECONDS);
            } while (!isFileFromSpoolerEligible(nextAvailFile, file, offset));

            if (nextAvailFile == null) {
                // no file to process
                LOG.debug("No new file available in spool directory after '{}' secs, producing empty batch",
                        conf.poolingTimeoutSecs);
            } else {
                // file to process
                currentFile = nextAvailFile;

                // if the current offset file is null or the file returned by the spooler is greater than the current offset
                // file we take the file returned by the spooler as the new file and set the offset to zero
                // if not, it means the spooler returned us the current file, we just keep processing it from the last
                // offset we processed (known via offset tracking)
                boolean pickFileFromSpooler = false;
                if (file == null) {
                    pickFileFromSpooler = true;
                } else if (useLastModified) {
                    File fileObject = new File(spooler.getSpoolDir(), file);
                    if (compareFiles(nextAvailFile, fileObject)) {
                        pickFileFromSpooler = true;
                    }
                } else if (nextAvailFile.getName().compareTo(file) > 0) {
                    pickFileFromSpooler = true;
                }
                if (pickFileFromSpooler) {
                    file = currentFile.getName();
                    offset = ZERO;
                }
            }
        } catch (InterruptedException ex) {
            // the spooler was interrupted while waiting for a file, we log and return, the pipeline agent will invoke us
            // again to wait for a file again
            LOG.warn("Pooling interrupted");
        }
    }

    if (currentFile != null) {
        // we have a file to process (from before or new from spooler)
        try {
            // we ask for a batch from the currentFile starting at offset
            offset = produce(currentFile, offset, batchSize, batchMaker);
        } catch (BadSpoolFileException ex) {
            LOG.error(Errors.SPOOLDIR_01.getMessage(), ex.getFile(), ex.getPos(), ex.toString(), ex);
            getContext().reportError(Errors.SPOOLDIR_01, ex.getFile(), ex.getPos(), ex.toString(), ex);
            try {
                // then we ask the spooler to error handle the failed file
                spooler.handleCurrentFileAsError();
            } catch (IOException ex1) {
                throw new StageException(Errors.SPOOLDIR_00, currentFile, ex1.toString(), ex1);
            }
            // we set the offset to -1 to indicate we are done with the file and we should fetch a new one from the spooler
            offset = MINUS_ONE;
        }
    }
    // create a new offset using the current file and offset
    return createSourceOffset(file, offset);
}

From source file:se.lu.nateko.edca.svc.GeoHelper.java

protected GeoHelper doInBackground(GeographyLayer... layers) {
    Log.d(TAG, "doInBackground(GeographyLayer...) called.");
    mGeoLayer = layers[0]; // Store the GeographyLayer reference.

    if (mRwMode != RWMODE_UPLOAD)
        startWatchingExternalStorage(); // Start to listen for changes in the storage state, upon which the operations may have to cancel.      

    /* Perform the task unless the storage is not available. */
    switch (mRwMode) {
    case RWMODE_READ: {
        if (!mExternalStorageAvailable)
            mService.showAlertDialog(mService.getString(R.string.service_sdunavailable), null);
        else//from   w  ww . j  a v a 2 s .co m
            mSuccess = readIntoGeographyLayer();
        break;
    }
    case RWMODE_WRITE: {
        if (!mExternalStorageWriteable)
            mService.showAlertDialog(mService.getString(R.string.service_sdunavailable), null);
        else
            mSuccess = writeFromGeographyLayer(false);
        break;
    }
    case RWMODE_OVERWRITE: {
        if (!mExternalStorageWriteable)
            mService.showAlertDialog(mService.getString(R.string.service_sdunavailable), null);
        else
            mSuccess = writeFromGeographyLayer(true);
        break;
    }
    case RWMODE_UPLOAD: {
        try { // Get or wait for exclusive access to the HttpClient.
            mHttpClient = mService.getHttpClient();
            mService.startAnimation(); // Start the animation, showing that a web communicating thread is active.
        } catch (InterruptedException e) {
            Log.e(TAG, "Thread " + Thread.currentThread().getId() + ": " + e.toString());
        }

        mSuccess = upload();
        mService.unlockHttpClient(); // Release the lock on the HttpClient, allowing new connections to be made.
        break;
    }
    default:
        Log.e(TAG, "Invalid read/write mode.");
    }

    return this;
}

From source file:org.springframework.yarn.test.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;// w  ww  .j  a va2 s.com
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            inReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
        }
        try {
            errReader.close();
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.now();
    }
}

From source file:de.forsthaus.webui.order.OrderDialogCtrl.java

private void doPrintOrderReport(Event event) throws InterruptedException {

    Order anOrder = getOrder();// w w  w.  j  ava2 s.c o m

    if (anOrder == null || anOrder.isNew()) {
        ZksampleMessageUtils.showErrorMessage(Labels.getLabel("message.error.PleaseFirstCreateOrder"));
        return;
    }

    Window win = (Window) Path.getComponent("/outerIndexWindow");

    try {
        new OrderDJReport(win, anOrder);
    } catch (final InterruptedException e) {
        ZksampleMessageUtils.showErrorMessage(e.toString());
    }

}

From source file:com.lenovo.tensorhusky.common.utils.Shell.java

/**
 * Run a command/*from   ww  w .  j  av a 2s  .c om*/
 */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        // One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(
            new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()));
    final BufferedReader inReader = new BufferedReader(
            new InputStreamReader(process.getInputStream(), Charset.defaultCharset()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    } catch (OutOfMemoryError oe) {
        LOG.error("Caught " + oe + ". One possible reason is that ulimit"
                + " setting of 'max user processes' is too low. If so, do"
                + " 'ulimit -u <largerNum>' and try again.");
        throw oe;
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        // make sure that the error thread exits
        joinThread(errThread);
        completed.set(true);
        // the timeout thread handling
        // taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled. the stream draining thread will attempt to
            // drain that fd!! it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            // issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        if (!completed.get()) {
            errThread.interrupt();
            joinThread(errThread);
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.monotonicNow();
    }
}

From source file:org.apache.hadoop.util.Shell.java

/** Run a command */
private void runCommand() throws IOException {
    ProcessBuilder builder = new ProcessBuilder(getExecString());
    Timer timeOutTimer = null;/* ww  w  .j ava2  s . c om*/
    ShellTimeoutTimerTask timeoutTimerTask = null;
    timedOut = new AtomicBoolean(false);
    completed = new AtomicBoolean(false);

    if (environment != null) {
        builder.environment().putAll(this.environment);
    }
    if (dir != null) {
        builder.directory(this.dir);
    }

    builder.redirectErrorStream(redirectErrorStream);

    if (Shell.WINDOWS) {
        synchronized (WindowsProcessLaunchLock) {
            // To workaround the race condition issue with child processes
            // inheriting unintended handles during process launch that can
            // lead to hangs on reading output and error streams, we
            // serialize process creation. More info available at:
            // http://support.microsoft.com/kb/315939
            process = builder.start();
        }
    } else {
        process = builder.start();
    }

    if (timeOutInterval > 0) {
        timeOutTimer = new Timer("Shell command timeout");
        timeoutTimerTask = new ShellTimeoutTimerTask(this);
        //One time scheduling.
        timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
    }
    final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    final StringBuffer errMsg = new StringBuffer();

    // read error and input streams as this would free up the buffers
    // free the error stream buffer
    Thread errThread = new Thread() {
        @Override
        public void run() {
            try {
                String line = errReader.readLine();
                while ((line != null) && !isInterrupted()) {
                    errMsg.append(line);
                    errMsg.append(System.getProperty("line.separator"));
                    line = errReader.readLine();
                }
            } catch (IOException ioe) {
                LOG.warn("Error reading the error stream", ioe);
            }
        }
    };
    try {
        errThread.start();
    } catch (IllegalStateException ise) {
    }
    try {
        parseExecResult(inReader); // parse the output
        // clear the input stream buffer
        String line = inReader.readLine();
        while (line != null) {
            line = inReader.readLine();
        }
        // wait for the process to finish and check the exit code
        exitCode = process.waitFor();
        try {
            // make sure that the error thread exits
            errThread.join();
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while reading the error stream", ie);
        }
        completed.set(true);
        //the timeout thread handling
        //taken care in finally block
        if (exitCode != 0) {
            throw new ExitCodeException(exitCode, errMsg.toString());
        }
    } catch (InterruptedException ie) {
        throw new IOException(ie.toString());
    } finally {
        if (timeOutTimer != null) {
            timeOutTimer.cancel();
        }
        // close the input stream
        try {
            // JDK 7 tries to automatically drain the input streams for us
            // when the process exits, but since close is not synchronized,
            // it creates a race if we close the stream first and the same
            // fd is recycled.  the stream draining thread will attempt to
            // drain that fd!!  it may block, OOM, or cause bizarre behavior
            // see: https://bugs.openjdk.java.net/browse/JDK-8024521
            //      issue is fixed in build 7u60
            InputStream stdout = process.getInputStream();
            synchronized (stdout) {
                inReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the input stream", ioe);
        }
        try {
            if (!completed.get()) {
                errThread.interrupt();
                errThread.join();
            }
        } catch (InterruptedException ie) {
            LOG.warn("Interrupted while joining errThread");
        }
        try {
            InputStream stderr = process.getErrorStream();
            synchronized (stderr) {
                errReader.close();
            }
        } catch (IOException ioe) {
            LOG.warn("Error while closing the error stream", ioe);
        }
        process.destroy();
        lastTime = Time.now();
    }
}

From source file:de.zib.gndms.GORFX.context.service.globus.resource.TaskResource.java

@Override
public void remove() {

    if (taskAction != null) {
        Log log = taskAction.getLog();// ww  w . j a  v  a2  s .  com
        log.debug("Removing task resource: " + getID());
        AbstractTask tsk = taskAction.getModel();
        boolean cleanUp = false;
        if (tsk != null) {
            if (!tsk.isDone()) {
                // task is still running cancel it and cleanup entity manager
                taskAction.setCancelled(true);
                log.debug("cancel task " + tsk.getWid());
                cleanUp = true;
                if (future != null) {
                    future.cancel(true);
                    try {
                        // give cancel some time
                        Thread.sleep(2000L);
                    } catch (InterruptedException e) {
                        logger.debug(e);
                    }
                }

                try {
                    EntityManager em = taskAction.getEntityManager();
                    if (em != null && em.isOpen()) {
                        try {
                            EntityTransaction tx = em.getTransaction();
                            if (tx.isActive())
                                tx.rollback();
                        } finally {
                            em.close();
                        }
                    }
                } catch (Exception e) {
                    // don't bother with exceptions
                    log.debug("Exception on task future cancel: " + e.toString(), e);
                }
            }

            EntityManager em = home.getEntityManagerFactory().createEntityManager();
            TxFrame tx = new TxFrame(em);
            // cleanup if necessary
            try {
                try {
                    Task t = em.find(Task.class, tsk.getId());
                    t.setPostMortem(true);
                    tx.commit();

                    if (cleanUp) {
                        log.debug("Triggering task cleanup");
                        try {
                            taskAction.setOwnEntityManager(em);
                            taskAction.cleanUpOnFail(t);
                        } catch (Exception e) {
                            log.debug("Exception on cleanup: " + e.toString());
                        }
                    }

                    // remove task from db
                    log.debug("Removing task: " + t.getId());
                    tx.begin();
                    em.remove(t);
                    tx.commit();
                } finally {
                    tx.finish();
                    if (em.isOpen())
                        em.close();
                }
            } catch (Exception e) {
                log.debug("Exception on task resource removal: " + e.toString());
                e.printStackTrace();
            }
        }
    }
}

From source file:ni.org.ics.estudios.appmovil.bluetooth.activity.BluetoothChatFragment.java

private void manageReceiveHandShake(String mensaje) {
    //RECEPTOR---->Recibe Casa
    if (mensaje.startsWith("INSERT INTO chf_casas_cohorte_familia")) {
        casaSQL = mensaje;//from   w w  w.j  a v  a  2  s  .c om
        int codigoComienza = 47;
        int codigoTermina = casaSQL.indexOf(",", 0) - 1;
        codigoCHF = casaSQL.substring(codigoComienza, codigoTermina);
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        //RECEPTOR---->Manda mensaje fin de casa y comienza participante
        sendMessage(this.getString(R.string.start_part));
    }
    //EMISOR---->Recibe mensaje de iniciar participante
    else if (mensaje.equals(this.getString(R.string.start_part))) {
        //EMISOR---->Consulta si hay participantes por enviar
        if (totalPartEnviar > contador) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            //EMISOR---->Enva participante
            enviarParticipante(contador);
            //Pausa para no pegar los dos mensajes
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            //EMISOR---->Enva participante CHF
            enviarParticipanteCHF(contador);
            //Aumenta el contador
            contador++;
        }
        //Si no hay participantes inicia procesos
        else {
            //EMISOR---->Envia mensaje que terminaron participantes y reinicia contador
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            contador = 0;
            sendMessage(this.getString(R.string.finished_part));
        }
    }
    //RECEPTOR---->Recibe participante
    else if (mensaje.startsWith("INSERT INTO participantes ")) {
        participantesSQL[totalPartEnviados] = mensaje;
    }
    //RECEPTOR---->Recibe participante CHF
    else if (mensaje.startsWith("INSERT INTO chf_participantes ")) {
        participantesChfSQL[totalPartEnviados] = mensaje;
        totalPartEnviados++;
        //Pausa
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        ////RECEPTOR---->Manda mensaje de enviar otro participante
        sendMessage(this.getString(R.string.start_part));
    }
    //EMISOR---->Recibe mensaje de iniciar procesos participante
    else if (mensaje.equals(this.getString(R.string.start_partproc))) {
        //EMISOR---->Consulta si hay participantes por enviar
        if (totalPartEnviar > contador) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            //EMISOR---->Enva participante procesos
            enviarParticipanteProc(contador);
            //Aumenta el contador
            contador++;
        }
        //Si no hay procesos participantes inicia seroprevalencia
        else {
            //EMISOR---->Envia mensaje que terminaron participantes y reinicia contador
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            contador = 0;
            sendMessage(this.getString(R.string.finished_partproc));
        }
    }
    //RECEPTOR---->Recibe participante
    else if (mensaje.startsWith("INSERT INTO participantes_procesos")) {
        participantesProcSQL[totalProcEnviados] = mensaje;
        totalProcEnviados++;
        ////RECEPTOR---->Manda mensaje de enviar otro participante proceso
        sendMessage(this.getString(R.string.start_partproc));
    }
    //RECEPTOR---->Recibe mensaje de que ya no hay participantes
    else if (mensaje.equals(this.getString(R.string.finished_part))) {
        //RECEPTOR---->Envia mensaje que inicien participantes procesos
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        sendMessage(this.getString(R.string.start_partproc));
    }
    //RECEPTOR---->Recibe mensaje de que ya no hay participantes
    else if (mensaje.equals(this.getString(R.string.finished_partproc))) {
        //RECEPTOR---->Envia mensaje que inicien participantes de seroprevalencia
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        sendMessage(this.getString(R.string.start_partcasos));
    }
    //EMISOR---->Recibe mensaje de iniciar procesos participante
    else if (mensaje.equals(this.getString(R.string.start_partcasos))) {
        //EMISOR---->Consulta si hay casos de participantes por enviar
        if (totalPartCasosEnviar > contador) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            //EMISOR---->Enva participante procesos
            enviarParticipanteCaso(contador);
            //Aumenta el contador
            contador++;
        }
        //Si no hay casos de participantes inicia seroprevalencia
        else {
            //EMISOR---->Envia mensaje que terminaron participantes y reinicia contador
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            contador = 0;
            sendMessage(this.getString(R.string.finished_partcasos));
        }
    }
    //RECEPTOR---->Recibe caso de participante
    else if (mensaje.startsWith("INSERT INTO chf_participantes_casos")) {
        participantesCasosSQL[totalCasosEnviados] = mensaje;
        totalCasosEnviados++;
        ////RECEPTOR---->Manda mensaje de enviar otro caso participante
        sendMessage(this.getString(R.string.start_partcasos));
    }
    //RECEPTOR---->Recibe mensaje de que ya no hay casos
    else if (mensaje.equals(this.getString(R.string.finished_partcasos))) {
        //RECEPTOR---->Envia mensaje que inicien participantes de seroprevalencia
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        sendMessage(this.getString(R.string.start_partsa));
    }
    //EMISOR---->Recibe mensaje de inicio de seroprevalencia
    else if (mensaje.equals(this.getString(R.string.start_partsa))) {
        //EMISOR---->Consulta si hay participantes seroprev por enviar
        if (totalPartSeroEnviar > contador) {
            //EMISOR---->Enva participante se seroprevalencia
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            enviarParticipanteSero(contador);
            //Aumenta el contador
            contador++;
        }
        //Si no hay participantes seroprevalencia finaliza
        else {
            //EMISOR---->Enva mensaje de finalizar
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            sendMessage(this.getString(R.string.finished));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                android.util.Log.d(TAG, ex.toString());
            }
            //finaliza servicio
            if (mChatService != null) {
                mChatService.stop();
                mChatService = null;
                mBluetoothAdapter.disable();
            }
            //Finaliza actividad
            Bundle arguments = new Bundle();
            if (mCasa != null)
                arguments.putSerializable(Constants.CASA, mCasa);
            Intent i = new Intent(getActivity(), MenuCasaActivity.class);
            i.putExtras(arguments);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);
            getActivity().finish();
        }
    }
    //RECEPTOR---->Recibe participante seroprevalencia
    else if (mensaje.startsWith("INSERT INTO sa_participante_seroprevalencia")) {
        participantesSeroSQL[totalPartSeroEnviados] = mensaje;
        totalPartSeroEnviados++;
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            android.util.Log.d(TAG, ex.toString());
        }
        ////RECEPTOR---->Manda mensaje de enviar otro participante
        sendMessage(this.getString(R.string.start_partsa));
    }
    //RECEPTOR---->Recibe mensaje de que ya se termino, guarda y finaliza
    else if (mensaje.equals(this.getString(R.string.finished))) {
        new SaveDataCasaTask().execute();
    }
}

From source file:com.undatech.opaque.RemoteCanvas.java

/**
 * Initialize the canvas to show the remote desktop
 *//*  w  w  w. j  a  v a2  s.  co m*/
void initialize(final ConnectionSettings settings) {
    checkNetworkConnectivity();
    initializeClipboardMonitor();
    this.settings = settings;

    Thread cThread = new Thread() {
        @Override
        public void run() {
            try {
                spicecomm = new SpiceCommunicator(getContext(), RemoteCanvas.this,
                        settings.isRequestingNewDisplayResolution());
                pointer = new RemoteSpicePointer(spicecomm, RemoteCanvas.this, handler);
                keyboard = new RemoteSpiceKeyboard(getResources(), spicecomm, RemoteCanvas.this, handler,
                        settings.getLayoutMap());
                spicecomm.setHandler(handler);

                // Obtain user's password if necessary.
                if (settings.getPassword().equals("")) {
                    android.util.Log.i(TAG, "Displaying a dialog to obtain user's password.");
                    handler.sendEmptyMessage(Constants.GET_PASSWORD);
                    synchronized (spicecomm) {
                        spicecomm.wait();
                    }
                }

                String ovirtCaFile = null;
                if (settings.isUsingCustomOvirtCa()) {
                    ovirtCaFile = settings.getOvirtCaFile();
                } else {
                    String caBundleFileName = getContext().getFilesDir() + "/ca-bundle.crt";
                    ovirtCaFile = caBundleFileName;
                }

                // If not VM name is specified, then get a list of VMs and let the user pick one.
                if (settings.getVmname().equals("")) {
                    int success = spicecomm.fetchOvirtVmNames(settings.getHostname(), settings.getUser(),
                            settings.getPassword(), ovirtCaFile, settings.isSslStrict());
                    // VM retrieval was unsuccessful we do not continue.
                    ArrayList<String> vmNames = spicecomm.getVmNames();
                    if (success != 0 || vmNames.isEmpty()) {
                        return;
                    } else {
                        // If there is just one VM, pick it and skip the dialog.
                        if (vmNames.size() == 1) {
                            settings.setVmname(vmNames.get(0));
                            settings.saveToSharedPreferences(getContext());
                        } else {
                            while (settings.getVmname().equals("")) {
                                android.util.Log.i(TAG, "Displaying a dialog with VMs to the user.");
                                handler.sendEmptyMessage(Constants.DIALOG_DISPLAY_VMS);
                                synchronized (spicecomm) {
                                    spicecomm.wait();
                                }
                            }
                        }
                    }
                }

                spicecomm.connectOvirt(settings.getHostname(), settings.getVmname(), settings.getUser(),
                        settings.getPassword(), ovirtCaFile, settings.isAudioPlaybackEnabled(),
                        settings.isSslStrict());

                try {
                    synchronized (spicecomm) {
                        spicecomm.wait(32000);
                    }
                } catch (InterruptedException e) {
                }

                if (!spiceUpdateReceived) {
                    handler.sendEmptyMessage(Constants.SPICE_CONNECT_FAILURE);
                }
            } catch (Throwable e) {
                if (stayConnected) {
                    e.printStackTrace();
                    android.util.Log.e(TAG, e.toString());

                    if (e instanceof OutOfMemoryError) {
                        disposeDrawable();
                        disconnectAndShowMessage(R.string.error_out_of_memory, R.string.error_dialog_title);
                    }
                }
            }
        }
    };
    cThread.start();
}

From source file:com.chinamobile.bcbsp.util.BSPJob.java

/**
 * If the job ready, submit the job, and start monitor.
 * @param verbose//  w  ww . j ava  2  s.co  m
 *        User has set true if the job ready.
 * @return job state.
 */
public boolean waitForCompletion(boolean verbose) {
    try {
        /** To set the params for aggregators. */
        completeAggregatorRegister();
        if (state == JobState.DEFINE) {
            submit();
        }
        if (verbose) {
            jobClient.monitorAndPrintJob(this, info);
        } else {
            info.waitForCompletion();
        }
        return isSuccessful();
    } catch (ClassNotFoundException lnfE) {
        LOG.error("Exception has been catched in BSPJob--waitForCompletion !", lnfE);
        Fault f = new Fault(Fault.Type.DISK, Fault.Level.WARNING, "null", lnfE.toString());
        jobClient.getJobSubmitClient().recordFault(f);
        jobClient.getJobSubmitClient().recovery(new BSPJobID("before have an BSPJobId !", -1));
        return false;
    } catch (InterruptedException iE) {
        LOG.error("Exception has been catched in BSPJob--waitForCompletion !", iE);
        Fault f = new Fault(Fault.Type.SYSTEMSERVICE, Fault.Level.INDETERMINATE, "null", iE.toString());
        jobClient.getJobSubmitClient().recordFault(f);
        jobClient.getJobSubmitClient().recovery(new BSPJobID("before have an BSPJobId !", -1));
        return false;
    } catch (IOException ioE) {
        LOG.error("Exception has been catched in BSPJob--waitForCompletion !", ioE);
        Fault f = new Fault(Fault.Type.SYSTEMSERVICE, Fault.Level.INDETERMINATE, "null", ioE.toString());
        jobClient.getJobSubmitClient().recordFault(f);
        jobClient.getJobSubmitClient().recovery(new BSPJobID("before have an BSPJobId !", -1));
        return false;
    }
}