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(String s) 

Source Link

Document

Constructs an InterruptedException with the specified detail message.

Usage

From source file:org.smartfrog.services.www.bulkio.client.SunJavaBulkIOClient.java

@Override
public long doDownload(long ioSize) throws IOException, InterruptedException {
    validateURL();// www  .ja v  a  2s. co m
    URL target = createFullURL(ioSize, format);
    getLog().info("Downloading " + ioSize + " bytes from " + target);
    CRC32 checksum = new CRC32();
    HttpURLConnection connection = openConnection(target);
    connection.setRequestMethod(HttpAttributes.METHOD_GET);
    connection.setDoOutput(false);
    connection.connect();
    checkStatusCode(target, connection, HttpURLConnection.HTTP_OK);
    String contentLengthHeader = connection.getHeaderField(HttpHeaders.CONTENT_LENGTH);
    long contentLength = Long.parseLong(contentLengthHeader);
    if (contentLength != ioSize) {
        throw new IOException("Wrong content length returned from " + target + " - expected " + ioSize
                + " but got " + contentLength);
    }
    String formatHeader = connection.getHeaderField(HttpHeaders.CONTENT_TYPE);
    if (!format.equals(formatHeader)) {
        throw new IOException("Wrong content type returned from " + target + " - expected " + format
                + " but got " + formatHeader);
    }
    InputStream stream = connection.getInputStream();
    long bytes = 0;
    try {
        for (bytes = 0; bytes < ioSize; bytes++) {
            int octet = stream.read();
            checksum.update(octet);
            if (interrupted) {
                throw new InterruptedException(
                        "Interrupted after reading" + bytes + " bytes" + " from " + target);
            }
        }
    } finally {
        closeQuietly(stream);
    }
    long actualChecksum = checksum.getValue();
    getLog().info("Download finished after " + bytes + " bytes, checksum=" + actualChecksum);
    if (bytes != ioSize) {
        throw new IOException("Wrong content length downloaded from " + target + " - requested " + ioSize
                + " but got " + bytes);
    }
    if (expectedChecksumFromGet >= 0 && expectedChecksumFromGet != actualChecksum) {
        throw new IOException("Wrong checksum from download of " + ioSize + " bytes " + " from " + target
                + " expected " + expectedChecksumFromGet + " but got " + actualChecksum);
    }
    return bytes;
}

From source file:org.eclipse.swordfish.tooling.test.util.Util.java

/**
 * Waits for specified amount of milliseconds the specified tester to return true
 * @param tester - IWaitTester instance/* w w  w  . j a va  2s.  co  m*/
 * @param timeout - amount of milliseconds to wait
 * @param timeoutMessage - message of InterruptedException in case of timeout
 * @throws InterruptedException - in case waiting timed out 
 */
public static void waitFor(IWaitTester tester, int timeout, final String timeoutMessage)
        throws InterruptedException {
    int counter = timeout / WAIT_INTERVAL;
    while ((counter > 0) && !(tester.test())) {
        Thread.sleep(WAIT_INTERVAL);
        counter--;
    }
    if (counter <= 0) {
        throw new InterruptedException(timeoutMessage);
    }
}

From source file:org.wso2.carbon.dss.syntax.test.ReturnRequestStatusTest.java

@Test(groups = "wso2.dss", dependsOnMethods = {
        "requestStatusNameSpaceQualifiedForDeleteOperation" }, timeOut = 1000 * 60 * 2)
public void inOperationConcurrencyTest() throws InterruptedException, ConcurrencyTestFailedError {

    final ExceptionHandler handler = new ExceptionHandler();
    final int concurrencyNumber = 50;
    final int numberOfIterations = 1;
    Thread[] clientThread = new Thread[concurrencyNumber];
    final AxisServiceClient serviceClient = new AxisServiceClient();
    for (int i = 0; i < concurrencyNumber; i++) {
        final int empNo = i + 50;
        clientThread[i] = new Thread(new Runnable() {
            public void run() {
                for (int j = 0; j < numberOfIterations; j++) {
                    try {
                        OMElement response = serviceClient.sendReceive(getAddEmployeePayload(empNo + ""),
                                serviceEndPoint, "addEmployee");
                        Assert.assertTrue(response.toString().contains("SUCCESSFUL"),
                                "Response Not Successful");
                        OMNamespace nameSpace = response.getNamespace();
                        Assert.assertNotNull(nameSpace, "Response Message NameSpace not qualified");
                    } catch (AxisFault axisFault) {
                        log.error(axisFault);
                        handler.setException(axisFault);
                    }//from  w  w w.j ava 2  s . com
                }
            }
        });
        clientThread[i].setUncaughtExceptionHandler(handler);

    }

    for (int i = 0; i < concurrencyNumber; i++) {
        clientThread[i].start();
    }

    for (int i = 0; i < concurrencyNumber; i++) {
        try {
            clientThread[i].join();
        } catch (InterruptedException e) {
            throw new InterruptedException("Exception Occurred while joining Thread");
        }
    }

    if (!handler.isTestPass()) {
        throw new ConcurrencyTestFailedError(handler.getFailCount() + " service invocation/s failed out of "
                + concurrencyNumber * numberOfIterations + " service invocations.\n"
                + "Concurrency Test Failed for Thread Group=" + concurrencyNumber + " and loop count="
                + numberOfIterations, handler.getException());
    }
}

From source file:org.kawanfw.sql.jdbc.BlobHttp.java

/**
 * Constructor used when reading a downloaded Blob
 * //from   w w w  .  java 2 s.c  o  m
 * @param in
 *            the input stream of the Blob whic maps a
 *            {@code remoteInputStream}
 * @param connection
 *            the Connection to the remote servers which maps a
 *            {@code ConnectionHttp}
 */
BlobHttp(InputStream in, Connection connection) throws SQLException {

    this();

    OutputStream out = null;

    try {

        if (in == null) {
            throw new IllegalArgumentException(Tag.PRODUCT_PRODUCT_FAIL + " i is null.");
        }

        if (connection == null) {
            throw new IllegalArgumentException(Tag.PRODUCT_PRODUCT_FAIL + " connection is null.");
        }

        if (!(in instanceof RemoteInputStream)) {
            throw new IllegalArgumentException(
                    Tag.PRODUCT_PRODUCT_FAIL + " in is not instance of RemoteInputStream.");
        }

        if (!(connection instanceof ConnectionHttp)) {
            throw new IllegalArgumentException(
                    Tag.PRODUCT_PRODUCT_FAIL + " in is not instance of RemoteConnection.");
        }

        AtomicInteger progress = ((ConnectionHttp) connection).getProgress();
        AtomicBoolean cancelled = ((ConnectionHttp) connection).getCancelled();

        // reinit progress
        progress.set(0);

        long totalLength = ((RemoteInputStream) in).length();

        out = new BufferedOutputStream(new FileOutputStream(file));

        int tempLen = 0;
        byte[] buffer = new byte[1024 * 4];
        int n = 0;

        while ((n = in.read(buffer)) != -1) {
            tempLen += n;

            if (totalLength > 0 && tempLen > totalLength / 100) {
                tempLen = 0;
                int cpt = progress.get();
                cpt++;

                // Update the progress value for progress
                // indicator
                progress.set(Math.min(99, cpt));
            }

            // If progress indicator says that user has cancelled the
            // download, stop now!
            if (cancelled.get()) {
                throw new InterruptedException("Blob download cancelled by user.");
            }

            out.write(buffer, 0, n);
        }

    } catch (Exception e) {
        JdbcHttpTransferUtil.wrapExceptionAsSQLException(e);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}

From source file:ch.epfl.scapetoad.CartogramGastner.java

/**
 * Starts the cartogram computation using the given grid size.
 * @param gridSize the size of the grid used for computation. The
 *        grid size must be a power of 2.
 *//*from w  ww. jav  a 2  s  . c  om*/
public void compute(int gridSize) throws InterruptedException {

    // Store the grid size in the lx and ly attributes.
    lx = gridSize;
    ly = gridSize;

    this.initializeArrays();
    this.computeInitialDensity();
    FFT.coscosft(rho_0, 1, 1);

    boolean hasConverged = false;
    while (hasConverged == false) {
        if (Thread.interrupted()) {
            // Raise an InterruptedException.
            throw new InterruptedException("Computation has been interrupted by the user.");
        }

        hasConverged = this.integrateNonlinearVolterraEquation();

    }

    this.projectCartogramGrid();

}

From source file:org.wso2.carbon.registry.governance.api.test.old.LifeCycleServiceTestCase.java

@Test(groups = {
        "wso2.greg" }, description = "check service life cycle promote/demote test scenarios", dependsOnMethods = {
                "testAddWSDL" })
public void testCheckLifeCycle() throws RegistryException, InterruptedException, XPathExpressionException {
    String testStageState;/*from w  w w .ja v a2s  . c o  m*/

    if (!context.getContextTenant().getDomain().equalsIgnoreCase("CARBON.SUPPER")) {
        testStageState = "Tested";
    } else {
        testStageState = "Testing";
    }

    try {
        registry.associateAspect(wsdl_path, lcName);
        assertEquals(registry.get(wsdl_path).getProperty(StateProperty), "Development",
                "Default Service Life Cycle Development State Fail:");
        Thread.sleep(sleepTime);

        registry.invokeAspect(wsdl_path, lcName, "Promote"); //Promote Life cycle to Tested State
        assertEquals(registry.get(wsdl_path).getProperty(StateProperty), testStageState,
                "Service Life Cycle Promote to Test state fail :");
        Thread.sleep(3000);

        registry.invokeAspect(wsdl_path, lcName, "Promote"); //Promote Life cycle to Production State
        assertEquals(registry.get(wsdl_path).getProperty(StateProperty), "Production",
                "Service Life Cycle Promote to Production state fail:");
        Thread.sleep(3000);

        registry.invokeAspect(wsdl_path, lcName, "Demote"); //Demote Life cycle to Tested State
        assertEquals(registry.get(wsdl_path).getProperty(StateProperty), testStageState,
                "Service Life Cycle Demote to Test State fail :");
        Thread.sleep(3000);

        registry.invokeAspect(wsdl_path, lcName, "Demote"); //Demote Life cycle to Development State
        assertEquals(registry.get(wsdl_path).getProperty(StateProperty), "Development",
                "Service Life Cycle Demote to initial state fail:");
        Thread.sleep(3000);
        deleteWSDL(); //Delete wsdl

        Assert.assertFalse(registry.resourceExists(wsdl_path), "WSDL delete failed");
        log.info("LifeCycleServiceTestClient testCheckLifeCycle() - Passed");
    } catch (RegistryException e) {
        log.error("Failed to Promote/Demote Life Cycle :" + e);
        throw new RegistryException("Failed to Promote/Demote Life Cycle :" + e);
    } catch (InterruptedException e) {
        log.error("Failed to Promote/Demote Life Cycle :" + e);
        throw new InterruptedException("Failed to Promote/Demote Life Cycle :" + e);
    }
}

From source file:nya.miku.wishmaster.chans.infinity.LolifoxModule.java

@Override
public String sendPost(SendPostModel model, ProgressListener listener, CancellableTask task) throws Exception {
    if (task != null && task.isCancelled())
        throw new InterruptedException("interrupted");
    String url = getUsingUrl() + "post.php";
    ExtendedMultipartBuilder postEntityBuilder = ExtendedMultipartBuilder.create().setDelegates(listener, task)
            .addString("name", model.name).addString("email", model.sage ? "sage" : model.email)
            .addString("subject", model.subject).addString("body", model.comment)
            .addString("post", ""). //     ?.
            addString("board", model.boardName);
    if (model.threadNumber != null)
        postEntityBuilder.addString("thread", model.threadNumber);
    if (model.custommark)
        postEntityBuilder.addString("spoiler", "on");
    postEntityBuilder//w  w w . j  ava2  s. co  m
            .addString("password", TextUtils.isEmpty(model.password) ? getDefaultPassword() : model.password)
            .addString("json_response", "1");
    if (model.attachments != null) {
        String[] images = new String[] { "file", "file2", "file3", "file4" };
        for (int i = 0; i < model.attachments.length; ++i) {
            postEntityBuilder.addFile(images[i], model.attachments[i], model.randomHash);
        }
    }
    if (needNewThreadCaptcha) {
        postEntityBuilder.addString("captcha_text", model.captchaAnswer);
    }

    UrlPageModel refererPage = new UrlPageModel();
    refererPage.chanName = getChanName();
    refererPage.boardName = model.boardName;
    if (model.threadNumber == null) {
        refererPage.type = UrlPageModel.TYPE_BOARDPAGE;
        refererPage.boardPage = UrlPageModel.DEFAULT_FIRST_PAGE;
    } else {
        refererPage.type = UrlPageModel.TYPE_THREADPAGE;
        refererPage.threadNumber = model.threadNumber;
    }
    Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, buildUrl(refererPage)) };
    HttpRequestModel request = HttpRequestModel.builder().setPOST(postEntityBuilder.build())
            .setCustomHeaders(customHeaders).setNoRedirect(true).build();
    JSONObject json = HttpStreamer.getInstance().getJSONObjectFromUrl(url, request, httpClient, listener, task,
            false);
    if (json.has("error")) {
        String error = json.optString("error");
        if (error.equals("true") && json.optBoolean("banned"))
            throw new Exception("You are banned! ;_;");
        throw new Exception(error);
    } else {
        String redirect = json.optString("redirect", "");
        if (redirect.length() > 0)
            return fixRelativeUrl(redirect);
        return null;
    }
}

From source file:org.paxle.core.threading.impl.Pool.java

/**
 * @see IPool#returnWorker(IWorker)//ww w .ja v  a  2 s  .  c o m
 * @see GenericObjectPool#returnObject(Object)
 */
public void returnWorker(IWorker<Data> worker) {
    try {
        if (this.closed) {
            // thread pool already closed. Notify the worker thrad about this circumstance.
            throw new InterruptedException("Thread pool was closed");
        }

        if (this.isPooledWorker(worker)) {
            super.returnObject(worker);
        } else {
            this.factory.destroyObject(worker);
        }
    } catch (Exception e) {
        this.logger.error(String.format("Unexpected '%s' while returning worker thread into pool.",
                e.getClass().getName()), e);
        worker.terminate();
    } finally {
        if (!this.closed)
            this.removeActiveWorker(worker);
    }
}

From source file:org.openqa.selenium.os.OsProcess.java

public void waitFor(long timeout) throws InterruptedException {
    long until = System.currentTimeMillis() + timeout;
    boolean timedOut = true;
    while (System.currentTimeMillis() < until) {
        if (handler.hasResult()) {
            timedOut = false;//from   w w w. j  a  v  a  2  s.c o m
            break;
        }
        Thread.sleep(50);
    }
    if (timedOut) {
        throw new InterruptedException(String.format("Process timed out after waiting for %d ms.", timeout));
    }

    // Wait until syserr and sysout have been read
}

From source file:org.eclipse.osee.ote.core.test.shells.TelnetShell.java

/**
 * Sits on the line, reading in characters, and waits for the expected output from telnet
 * //from w w  w  .ja  va2s .c  om
 * @param string The String this function will stop on and return
 */
public synchronized void waitFor(String string) throws InterruptedException {
    if (inputBuffer.waitFor(string, true, MAX_RESPONSE_TIME) < 0) {
        throw new InterruptedException(
                "Waiting for '" + string + "' took longer then " + MAX_RESPONSE_TIME + " miliseconds.");
    }
}