Search in sources :

Example 86 with CancellationException

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

the class SolarRadiation method computeOnImportedMesh.

private void computeOnImportedMesh(final int minute, final ReadOnlyVector3 directionTowardSun, final Foundation foundation, final Mesh mesh) {
    final UserData userData = (UserData) mesh.getUserData();
    if (!userData.isReachable()) {
        return;
    }
    final ReadOnlyVector3 normal = userData.getRotatedNormal() == null ? userData.getNormal() : userData.getRotatedNormal();
    final MeshDataStore data = onMesh.get(mesh);
    final int timeStep = Scene.getInstance().getTimeStep();
    final int iMinute = minute / timeStep;
    final double dot = normal.dot(directionTowardSun);
    final double directRadiation = dot > 0 ? calculateDirectRadiation(directionTowardSun, normal) : 0;
    final double indirectRadiation = calculateDiffuseAndReflectedRadiation(directionTowardSun, normal);
    final double solarStep = Scene.getInstance().getSolarStep();
    final double annotationScale = Scene.getInstance().getAnnotationScale();
    final double scaleFactor = annotationScale * annotationScale / 60 * timeStep;
    final float absorption = 1 - foundation.getAlbedo();
    for (int col = 0; col < data.cols; col++) {
        // final double w = col == data.cols - 1 ? data.p2.distance(data.u.multiply(col * solarStep, null).addLocal(data.p0)) : solarStep;
        final double w = col == data.cols - 1 ? data.p2.distance(data.p0) - col * solarStep : solarStep;
        final ReadOnlyVector3 pU = data.u.multiply(col * solarStep + 0.5 * w, null).addLocal(data.p0);
        for (int row = 0; row < data.rows; row++) {
            if (EnergyPanel.getInstance().isCancelled()) {
                throw new CancellationException();
            }
            if (data.dailySolarIntensity[row][col] == -1) {
                continue;
            }
            final double h = row == data.rows - 1 ? data.p1.distance(data.p0) - row * solarStep : solarStep;
            // cannot do offset as in computeOnMesh
            final ReadOnlyVector3 p = data.v.multiply(row * solarStep + 0.5 * h, null).addLocal(pU);
            final Ray3 pickRay = new Ray3(p, directionTowardSun);
            final PickResults pickResults = new PrimitivePickResults();
            // assuming that indirect (ambient or diffuse) radiation can always reach a grid point
            double radiation = indirectRadiation;
            final double scaledArea = w * h * scaleFactor;
            if (dot > 0) {
                for (final Spatial spatial : collidables) {
                    if (EnergyPanel.getInstance().isCancelled()) {
                        throw new CancellationException();
                    }
                    if (spatial != mesh) {
                        PickingUtil.findPick(spatial, pickRay, pickResults, false);
                        if (pickResults.getNumber() != 0) {
                            break;
                        }
                    }
                }
                if (pickResults.getNumber() == 0) {
                    radiation += directRadiation;
                }
            }
            data.dailySolarIntensity[row][col] += Scene.getInstance().getOnlyAbsorptionInSolarMap() ? absorption * radiation : radiation;
            if (data.solarPotential != null) {
                data.solarPotential[iMinute] += radiation * scaledArea;
            }
            // sum all the solar energy up over all meshes and store in the foundation's solar potential array
            foundation.getSolarPotential()[iMinute] += radiation * scaledArea;
        }
    }
}
Also used : PrimitivePickResults(com.ardor3d.intersection.PrimitivePickResults) ReadOnlyVector3(com.ardor3d.math.type.ReadOnlyVector3) UserData(org.concord.energy3d.model.UserData) CancellationException(java.util.concurrent.CancellationException) Spatial(com.ardor3d.scenegraph.Spatial) PrimitivePickResults(com.ardor3d.intersection.PrimitivePickResults) PickResults(com.ardor3d.intersection.PickResults) CullHint(com.ardor3d.scenegraph.hint.CullHint) TPoint(org.poly2tri.triangulation.point.TPoint) Point(org.poly2tri.geometry.primitives.Point) Ray3(com.ardor3d.math.Ray3)

Example 87 with CancellationException

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

the class SolarRadiation method computeOnFresnelReflector.

// unlike PV solar panels, no indirect (ambient or diffuse) radiation should be included in reflection calculation
private void computeOnFresnelReflector(final int minute, final ReadOnlyVector3 directionTowardSun, final FresnelReflector reflector) {
    final int nx = reflector.getNSectionLength();
    final int ny = reflector.getNSectionWidth();
    final Foundation target = reflector.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);
        reflector.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 = reflector.getModuleWidth() * reflector.getLength() * Scene.getInstance().getTimeStep() / (nx * ny * 60.0);
    final ReadOnlyVector3 normal = reflector.getNormal();
    if (normal == null) {
        throw new RuntimeException("Normal is null");
    }
    final Mesh mesh = reflector.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 = mesh.localToWorld(p0, null);
    // final Vector3 q1 = mesh.localToWorld(p1, null);
    // final Vector3 q2 = mesh.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 absorber = target != null ? target.getSolarReceiverCenter() : null;
    List<Mesh> absorberCollisionMeshes = null;
    if (target != null) {
        absorberCollisionMeshes = new ArrayList<Mesh>();
        for (final HousePart child : target.getChildren()) {
            absorberCollisionMeshes.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()) {
                    absorberCollisionMeshes.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;
                    }
                    // TODO: Edge losses are not considered yet
                    if (absorber != null) {
                        // TODO: This calculation is not exactly accurate as the collision detection assumes that the ray emits from a grid point on the reflector to
                        // the parallel position on the absorber tube -- without considering the actual direction of the reflected light
                        final Vector3 toAbsorber = absorber.subtract(p, null);
                        toAbsorber.setY(0);
                        final Ray3 rayToAbsorber = new Ray3(p, toAbsorber.normalize(null));
                        final PickResults pickResultsToAbsorber = new PrimitivePickResults();
                        for (final Spatial spatial : collidables) {
                            if (spatial != mesh) {
                                if (absorberCollisionMeshes == null || (absorberCollisionMeshes != null && !absorberCollisionMeshes.contains(spatial))) {
                                    PickingUtil.findPick(spatial, rayToAbsorber, pickResultsToAbsorber, false);
                                    if (pickResultsToAbsorber.getNumber() != 0) {
                                        // FIXME: how to stop the ray when it hits the absorber?
                                        break;
                                    }
                                }
                            }
                        }
                        if (pickResultsToAbsorber.getNumber() == 0) {
                            final double r = directRadiation * Atmosphere.getTransmittance(toAbsorber.length() * Scene.getInstance().getAnnotationScale() * 0.001, false);
                            reflector.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)

Example 88 with CancellationException

use of java.util.concurrent.CancellationException in project incubator-pulsar by apache.

the class RawReaderTest method testReadCancellationOnClose.

@Test
public void testReadCancellationOnClose() throws Exception {
    int numKeys = 10;
    String topic = "persistent://my-property/use/my-ns/my-raw-topic";
    publishMessages(topic, numKeys / 2);
    RawReader reader = RawReader.create(pulsarClient, topic, subscription).get();
    List<Future<RawMessage>> futures = new ArrayList<>();
    for (int i = 0; i < numKeys; i++) {
        futures.add(reader.readNextAsync());
    }
    for (int i = 0; i < numKeys / 2; i++) {
        // complete successfully
        futures.remove(0).get();
    }
    reader.closeAsync().get();
    while (!futures.isEmpty()) {
        try {
            futures.remove(0).get();
            Assert.fail("Should have been cancelled");
        } catch (CancellationException ee) {
        // correct behaviour
        }
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) RawReader(org.apache.pulsar.client.api.RawReader) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) Test(org.testng.annotations.Test) MockedPulsarServiceBaseTest(org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest)

Example 89 with CancellationException

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

the class IndexEndpoint method recreateIndexFromService.

@POST
@Path("recreateIndex/{service}")
@RestQuery(name = "recreateIndexFromService", description = "Repopulates the Admin UI Index from an specific service", returnDescription = "OK if repopulation has started", pathParameters = { @RestParameter(name = "service", isRequired = true, description = "The service to recreate index from. " + "The available services are: Groups, Acl, Themes, Series, Scheduler, Workflow, AssetManager and Comments. " + "The service order (see above) is very important! Make sure, you do not run index rebuild for more than one " + "service at a time!", type = RestParameter.Type.STRING) }, reponses = { @RestResponse(description = "OK if repopulation has started", responseCode = HttpServletResponse.SC_OK) })
public Response recreateIndexFromService(@PathParam("service") final String service) {
    final SecurityContext securityContext = new SecurityContext(securityService, securityService.getOrganization(), securityService.getUser());
    executor.execute(new Runnable() {

        @Override
        public void run() {
            securityContext.runInContext(new Effect0() {

                @Override
                protected void run() {
                    try {
                        logger.info("Starting to repopulate the index from service {}", service);
                        adminUISearchIndex.recreateIndex(service);
                    } catch (InterruptedException e) {
                        logger.error("Repopulating the index was interrupted", e);
                    } catch (CancellationException e) {
                        logger.trace("Listening for index messages has been cancelled.");
                    } catch (ExecutionException e) {
                        logger.error("Repopulating the index failed to execute", e);
                    } catch (Throwable t) {
                        logger.error("Repopulating the index failed", t);
                    }
                }
            });
        }
    });
    return R.ok();
}
Also used : CancellationException(java.util.concurrent.CancellationException) Effect0(org.opencastproject.util.data.Effect0) SecurityContext(org.opencastproject.security.util.SecurityContext) ExecutionException(java.util.concurrent.ExecutionException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

Example 90 with CancellationException

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

the class BaseEndpoint method recreateIndex.

@POST
@Path("recreateIndex")
@RestQuery(name = "recreateIndex", description = "Repopulates the External Index directly from the Services", returnDescription = "OK if repopulation has started", reponses = { @RestResponse(description = "OK if repopulation has started", responseCode = HttpServletResponse.SC_OK) })
public Response recreateIndex() {
    final SecurityContext securityContext = new SecurityContext(securityService, securityService.getOrganization(), securityService.getUser());
    executor.execute(new Runnable() {

        @Override
        public void run() {
            securityContext.runInContext(new Effect0() {

                @Override
                protected void run() {
                    try {
                        logger.info("Starting to repopulate the external index");
                        externalIndex.recreateIndex();
                        logger.info("Finished repopulating the external index");
                    } catch (InterruptedException e) {
                        logger.error("Repopulating the external index was interrupted {}", getStackTrace(e));
                    } catch (CancellationException e) {
                        logger.trace("Listening for external index messages has been cancelled.");
                    } catch (ExecutionException e) {
                        logger.error("Repopulating the external index failed to execute because {}", getStackTrace(e));
                    } catch (Throwable t) {
                        logger.error("Repopulating the external index failed because {}", getStackTrace(t));
                    }
                }
            });
        }
    });
    return R.ok();
}
Also used : CancellationException(java.util.concurrent.CancellationException) Effect0(org.opencastproject.util.data.Effect0) SecurityContext(org.opencastproject.security.util.SecurityContext) ExecutionException(java.util.concurrent.ExecutionException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) RestQuery(org.opencastproject.util.doc.rest.RestQuery)

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