Search in sources :

Example 81 with CancellationException

use of java.util.concurrent.CancellationException in project scribejava by scribejava.

the class OauthAsyncCompletionHandlerTest method shouldReleaseLatchOnCancel.

@Test
public void shouldReleaseLatchOnCancel() throws Exception {
    handler = new OAuthAsyncCompletionHandler<>(callback, ALL_GOOD_RESPONSE_CONVERTER);
    final HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("4", 1, 1), 200, "ok"));
    final BasicHttpEntity entity = new BasicHttpEntity();
    entity.setContent(new ByteArrayInputStream(new byte[0]));
    response.setEntity(entity);
    handler.cancelled();
    assertNull(callback.getResponse());
    assertNotNull(callback.getThrowable());
    assertTrue(callback.getThrowable() instanceof CancellationException);
    // verify latch is released
    try {
        handler.getResult();
        fail();
    } catch (ExecutionException expected) {
    // expected
    }
}
Also used : BasicHttpResponse(org.apache.http.message.BasicHttpResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) CancellationException(java.util.concurrent.CancellationException) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) ProtocolVersion(org.apache.http.ProtocolVersion) ExecutionException(java.util.concurrent.ExecutionException) BasicStatusLine(org.apache.http.message.BasicStatusLine) Test(org.junit.Test)

Example 82 with CancellationException

use of java.util.concurrent.CancellationException in project atlasdb by palantir.

the class InterruptibleFuture method cancel.

@Override
public final boolean cancel(boolean mayInterruptIfRunning) {
    lock.lock();
    try {
        if (state == State.WAITING_TO_RUN) {
            cancellationException = new CancellationException("Cancel was successful.");
            noteFinished();
        }
    } finally {
        lock.unlock();
    }
    return futureTask.cancel(mayInterruptIfRunning);
}
Also used : CancellationException(java.util.concurrent.CancellationException)

Example 83 with CancellationException

use of java.util.concurrent.CancellationException in project cdap by caskdata.

the class ExploreStatement method execute.

/**
 * Executes a query and wait until it is finished, but does not close the session.
 */
@Override
public boolean execute(String sql) throws SQLException {
    if (isClosed) {
        throw new SQLException("Can't execute after statement has been closed");
    }
    if (resultSet != null) {
        // As requested by the Statement interface javadoc, "All execution methods in the Statement interface
        // implicitly close a statement's current ResultSet object if an open one exists"
        resultSet.close();
        resultSet = null;
    }
    futureResults = exploreClient.submit(namespace, sql);
    try {
        resultSet = new ExploreResultSet(futureResults.get(), this, maxRows);
        // Here we have a result, it may contain rows or may be empty, but it exists.
        return true;
    } catch (InterruptedException e) {
        LOG.error("Caught exception", e);
        Thread.currentThread().interrupt();
        return false;
    } catch (ExecutionException e) {
        Throwable t = Throwables.getRootCause(e);
        if (t instanceof HandleNotFoundException) {
            LOG.error("Error executing query", e);
            throw new SQLException("Unknown state");
        }
        LOG.error("Caught exception", e);
        throw new SQLException(Throwables.getRootCause(e));
    } catch (CancellationException e) {
        // If futureResults has been cancelled
        return false;
    }
}
Also used : HandleNotFoundException(co.cask.cdap.explore.service.HandleNotFoundException) SQLException(java.sql.SQLException) CancellationException(java.util.concurrent.CancellationException) ExecutionException(java.util.concurrent.ExecutionException)

Example 84 with CancellationException

use of java.util.concurrent.CancellationException in project keepass2android by PhilippC.

the class LocalFileProvider method listFiles.

// doRetrieveFileInfo()
/**
 * Lists all file inside {@code dir}.
 *
 * @param taskId
 *            the task ID.
 * @param dir
 *            the source directory.
 * @param showHiddenFiles
 *            {@code true} or {@code false}.
 * @param filterMode
 *            can be one of {@link BaseFile#FILTER_DIRECTORIES_ONLY},
 *            {@link BaseFile#FILTER_FILES_ONLY},
 *            {@link BaseFile#FILTER_FILES_AND_DIRECTORIES}.
 * @param limit
 *            the limit.
 * @param positiveRegex
 *            the positive regex filter.
 * @param negativeRegex
 *            the negative regex filter.
 * @param results
 *            the results.
 * @param hasMoreFiles
 *            the first item will contain a value representing that there is
 *            more files (exceeding {@code limit}) or not.
 */
private void listFiles(final int taskId, final File dir, final boolean showHiddenFiles, final int filterMode, final int limit, String positiveRegex, String negativeRegex, final List<File> results, final boolean[] hasMoreFiles) {
    final Pattern positivePattern = Texts.compileRegex(positiveRegex);
    final Pattern negativePattern = Texts.compileRegex(negativeRegex);
    hasMoreFiles[0] = false;
    try {
        dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                if (mMapInterruption.get(taskId))
                    throw new CancellationException();
                final boolean isFile = pathname.isFile();
                final String name = pathname.getName();
                /*
                     * Filters...
                     */
                if (filterMode == BaseFile.FILTER_DIRECTORIES_ONLY && isFile)
                    return false;
                if (!showHiddenFiles && name.startsWith("."))
                    return false;
                if (isFile && positivePattern != null && !positivePattern.matcher(name).find())
                    return false;
                if (isFile && negativePattern != null && negativePattern.matcher(name).find())
                    return false;
                /*
                     * Limit...
                     */
                if (results.size() >= limit) {
                    hasMoreFiles[0] = true;
                    throw new CancellationException("Exceeding limit...");
                }
                results.add(pathname);
                return false;
            }
        });
    } catch (CancellationException e) {
        if (Utils.doLog())
            Log.d(CLASSNAME, "listFiles() >> cancelled... >> " + e);
    }
}
Also used : Pattern(java.util.regex.Pattern) CancellationException(java.util.concurrent.CancellationException) FileFilter(java.io.FileFilter) File(java.io.File) BaseFile(group.pals.android.lib.ui.filechooser.providers.basefile.BaseFileContract.BaseFile)

Example 85 with CancellationException

use of java.util.concurrent.CancellationException in project energy3d by concord-consortium.

the class SolarRadiation method computeOnMirror.

// unlike PV solar panels, no indirect (ambient or diffuse) radiation should be included in reflection calculation
private void computeOnMirror(final int minute, final ReadOnlyVector3 directionTowardSun, final Mirror mirror) {
    final int nx = Scene.getInstance().getMirrorNx();
    final int ny = Scene.getInstance().getMirrorNy();
    final Foundation target = mirror.getReceiver();
    if (target != null) {
        final Calendar calendar = Heliodon.getInstance().getCalendar();
        calendar.set(Calendar.HOUR_OF_DAY, (int) ((double) minute / (double) SolarRadiation.MINUTES_OF_DAY * 24.0));
        calendar.set(Calendar.MINUTE, minute % 60);
        mirror.draw();
    }
    // nx*ny*60: nx*ny is to get the unit cell area of the nx*ny grid; 60 is to convert the unit of timeStep from minute to kWh
    final double a = mirror.getMirrorWidth() * mirror.getMirrorHeight() * Scene.getInstance().getTimeStep() / (nx * ny * 60.0);
    final ReadOnlyVector3 normal = mirror.getNormal();
    if (normal == null) {
        throw new RuntimeException("Normal is null");
    }
    final Mesh mesh = mirror.getRadiationMesh();
    MeshDataStore data = onMesh.get(mesh);
    if (data == null) {
        data = initMeshTextureDataOnRectangle(mesh, nx, ny);
    }
    final ReadOnlyVector3 offset = directionTowardSun.multiply(1, null);
    final double dot = normal.dot(directionTowardSun);
    double directRadiation = 0;
    if (dot > 0) {
        directRadiation += calculateDirectRadiation(directionTowardSun, normal);
    }
    final FloatBuffer vertexBuffer = mesh.getMeshData().getVertexBuffer();
    // (0, 0)
    final Vector3 p0 = new Vector3(vertexBuffer.get(3), vertexBuffer.get(4), vertexBuffer.get(5));
    // (1, 0)
    final Vector3 p1 = new Vector3(vertexBuffer.get(6), vertexBuffer.get(7), vertexBuffer.get(8));
    // (0, 1)
    final Vector3 p2 = new Vector3(vertexBuffer.get(0), vertexBuffer.get(1), vertexBuffer.get(2));
    // final Vector3 q0 = drawMesh.localToWorld(p0, null);
    // final Vector3 q1 = drawMesh.localToWorld(p1, null);
    // final Vector3 q2 = drawMesh.localToWorld(p2, null);
    // System.out.println("***" + q0.distance(q1) * Scene.getInstance().getAnnotationScale() + "," + q0.distance(q2) * Scene.getInstance().getAnnotationScale());
    // this is the longer side (supposed to be y)
    final Vector3 u = p1.subtract(p0, null).normalizeLocal();
    // this is the shorter side (supposed to be x)
    final Vector3 v = p2.subtract(p0, null).normalizeLocal();
    // x and y must be swapped to have correct heat map texture, because nx represents rows and ny columns as we call initMeshTextureDataOnRectangle(mesh, nx, ny)
    final double xSpacing = p1.distance(p0) / nx;
    final double ySpacing = p2.distance(p0) / ny;
    final Vector3 receiver = target != null ? target.getSolarReceiverCenter() : null;
    List<Mesh> towerCollisionMeshes = null;
    if (target != null) {
        towerCollisionMeshes = new ArrayList<Mesh>();
        for (final HousePart child : target.getChildren()) {
            towerCollisionMeshes.add((Mesh) child.getRadiationCollisionSpatial());
        }
        final List<Roof> roofs = target.getRoofs();
        if (!roofs.isEmpty()) {
            for (final Roof r : roofs) {
                for (final Spatial roofPart : r.getRoofPartsRoot().getChildren()) {
                    towerCollisionMeshes.add((Mesh) ((Node) roofPart).getChild(6));
                }
            }
        }
    }
    final int iMinute = minute / Scene.getInstance().getTimeStep();
    final boolean reflectionMapOnly = Scene.getInstance().getOnlyReflectedEnergyInMirrorSolarMap();
    for (int x = 0; x < nx; x++) {
        for (int y = 0; y < ny; y++) {
            if (EnergyPanel.getInstance().isCancelled()) {
                throw new CancellationException();
            }
            final Vector3 u2 = u.multiply(xSpacing * (x + 0.5), null);
            final Vector3 v2 = v.multiply(ySpacing * (y + 0.5), null);
            final ReadOnlyVector3 p = mesh.getWorldTransform().applyForward(p0.add(v2, null).addLocal(u2)).addLocal(offset);
            final Ray3 pickRay = new Ray3(p, directionTowardSun);
            if (dot > 0) {
                final PickResults pickResults = new PrimitivePickResults();
                for (final Spatial spatial : collidables) {
                    if (spatial != mesh) {
                        PickingUtil.findPick(spatial, pickRay, pickResults, false);
                        if (pickResults.getNumber() != 0) {
                            break;
                        }
                    }
                }
                if (pickResults.getNumber() == 0) {
                    // for heat map generation
                    if (!reflectionMapOnly) {
                        data.dailySolarIntensity[x][y] += directRadiation;
                    }
                    if (receiver != null) {
                        // for concentrated energy calculation
                        final Vector3 toReceiver = receiver.subtract(p, null);
                        final Ray3 rayToReceiver = new Ray3(p, toReceiver.normalize(null));
                        final PickResults pickResultsToReceiver = new PrimitivePickResults();
                        for (final Spatial spatial : collidables) {
                            if (spatial != mesh) {
                                if (towerCollisionMeshes == null || (towerCollisionMeshes != null && !towerCollisionMeshes.contains(spatial))) {
                                    PickingUtil.findPick(spatial, rayToReceiver, pickResultsToReceiver, false);
                                    if (pickResultsToReceiver.getNumber() != 0) {
                                        break;
                                    }
                                }
                            }
                        }
                        if (pickResultsToReceiver.getNumber() == 0) {
                            final double r = directRadiation * Atmosphere.getTransmittance(toReceiver.length() * Scene.getInstance().getAnnotationScale() * 0.001, false);
                            mirror.getSolarPotential()[iMinute] += r * a;
                            if (reflectionMapOnly) {
                                data.dailySolarIntensity[x][y] += r;
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Calendar(java.util.Calendar) Node(com.ardor3d.scenegraph.Node) Mesh(com.ardor3d.scenegraph.Mesh) FloatBuffer(java.nio.FloatBuffer) ReadOnlyVector3(com.ardor3d.math.type.ReadOnlyVector3) Vector3(com.ardor3d.math.Vector3) CullHint(com.ardor3d.scenegraph.hint.CullHint) TPoint(org.poly2tri.triangulation.point.TPoint) Point(org.poly2tri.geometry.primitives.Point) Ray3(com.ardor3d.math.Ray3) PrimitivePickResults(com.ardor3d.intersection.PrimitivePickResults) ReadOnlyVector3(com.ardor3d.math.type.ReadOnlyVector3) Roof(org.concord.energy3d.model.Roof) Spatial(com.ardor3d.scenegraph.Spatial) CancellationException(java.util.concurrent.CancellationException) Foundation(org.concord.energy3d.model.Foundation) PrimitivePickResults(com.ardor3d.intersection.PrimitivePickResults) PickResults(com.ardor3d.intersection.PickResults) HousePart(org.concord.energy3d.model.HousePart)

Aggregations

CancellationException (java.util.concurrent.CancellationException)505 ExecutionException (java.util.concurrent.ExecutionException)150 Test (org.junit.Test)91 TimeoutException (java.util.concurrent.TimeoutException)76 ArrayList (java.util.ArrayList)47 CountDownLatch (java.util.concurrent.CountDownLatch)46 Future (java.util.concurrent.Future)46 IOException (java.io.IOException)42 ExecutorService (java.util.concurrent.ExecutorService)30 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)29 CompletableFuture (java.util.concurrent.CompletableFuture)28 Callable (java.util.concurrent.Callable)27 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)27 List (java.util.List)24 Map (java.util.Map)23 HashMap (java.util.HashMap)22 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)22 TimeUnit (java.util.concurrent.TimeUnit)20 CharStream (org.antlr.v4.runtime.CharStream)20 CommonTokenStream (org.antlr.v4.runtime.CommonTokenStream)20