Example usage for java.lang InterruptedException InterruptedException

List of usage examples for java.lang InterruptedException InterruptedException

Introduction

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

Prototype

public InterruptedException() 

Source Link

Document

Constructs an InterruptedException with no detail message.

Usage

From source file:org.eclipse.triquetrum.workflow.editor.wizard.MomlExportOperation.java

/**
 * Export the passed file to the specified location
 *
 * @param file/*from ww  w .j a va  2s .co m*/
 *          org.eclipse.core.resources.IFile
 * @param location
 *          org.eclipse.core.runtime.IPath
 */
protected void exportFile(IFile file, IPath location) throws InterruptedException {
    IPath fullPath = location.append(file.getName()).removeFileExtension().addFileExtension("moml");
    monitor.subTask(file.getFullPath().toString());
    String properPathString = fullPath.toOSString();
    File targetFile = new File(properPathString);

    if (targetFile.exists()) {
        if (!targetFile.canWrite()) {
            errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0,
                    NLS.bind("Cannot overwrite file: {0}", targetFile.getAbsolutePath()), null));
            monitor.worked(1);
            return;
        }

        if (overwriteState == OVERWRITE_NONE) {
            return;
        }

        if (overwriteState != OVERWRITE_ALL) {
            String overwriteAnswer = overwriteCallback.queryOverwrite(properPathString);

            if (overwriteAnswer.equals(IOverwriteQuery.CANCEL)) {
                throw new InterruptedException();
            }

            if (overwriteAnswer.equals(IOverwriteQuery.NO)) {
                monitor.worked(1);
                return;
            }

            if (overwriteAnswer.equals(IOverwriteQuery.NO_ALL)) {
                monitor.worked(1);
                overwriteState = OVERWRITE_NONE;
                return;
            }

            if (overwriteAnswer.equals(IOverwriteQuery.ALL)) {
                overwriteState = OVERWRITE_ALL;
            }
        }
    }

    try {
        // 1. obtain Diagram for the file
        Diagram diagram = GraphitiUiInternal.getEmfService().getDiagramFromFile(file, new ResourceSetImpl());
        // 2. find root CompositeActor
        CompositeActor toplevel = (CompositeActor) Graphiti.getLinkService()
                .getBusinessObjectForLinkedPictogramElement(diagram);
        // 3. push location info of diagram model elements to the Ptolemy II model elements
        pushLocations(diagram, toplevel);
        // 4. exportMOML to the destination file
        FileUtils.writeStringToFile(new File(fullPath.toOSString()), toplevel.getWrappedObject().exportMoML());
    } catch (IOException e) {
        errorTable.add(new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, 0,
                NLS.bind("Error exporting {0}: {1}", fullPath, e.getMessage()), e));
    }

    monitor.worked(1);
    ModalContext.checkCanceled(monitor);
}

From source file:org.jenkinsci.plugins.objectstudio.ObjectStudioRunner.java

private void readLog(FilePath log, Proc proc) throws InterruptedException {

    BufferedReader reader = null;
    int lastLine = 0;

    try {//from ww w .  j a va 2 s . co  m
        String s = null;
        while (proc.isAlive()) {

            // Seems we need to open it again when running on remote node.
            // Which is really bad, should rewrite this to run on remote node.
            reader = new BufferedReader(new InputStreamReader(log.read()));
            int line = 1;
            int timeout = 0;

            while (proc.isAlive() && timeout < 10) {

                s = reader.readLine();
                while (s != null) {
                    if (line > lastLine) {
                        logger.println(s);
                        timeout = 0;
                    }
                    line++;
                    s = reader.readLine();
                }

                // Sleep here, so we do not create too much CPU overhead while ObjectStudio is working
                if (proc.isAlive()) {
                    Thread.sleep(1000);
                    timeout++;
                }
            }

            reader.close();
            lastLine = line - 1;
        }
    } catch (IOException e) {
        logger.println("Failed reading log " + log.getRemote());
        e.printStackTrace();
    } catch (InterruptedException e) {
        try {
            proc.kill();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
        throw new InterruptedException();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }
}

From source file:org.apache.http.impl.conn.JMeterPoolingClientConnectionManager.java

ManagedClientConnection leaseConnection(final Future<HttpPoolEntry> future, final long timeout,
        final TimeUnit tunit) throws InterruptedException, ConnectionPoolTimeoutException {
    final HttpPoolEntry entry;
    try {/*ww w  .j  a  va2 s  .c  o m*/
        entry = future.get(timeout, tunit);
        if (entry == null || future.isCancelled()) {
            throw new InterruptedException();
        }
        Asserts.check(entry.getConnection() != null, "Pool entry with no connection");
        if (this.log.isDebugEnabled()) {
            this.log.debug("Connection leased: " + format(entry) + formatStats(entry.getRoute()));
        }
        return new ManagedClientConnectionImpl(this, this.operator, entry);
    } catch (final ExecutionException ex) {
        Throwable cause = ex.getCause();
        if (cause == null) {
            cause = ex;
        }
        this.log.error("Unexpected exception leasing connection from pool", cause);
        // Should never happen
        throw new InterruptedException();
    } catch (final TimeoutException ex) {
        throw new ConnectionPoolTimeoutException("Timeout waiting for connection from pool");
    }
}

From source file:com.asakusafw.testdriver.inprocess.InProcessJobExecutorTest.java

/**
 * Test method for executing Hadoop job with errors.
 *///from   w w  w .j  a  v a2s. co m
@Test
public void executeJob_error() {
    prepareJobflow();
    MockHadoopJob.callback((args, conf) -> {
        throw new InterruptedException();
    });

    JobExecutor executor = new InProcessJobExecutor(context);
    try {
        executor.execute(job(MockHadoopJob.class.getName()), Collections.emptyMap());
        throw new IOException();
    } catch (IOException e) {
        throw new AssertionError(e);
    } catch (AssertionError e) {
        // ok.
    }
}

From source file:lockstep.LockstepServer.java

/**
 * This method puts the server in waiting for client connections. It returns
 * when the expected number of clients have successfully completed the 
 * handshake./*from www. j a  v  a2 s  . c o m*/
 * Parallel threads are started to handle the handshakes.
 * In case of failure, all threads are interrupted and then the exception is
 * propagated.
 * 
 * @throws IOException In case of failure on opening the ServerSocket and 
 * accepting connections through it 
 * @throws InterruptedException In case of failure during the handshake 
 * sessions
 */
private void handshakePhase() throws IOException, InterruptedException {
    ServerSocket tcpServerSocket = new ServerSocket(tcpPort);

    CyclicBarrier barrier = new CyclicBarrier(this.clientsNumber);
    CountDownLatch latch = new CountDownLatch(this.clientsNumber);

    //Each session of the protocol starts with a different random frame number
    int firstFrameNumber = (new Random()).nextInt(1000) + 100;

    Thread[] handshakeSessions = new Thread[clientsNumber];

    for (int i = 0; i < clientsNumber; i++) {
        Socket tcpConnectionSocket = tcpServerSocket.accept();
        LOG.info("Connection " + i + " accepted from " + tcpConnectionSocket.getInetAddress().getHostAddress());
        handshakeSessions[i] = new Thread(
                () -> serverHandshakeProtocol(tcpConnectionSocket, firstFrameNumber, barrier, latch, this));
        handshakeSessions[i].start();
    }
    try {
        latch.await();
    } catch (InterruptedException inEx) {
        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.interrupt();

        for (Thread handshakeSession : handshakeSessions)
            handshakeSession.join();

        throw new InterruptedException();
    }
    LOG.info("All handshakes completed");
}

From source file:at.alladin.rmbt.android.test.RMBTTask.java

private void doInBackground() {
    try {//from w  w  w . j a va 2 s . c om
        boolean error = false;
        connectionError.set(false);
        TestResult result = null;
        QoSResultCollector qosResult = null;

        try {
            final String uuid = fullInfo.getUUID();

            final String controlServer = ConfigHelper.getControlServerName(context);
            final int controlPort = ConfigHelper.getControlServerPort(context);
            final boolean controlSSL = ConfigHelper.isControlSeverSSL(context);

            final ArrayList<String> geoInfo = fullInfo.getCurLocation();

            client = RMBTClient.getInstance(controlServer, null, controlPort, controlSSL, geoInfo, uuid,
                    Config.RMBT_CLIENT_TYPE, Config.RMBT_CLIENT_NAME,
                    fullInfo.getInfo("CLIENT_SOFTWARE_VERSION"), null, fullInfo.getInitialInfo());

            if (client != null) {
                /*
                 * Example on how to implement the information collector tool:
                 *
                 * 
                */

                final InformationCollectorTool infoTool = new InformationCollectorTool(TimeUnit.NANOSECONDS,
                        TimeUnit.NANOSECONDS.convert(120, TimeUnit.SECONDS));
                infoTool.addCollector(new CpuStatCollector(new CpuStatAndroidImpl(),
                        TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS)));
                infoTool.addCollector(new MemInfoCollector(new MemInfoAndroidImpl(),
                        TimeUnit.NANOSECONDS.convert(1, TimeUnit.SECONDS)));
                client.setInformationCollectorTool(infoTool);
                client.startInformationCollectorTool();

                /////////////////////////////////////////////////////////////////

                client.setTrafficService(new TrafficServiceImpl());
                final ControlServerConnection controlConnection = client.getControlConnection();
                if (controlConnection != null) {
                    fullInfo.setUUID(controlConnection.getClientUUID());
                    fullInfo.setTestServerName(controlConnection.getServerName());
                }
            }
        } catch (final Exception e) {
            e.printStackTrace();
            error = true;
        }

        if (error || client == null) {
            connectionError.set(true);
        } else {

            if (client.getStatus() != TestStatus.ERROR) {
                try {
                    if (Thread.interrupted() || cancelled.get())
                        throw new InterruptedException();
                    Log.d(LOG_TAG, "runTest RMBTTask=" + this);
                    result = client.runTest();
                    final ControlServerConnection controlConnection = client.getControlConnection();

                    final InformationCollectorTool infoCollectorTool = client.getInformationCollectorTool();

                    if (result != null && !fullInfo.getIllegalNetworkTypeChangeDetcted()) {
                        final JSONObject infoObject = fullInfo
                                .getResultValues(controlConnection.getStartTimeNs());
                        if (infoCollectorTool != null) {
                            infoCollectorTool.stop();
                            infoObject.put("extended_test_stat", infoCollectorTool.getJsonObject(true,
                                    client.getControlConnection().getStartTimeNs()));
                        }

                        infoObject.put("publish_public_data", ConfigHelper.isInformationCommissioner(context));

                        client.sendResult(infoObject);
                    } else {
                        error = true;
                    }
                } catch (final Exception e) {
                    e.printStackTrace();
                } finally {
                    client.shutdown();
                }
            } else {
                System.err.println(client.getErrorMsg());
                error = true;
            }

            //client.shutdown();

            setPreviousTestStatus();
            QualityOfServiceTest qosTest = null;

            boolean runQoS = (client.getTaskDescList() != null && client.getTaskDescList().size() >= 1);

            //run qos test:
            if (runQoS && !error && !cancelled.get()) {
                try {

                    TestSettings qosTestSettings = new TestSettings();
                    qosTestSettings.setCacheFolder(context.getCacheDir());
                    qosTestSettings.setWebsiteTestService(new WebsiteTestServiceImpl(context));
                    qosTestSettings.setTrafficService(new TrafficServiceImpl());
                    qosTestSettings.setTracerouteServiceClazz(TracerouteAndroidImpl.class);
                    qosTestSettings.setStartTimeNs(getRmbtClient().getControlConnection().getStartTimeNs());
                    qosTestSettings.setUseSsl(ConfigHelper.isQoSSeverSSL(context));

                    qosTest = new QualityOfServiceTest(client, qosTestSettings);
                    qosReference.set(qosTest);
                    client.setStatus(TestStatus.QOS_TEST_RUNNING);
                    qosResult = qosTest.call();
                    InformationCollector.qoSResult = qosResult;

                    if (!cancelled.get()) {
                        if (qosResult != null && !qosTest.getStatus().equals(QoSTestEnum.ERROR)) {
                            client.sendQoSResult(qosResult);
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    error = true;
                }
            }

            if (qosTest != null && !cancelled.get() && qosTest.getStatus().equals(QoSTestEnum.QOS_FINISHED)) {
                if (ConfigHelper.isNDT(context)) {
                    qosTest.setStatus(QoSTestEnum.NDT_RUNNING);
                    runNDT();
                }
                qosTest.setStatus(QoSTestEnum.STOP);
            }
        }
    } catch (final Exception e) {
        client.setStatus(TestStatus.ERROR);
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } finally {
        try {
            if (client != null) {
                client.stopInformationCollectorTool();
                final TestStatus status = client.getStatus();
                if (!(status == TestStatus.ABORTED || status == TestStatus.ERROR))
                    client.setStatus(TestStatus.END);
            }
        } catch (Exception e) {
        }
    }
}

From source file:pl.nask.hsn2.service.hpc.CaptureTaskProcessingTest.java

private ServiceConnectorMock getModifiedServiceConnectorMock(final int noCalls) {

    return new ServiceConnectorMock() {
        @Override// w  ww . j a v a 2 s .co m
        public TaskRequest getTaskRequest() throws BusException, InterruptedException {
            int taskId;
            synchronized (taskRequestCalls) {
                if (taskRequestCalls.get() >= noCalls) {
                    throw new InterruptedException();
                }
                taskId = taskRequestCalls.incrementAndGet();
            }
            pl.nask.hsn2.protobuff.Process.TaskRequest.Builder trb = TaskRequest.newBuilder().setJob(2)
                    .setTaskId(taskId).setObject(taskId);
            return trb.build();
        }

        @Override
        public ObjectResponse getObjectStoreData(long jobId, List<Long> objectsId) throws StorageException {
            ObjectResponse.Builder b = ObjectResponse.newBuilder();
            ObjectData.Builder objDataBuilder = ObjectData.newBuilder();

            Builder attrBuilder = Attribute.newBuilder();
            attrBuilder.setName("url_original");
            attrBuilder.setType(Type.STRING);
            attrBuilder.setDataString("http://space.com/test " + objectsId.get(0) + " x.html");
            objDataBuilder.addAttrs(attrBuilder);

            b.addData(objDataBuilder.build());
            b.setType(ResponseType.SUCCESS_GET);
            return b.build();
        }

    };

}

From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java

/**
 * Creates all databases./* w w  w .j  a v a  2  s  . c om*/
 *
 * @throws IOException          I/O error in visitor method
 * @throws InterruptedException thread is interrupted
 */
public void createDatabases() throws IOException, InterruptedException {
    final long maxChunkSize = getMaxChunkSize();
    // Create databases
    FileVisitor<Path> basexPartitioner = new BasexFileVisitorPartitioner(maxChunkSize);
    Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, basexPartitioner);
    if (Thread.currentThread().isInterrupted()) {
        throw new InterruptedException();
    }
    logger.info("Added " + fileCount + " files (" + FileUtils.byteCountToDisplaySize(size) + ") to "
            + getDbCount() + " database(s) ");
    logger.info("Optimizing database " + dbBaseName + "-0");
    flushAndOptimize(ctx);
    new Open(dbBaseName + "-0").execute(ctx);
    new Close().execute(ctx);
    ctx.close();
    logger.info("Import completed");

}

From source file:com.hexidec.ekit.component.RelativeImageView.java

/** Method insures that the image is loaded and not a broken reference
  *//* w  w w  .jav  a2 s.  c  om*/
private void waitForImage() throws InterruptedException {
    int w = fImage.getWidth(this);
    int h = fImage.getHeight(this);
    while (true) {
        int flags = Toolkit.getDefaultToolkit().checkImage(fImage, w, h, this);
        if (((flags & ERROR) != 0) || ((flags & ABORT) != 0)) {
            throw new InterruptedException();
        } else if ((flags & (ALLBITS | FRAMEBITS)) != 0) {
            return;
        }
        Thread.sleep(10);
    }
}

From source file:cz.vity.freerapid.plugins.services.rapidshare_premium.RapidShareRunner.java

private void finalDownload(String url, HttpFileDownloadTask downloadTask) throws Exception {
    logger.info("Download URL: " + url);
    downloadTask.sleep(0);//from   w ww  .  j  av  a2 s.  c o m
    if (downloadTask.isTerminated()) {
        throw new InterruptedException();
    }
    httpFile.setState(DownloadState.GETTING);
    final GetMethod method = client.getGetMethod(url);
    try {
        final InputStream inputStream = client.makeFinalRequestForFile(method, httpFile, true);
        if (inputStream != null) {
            downloadTask.saveToFile(inputStream);
        } else {
            checkProblems();
            throw new IOException("File input stream is empty.");
        }
    } finally {
        method.abort(); //really important lines!!!!!
        method.releaseConnection();
    }
}