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:uk.co.modularaudio.componentdesigner.controller.front.impl.ComponentDesignerFrontControllerImpl.java

private boolean callCheckOrStartAudioEngine(final boolean isStart) throws DatastoreException {
    boolean retVal = false;

    final UserPreferencesMVCController userPreferencesMVCController = userPreferencesController
            .getUserPreferencesMVCController();
    final UserPreferencesMVCModel prefsModel = userPreferencesMVCController.getModel();

    final HardwareIOConfiguration hardwareIOConfiguration = PrefsModelToHardwareIOConfigurationBridge
            .modelToConfiguration(prefsModel);

    final AppRenderingErrorCallback errorCallback = new AppRenderingErrorCallback() {

        @Override//  www  .ja  v  a  2 s  .com
        public void errorCallback(final AppRenderingErrorStruct error) {
            //            log.error( "AppRenderingErrorCallback happened: " + error.severity.toString() + " " + error.msg );

            if (error.severity == ErrorSeverity.FATAL) {
                if (isRendering()) {
                    toggleRendering();
                }
                stopAudioEngine();
            } else {
                log.warn(error.msg);
            }
        }

        @Override
        public String getName() {
            return "ApplicationAppRenderingErrorCallback(Anonymous)";
        }
    };

    try {
        if (isStart) {
            if (appRenderingSession != null) {
                throw new DatastoreException("Attempting to replace magical audio IO when one already exists!");
            }
            appRenderingSession = appRenderingController
                    .createAppRenderingSessionForConfiguration(hardwareIOConfiguration, errorCallback);
            final MadGraphInstance<?, ?> rgi = rackService.getRackGraphInstance(userVisibleRack);
            appRenderingSession.setApplicationGraph(rgi);

            appRenderingSession.startRendering();
            retVal = true;
        } else {
            // is a config test
            boolean wasRunningBeforeTest = false;
            if (appRenderingSession != null && appRenderingSession.isRendering()) {
                wasRunningBeforeTest = true;
                appRenderingSession.stopRendering();
                appRenderingSession.destroy();
                appRenderingSession = null;
                try {
                    Thread.currentThread();
                    Thread.sleep(AUDIO_ENGINE_RESTART_PAUSE_MILLIS);
                } catch (final InterruptedException e) {
                    log.error(e);
                }
            }

            final AppRenderingSession testAppRenderingSession = appRenderingController
                    .createAppRenderingSessionForConfiguration(hardwareIOConfiguration, errorCallback);
            retVal = testAppRenderingSession.testRendering(AUDIO_TEST_RUN_MILLIS);

            if (wasRunningBeforeTest && !retVal) {
                try {
                    Thread.sleep(AUDIO_ENGINE_RESTART_PAUSE_MILLIS);
                } catch (final InterruptedException e) {
                    log.error(e);
                }
                callCheckOrStartAudioEngine(true);
            }
        }
    } catch (final Exception e) {
        final String msg = "Exception caught calling check or start audio engine: " + e.toString();
        log.error(msg, e);
        if (appRenderingSession != null) {
            appRenderingSession.stopRendering();
            appRenderingSession.destroy();
            appRenderingSession = null;
        }
    }
    return retVal;
}

From source file:gdsc.smlm.engine.FitWorker.java

public void run() {
    try {// w w w  . ja  v a2 s  . co m
        while (!finished) {
            FitJob job = jobs.take();
            if (job == null || job.data == null || finished)
                break;
            run(job);
        }
    } catch (InterruptedException e) {
        System.out.println(e.toString());
        throw new RuntimeException(e);
    } finally {
        finished = true;
        //notifyAll();
    }
}

From source file:net.doubledoordev.backend.server.Server.java

/**
 * Downloads and uses specific forge installer
 *///from  w  w  w  .  j a  va 2  s  . c  o  m
public void installForge(final IMethodCaller methodCaller, final String name) {
    if (getOnline())
        throw new ServerOnlineException();
    final String version = Helper.getForgeVersionForName(name);
    if (version == null)
        throw new IllegalArgumentException("Forge with ID " + name + " not found.");
    if (downloading)
        throw new IllegalStateException("Already downloading something.");
    if (!isCoOwner(methodCaller.getUser()))
        throw new AuthenticationException();
    final Server instance = this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            downloading = true;
            try {
                // delete old files
                for (File file : folder.listFiles(ACCEPT_MINECRAFT_SERVER_FILTER))
                    file.delete();
                for (File file : folder.listFiles(ACCEPT_FORGE_FILTER))
                    file.delete();

                // download new files
                String url = Constants.FORGE_INSTALLER_URL.replace("%ID%", version);
                String forgeName = url.substring(url.lastIndexOf('/'));
                File forge = new File(folder, forgeName);
                FileUtils.copyURLToFile(new URL(url), forge);

                // run installer
                List<String> arguments = new ArrayList<>();

                arguments.add(Constants.getJavaPath());
                arguments.add("-Xmx1G");

                arguments.add("-jar");
                arguments.add(forge.getName());

                arguments.add("--installServer");

                ProcessBuilder builder = new ProcessBuilder(arguments);
                builder.directory(folder);
                builder.redirectErrorStream(true);
                final Process process = builder.start();
                printLine(arguments.toString());
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line;
                while ((line = reader.readLine()) != null) {
                    methodCaller.sendMessage(line);
                    printLine(line);
                }

                try {
                    process.waitFor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                for (String name : folder.list(ACCEPT_FORGE_FILTER))
                    getJvmData().jarName = name;

                forge.delete();

                methodCaller.sendDone();
                printLine("Forge installer done.");

                instance.update();
            } catch (IOException e) {
                printLine("##################################################################");
                printLine("Error installing a new forge version (version " + version + ")");
                printLine(e.toString());
                printLine("##################################################################");
                e.printStackTrace();
            }
            downloading = false;
        }
    }, getID() + "-forge-installer").start();
}

From source file:com.radiohitwave.ftpsync.API.java

private String CallBackend(String method) {
    int retryNum = 0;
    long retryTime = 0;
    if (!method.equals("ping")) {
        while (!this.IsOnline() && retryNum <= 10) {
            retryNum++;/*  w w w  . j a va 2 s  .  c  om*/
            retryTime = (long) (100 * Math.pow(2, retryNum));
            try {
                Thread.sleep(retryTime);
            } catch (InterruptedException ex) {
                Log.remoteError(ex);
                Log.error("Thread interrupted while waiting for Network");
            }
        }
        if (retryNum > 0) {
            Log.info("Needed " + retryNum + " retries (" + retryTime / 1000 + "sec) for API call (" + method
                    + ")");
            Log.remoteInfo("Needed " + retryNum + " retries (" + retryTime / 1000 + "sec) for API call ("
                    + method + ")");
        }
    }

    String response = "";

    try {
        String request = this.apiURL;
        request += "?q=" + method;
        request += "&u=" + URLDecoder.decode(this.loginName, "UTF-8");
        request += "&p=" + URLDecoder.decode(this.loginPassword, "UTF-8");

        Log.info("Calling API: <" + method + ">");

        URL url = new URL(request);
        InputStreamReader input = new InputStreamReader(url.openStream(), Charset.forName("UTF-8"));
        BufferedReader br = new BufferedReader(input);
        String strTemp = "";
        while (null != (strTemp = br.readLine())) {
            response += strTemp;
        }
    } catch (Exception ex) {
        Log.error(ex.toString());
        Log.remoteError(ex);
    }

    int responseLength = response.length();

    if (responseLength < minimumApiResponseCharsBeforeAlert) {
        Log.warning(
                "Response for API-Call <" + method + "> was very short (" + responseLength + " characters)");
        Log.remoteInfo("Short API-Response for <" + method + "> (" + responseLength + " chars)");
    }

    return response;
}

From source file:org.openhab.binding.stiebelheatpump.internal.StiebelHeatPumpBinding.java

/**
 * This method reads initially all information from the heat pump It read
 * the configuration file and loads all defined record definitions of sensor
 * data, status information , actual time settings and setting parameter
 * values.//w w w  . j  a v a  2 s.  c o  m
 *
 * @return true if heat pump information could be successfully read
 */
public boolean getInitialHeatPumpSettings() {
    CommunicationService communicationService = null;
    try {

        int retry = 0;
        while (communicationInUse) {
            try {
                Thread.sleep(CommunicationService.WAITING_TIME_BETWEEN_REQUESTS);
                retry++;
                if (retry > DEFAULT_SERIAL_TIMEOUT) {
                    return false;
                }
            } catch (InterruptedException e) {
                logger.error("could not access Heat pump for version {}", version);
            }
        }

        communicationInUse = true;

        communicationService = new CommunicationService(connector);
        Map<String, String> data = new HashMap<String, String>();
        Map<String, String> allData = new HashMap<String, String>();

        heatPumpConfiguration = communicationService.getHeatPumpConfiguration(version + ".xml");
        String version = communicationService.getversion();
        logger.info("Heat pump has version {}", version);
        allData.put("Version", version);

        data = communicationService.getSettings();
        allData.putAll(data);

        data = communicationService.getStatus();
        allData.putAll(data);

        data = communicationService.getSensors();
        allData.putAll(data);

        for (Map.Entry<String, String> entry : allData.entrySet()) {
            logger.debug("Data {} has value {}", entry.getKey(), entry.getValue());
        }

        publishValues(allData);

        return true;
    } catch (StiebelHeatPumpException e) {
        logger.error("Stiebel heatpump version could not be read from heat pump! " + e.toString());
    } finally {
        communicationInUse = false;
        if (communicationService != null) {
            communicationService.finalizer();
        }
    }

    return false;
}

From source file:com.siberhus.tdfl.DataFileLoader.java

/**
 * //  w w w.  j  a va 2s.c  o m
 * @param dataContext
 * @param reader
 * @param successWriter
 * @param errorWriter
 * @throws Exception
 */
private void _doReadProcessWrite(DataContext dataContext, DataFileReader reader, DataFileWriter successWriter,
        DataFileWriter errorWriter) throws Exception {

    boolean successLabeled = false, errorLabeled = false;

    reader.open(dataContext);

    String labels[] = null, values[] = null;
    if (reader.isReadLabels()) {
        labels = reader.read();
    }

    int successCount = 0, lineCount = 0;
    while ((values = reader.read()) != null) {
        lineCount++;
        dataContext.linesRead += reader.getLinesRead();
        FieldSet fieldSet = null;
        if (labels != null) {
            if (values.length > labels.length) {
                List<String> vList = new ArrayList<String>();
                for (int i = 0; i < labels.length; i++) {
                    vList.add(values[i]);
                }
                values = vList.toArray(new String[0]);
            }
            fieldSet = new DefaultFieldSet(values, labels);
        } else {
            fieldSet = new DefaultFieldSet(values);
        }

        FieldDataException fde = new FieldDataException();
        T item = null;
        try {
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException("Current thread is interrupted");
            }
            item = dataFileProcessor.mapLine(fieldSet, fde);
            if (item == null) {
                //skip
                continue;
            }
            dataFileProcessor.validateItem(item, fde);
            if (fde.hasErrors()) {
                if (fde.isForceProcess()) {
                    dataFileProcessor.processItem(item);
                }
                throw fde;
            }
            dataFileProcessor.processItem(item);
            successCount++;
            if (successCount == updateInterval) {
                successCount = 0;//reset
                dataFileProcessor.update();
                reader.update(dataContext);
                if (successWriter != null)
                    successWriter.update(dataContext);
                if (errorWriter != null)
                    errorWriter.update(dataContext);
                //TODO: save dataContext here
            }
            dataContext.itemSuccessCount++;
            dataFileProcessor.onItemSuccess(item);
            if (!successLabeled && labels != null) {
                lazyOpenWriterThenWriteLabels(dataContext, successWriter, labels);
                successLabeled = true;
            }
            lazyOpenWriterThenWrite(dataContext, successWriter, values);
            if (successWriter != null)
                dataContext.successLinesWritten += successWriter.getLinesWritten();
        } catch (InterruptedException e) {
            logger.info("Data processing is interrupted on file " + dataContext.getResource().getFilename());
            dataFileProcessor.onInterrupt(e);
            throw new DataFileLoaderException(e);
        } catch (Exception e) {
            if (!(e instanceof FieldDataException)) {
                if (e instanceof CancelException) {
                    logger.info(
                            "Data processing is cancelled on file " + dataContext.getResource().getFilename());
                    dataFileProcessor.onCancel((CancelException) e);
                    //                  break;
                    throw e;
                }
                logger.error(e.getMessage(), e);
            }
            dataContext.itemErrorCount++;
            dataFileProcessor.onItemError(item, e);

            if (!errorLabeled && labels != null) {
                lazyOpenWriterThenWriteLabels(dataContext, errorWriter, labels);
                errorLabeled = true;
            }
            String valuesWithErr[] = (String[]) ArrayUtils.add(values, e.toString());
            lazyOpenWriterThenWrite(dataContext, errorWriter, valuesWithErr);
            if (errorWriter != null)
                dataContext.errorLinesWritten += errorWriter.getLinesWritten();
        } finally {
            if (lineCount > 0) {
                //do again in case there are no success item.
                dataFileProcessor.update();
                reader.update(dataContext);
                if (successWriter != null)
                    successWriter.update(dataContext);
                if (errorWriter != null)
                    errorWriter.update(dataContext);
                //TODO: save dataContext here
            }
        }
    } //end while
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testBorrowObjectFairness() {
    // Config/*from w  w  w . j a v  a2s . c om*/
    int numThreads = 30;
    int maxActive = 10;

    SimpleFactory factory = new SimpleFactory();
    factory.setMaxActive(maxActive);
    pool.setFactory(factory);
    pool.setMaxActive(maxActive);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setTimeBetweenEvictionRunsMillis(-1);

    // Start threads to borrow objects
    TestThread[] threads = new TestThread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        threads[i] = new TestThread(pool, 1, 2000, false, String.valueOf(i % maxActive));
        Thread t = new Thread(threads[i]);
        t.start();
        // Short delay to ensure threads start in correct order
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            fail(e.toString());
        }
    }

    // Wait for threads to finish
    for (int i = 0; i < numThreads; i++) {
        while (!(threads[i]).complete()) {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                // ignored
            }
        }
        if (threads[i].failed()) {
            fail("Thread " + i + " failed: " + threads[i]._error.toString());
        }
    }
}

From source file:org.apache.nifi.cluster.coordination.http.replication.TestThreadPoolRequestReplicator.java

private void withReplicator(final WithReplicator function, final Status status, final long delayMillis,
        final RuntimeException failure, final String expectedRequestChain) {
    final ClusterCoordinator coordinator = createClusterCoordinator();
    final NiFiProperties nifiProps = NiFiProperties.createBasicNiFiProperties(null, null);
    final ThreadPoolRequestReplicator replicator = new ThreadPoolRequestReplicator(2, new Client(), coordinator,
            "1 sec", "1 sec", null, null, nifiProps) {
        @Override/*from  w  w  w. j  a va 2  s  .c  o  m*/
        protected NodeResponse replicateRequest(final WebResource.Builder resourceBuilder,
                final NodeIdentifier nodeId, final String method, final URI uri, final String requestId,
                Map<String, String> givenHeaders) {
            if (delayMillis > 0L) {
                try {
                    Thread.sleep(delayMillis);
                } catch (InterruptedException e) {
                    Assert.fail("Thread Interrupted during test");
                }
            }

            if (failure != null) {
                throw failure;
            }

            final OutBoundHeaders headers = (OutBoundHeaders) Whitebox.getInternalState(resourceBuilder,
                    "metadata");
            final Object proxiedEntities = headers.getFirst(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN);

            // ensure the request chain is in the request
            Assert.assertEquals(expectedRequestChain, proxiedEntities);

            // Return given response from all nodes.
            final ClientResponse clientResponse = new ClientResponse(status, new InBoundHeaders(),
                    new ByteArrayInputStream(new byte[0]), null);
            return new NodeResponse(nodeId, method, uri, clientResponse, -1L, requestId);
        }
    };

    try {
        function.withReplicator(replicator);
    } catch (final Exception e) {
        e.printStackTrace();
        Assert.fail(e.toString());
    } finally {
        replicator.shutdown();
    }
}