Example usage for java.util Queue iterator

List of usage examples for java.util Queue iterator

Introduction

In this page you can find the example usage for java.util Queue iterator.

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this collection.

Usage

From source file:test.jamocha.languages.clips.SystemTest.java

@Test
public void testSimpleNegatedTest() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    {//from   ww  w  .  j a v a2s .com
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(unwatch all)\n(watch facts)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate t1 (slot s1 (type INTEGER)))\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(defrule r1 (t1 (s1 ?x)) (not (test (> ?x 5))) => (assert (t1 (s1 999))) )\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t1 (s1 111)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-2>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-2\t(t1 (s1 111))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t1 (s1 1)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-3>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-3\t(t1 (s1 1))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-4\t(t1 (s1 999))", lines[0]);
        out.reset();
    }
}

From source file:test.jamocha.languages.clips.SystemTest.java

@Test
public void testEquivalenceClasses() throws ParseException {
    final Network network = new Network();
    final ByteArrayOutputStream out = initializeAppender(network);
    {/*w w w .j av  a  2  s  .c  om*/
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(unwatch all)\n(watch facts)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate t1 (slot s1 (type INTEGER)))\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(deftemplate t2 (slot s1 (type INTEGER)))\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network,
                "(defrule r1 (t1 (s1 ?x)) (t2 (s1 ?x)) => (assert (t1 (s1 999))) )\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t1 (s1 5)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-2>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-2\t(t1 (s1 5))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t2 (s1 9)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-3>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-3\t(t2 (s1 9))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        assertThat(out.toString(), isEmptyString());
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(assert (t2 (s1 5)))\n");
        final Queue<Object> values = returnValues.getLeft();
        assertThat(values, hasSize(1));
        final Object value = values.iterator().next();
        assertThat(value, instanceOf(String.class));
        assertEquals("<Fact-4>", value);
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-4\t(t2 (s1 5))", lines[0]);
        out.reset();
    }
    {
        final Pair<Queue<Object>, Queue<Warning>> returnValues = run(network, "(run)\n");
        assertThat(returnValues.getLeft(), empty());
        assertThat(returnValues.getRight(), empty());
        final String[] lines = out.toString().split(linesep);
        assertThat(lines, arrayWithSize(1));
        assertEquals("==> f-5\t(t1 (s1 999))", lines[0]);
        out.reset();
    }
}

From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java

/**
 * Used by batch import and export to wait for queued tasks to complete. Handles fail-fast behavior
 * if any of the tasks threw and exception by canceling all queued futures and logging a summary of
 * the failures. All completed futures are removed from the queue.
 *
 * @param futures Queued futures to check for completeness
 * @param wait If true it will wait for all futures to complete, if false only check for completed futures
 * @return a list of futures that either threw exceptions or timed out
 *//*from w  ww.j  a va  2s.co m*/
protected List<FutureHolder<?>> waitForFutures(final Queue<? extends FutureHolder<?>> futures,
        final PrintWriter reportWriter, final File reportDirectory, final boolean wait)
        throws InterruptedException {

    final List<FutureHolder<?>> failedFutures = new LinkedList<FutureHolder<?>>();

    for (Iterator<? extends FutureHolder<?>> futuresItr = futures.iterator(); futuresItr.hasNext();) {
        final FutureHolder<?> futureHolder = futuresItr.next();

        //If waiting, or if not waiting but the future is already done do the get
        final Future<?> future = futureHolder.getFuture();
        if (wait || (!wait && future.isDone())) {
            futuresItr.remove();

            try {
                //Don't bother doing a get() on canceled futures
                if (!future.isCancelled()) {
                    if (this.maxWait > 0) {
                        future.get(this.maxWait, this.maxWaitTimeUnit);
                    } else {
                        future.get();
                    }

                    reportWriter.printf(REPORT_FORMAT, "SUCCESS", futureHolder.getDescription(),
                            futureHolder.getExecutionTimeMillis());
                }
            } catch (CancellationException e) {
                //Ignore cancellation exceptions
            } catch (ExecutionException e) {
                logger.error("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                reportWriter.printf(REPORT_FORMAT, "FAIL", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());

                try {
                    final String dataReportName = SafeFilenameUtils.makeSafeFilename(
                            futureHolder.getDataType() + "_" + futureHolder.getDataName() + ".txt");
                    final File dataReportFile = new File(reportDirectory, dataReportName);
                    final PrintWriter dataReportWriter = new PrintWriter(
                            new BufferedWriter(new FileWriter(dataReportFile)));
                    try {
                        dataReportWriter.println(
                                "FAIL: " + futureHolder.getDataType() + " - " + futureHolder.getDataName());
                        dataReportWriter.println(
                                "--------------------------------------------------------------------------------");
                        e.getCause().printStackTrace(dataReportWriter);
                    } finally {
                        IOUtils.closeQuietly(dataReportWriter);
                    }
                } catch (Exception re) {
                    logger.warn("Failed to write error report for failed " + futureHolder
                            + ", logging root failure here", e.getCause());
                }
            } catch (TimeoutException e) {
                logger.warn("Failed: " + futureHolder);

                futureHolder.setError(e);
                failedFutures.add(futureHolder);
                future.cancel(true);
                reportWriter.printf(REPORT_FORMAT, "TIMEOUT", futureHolder.getDescription(),
                        futureHolder.getExecutionTimeMillis());
            }
        }
    }

    return failedFutures;
}

From source file:ibme.sleepap.recording.SignalsRecorder.java

private List<Number> doubleQueueToNumberList(Queue<Double> queue) {
    List<Number> list;
    // If the Queue is modified while the loop is running (which is more
    // than possible), a ConcurrentModificationException will be thrown.
    // If one is, it is caught and we try again.
    int attempts = 0;
    while (attempts < 5) {
        try {/* w w w. j  a  v  a 2  s.  c  o m*/
            list = new ArrayList<Number>();
            for (Iterator<Double> iter = queue.iterator(); iter.hasNext();) {
                Double obj = iter.next();
                list.add(obj);
            }
            return list;
        } catch (ConcurrentModificationException e) {
            // Don't return anything so we go through the while loop again.
            attempts++;
        }
    }
    list = new ArrayList<Number>();
    list.add(0);
    list.add(0);
    return list;
}

From source file:org.archive.crawler.frontier.WorkQueueFrontier.java

/** Compact report of all nonempty queues (one queue per line)
 * // w  ww.  j  a v  a 2  s.c om
 * @param writer
 */
public void allNonemptyReportTo(PrintWriter writer) {
    ArrayList<WorkQueue> inProcessQueuesCopy;
    synchronized (this.inProcessQueues) {
        // grab a copy that will be stable against mods for report duration 
        Collection<WorkQueue> inProcess = this.inProcessQueues;
        inProcessQueuesCopy = new ArrayList<WorkQueue>(inProcess);
    }
    writer.print("\n -----===== IN-PROCESS QUEUES =====-----\n");
    queueSingleLinesTo(writer, inProcessQueuesCopy.iterator());

    writer.print("\n -----===== READY QUEUES =====-----\n");
    queueSingleLinesTo(writer, this.readyClassQueues.iterator());

    writer.print("\n -----===== SNOOZED QUEUES =====-----\n");
    queueSingleLinesTo(writer, this.snoozedClassQueues.iterator());
    queueSingleLinesTo(writer, this.snoozedOverflow.values().iterator());

    writer.print("\n -----===== INACTIVE QUEUES =====-----\n");
    for (Queue<String> inactiveQueues : getInactiveQueuesByPrecedence().values()) {
        queueSingleLinesTo(writer, inactiveQueues.iterator());
    }

    writer.print("\n -----===== RETIRED QUEUES =====-----\n");
    queueSingleLinesTo(writer, getRetiredQueues().iterator());
}

From source file:org.archive.crawler.frontier.WorkQueueFrontier.java

/**
 * This method compiles a human readable report on the status of the frontier
 * at the time of the call.//from   w w w. j ava 2s.com
 * @param name Name of report.
 * @param writer Where to write to.
 */
@Override
public synchronized void reportTo(PrintWriter writer) {
    int allCount = allQueues.size();
    int inProcessCount = inProcessQueues.size();
    int readyCount = readyClassQueues.size();
    int snoozedCount = getSnoozedCount();
    int activeCount = inProcessCount + readyCount + snoozedCount;
    int inactiveCount = getTotalInactiveQueues();
    int retiredCount = getRetiredQueues().size();
    int exhaustedCount = allCount - activeCount - inactiveCount - retiredCount;

    writer.print("Frontier report - ");
    writer.print(ArchiveUtils.get12DigitDate());
    writer.print("\n");
    writer.print(" Job being crawled: ");
    writer.print(controller.getMetadata().getJobName());
    writer.print("\n");
    writer.print("\n -----===== STATS =====-----\n");
    writer.print(" Discovered:    ");
    writer.print(Long.toString(discoveredUriCount()));
    writer.print("\n");
    writer.print(" Queued:        ");
    writer.print(Long.toString(queuedUriCount()));
    writer.print("\n");
    writer.print(" Finished:      ");
    writer.print(Long.toString(finishedUriCount()));
    writer.print("\n");
    writer.print("  Successfully: ");
    writer.print(Long.toString(succeededFetchCount()));
    writer.print("\n");
    writer.print("  Failed:       ");
    writer.print(Long.toString(failedFetchCount()));
    writer.print("\n");
    writer.print("  Disregarded:  ");
    writer.print(Long.toString(disregardedUriCount()));
    writer.print("\n");
    writer.print("\n -----===== QUEUES =====-----\n");
    writer.print(" Already included size:     ");
    writer.print(Long.toString(uriUniqFilter.count()));
    writer.print("\n");
    writer.print("               pending:     ");
    writer.print(Long.toString(uriUniqFilter.pending()));
    writer.print("\n");
    writer.print("\n All class queues map size: ");
    writer.print(Long.toString(allCount));
    writer.print("\n");
    writer.print("             Active queues: ");
    writer.print(activeCount);
    writer.print("\n");
    writer.print("                    In-process: ");
    writer.print(inProcessCount);
    writer.print("\n");
    writer.print("                         Ready: ");
    writer.print(readyCount);
    writer.print("\n");
    writer.print("                       Snoozed: ");
    writer.print(snoozedCount);
    writer.print("\n");
    writer.print("           Inactive queues: ");
    writer.print(inactiveCount);
    writer.print(" (");
    Map<Integer, Queue<String>> inactives = getInactiveQueuesByPrecedence();
    boolean betwixt = false;
    for (Integer k : inactives.keySet()) {
        if (betwixt) {
            writer.print("; ");
        }
        writer.print("p");
        writer.print(k);
        writer.print(": ");
        writer.print(inactives.get(k).size());
        betwixt = true;
    }
    writer.print(")\n");
    writer.print("            Retired queues: ");
    writer.print(retiredCount);
    writer.print("\n");
    writer.print("          Exhausted queues: ");
    writer.print(exhaustedCount);
    writer.print("\n");

    State last = lastReachedState;
    writer.print("\n             Last state: " + last);

    writer.print("\n -----===== MANAGER THREAD =====-----\n");
    ToeThread.reportThread(managerThread, writer);

    writer.print("\n -----===== " + largestQueues.size() + " LONGEST QUEUES =====-----\n");
    appendQueueReports(writer, "LONGEST", largestQueues.getEntriesDescending().iterator(), largestQueues.size(),
            largestQueues.size());

    writer.print("\n -----===== IN-PROCESS QUEUES =====-----\n");
    Collection<WorkQueue> inProcess = inProcessQueues;
    ArrayList<WorkQueue> copy = extractSome(inProcess, maxQueuesPerReportCategory);
    appendQueueReports(writer, "IN-PROCESS", copy.iterator(), copy.size(), maxQueuesPerReportCategory);

    writer.print("\n -----===== READY QUEUES =====-----\n");
    appendQueueReports(writer, "READY", this.readyClassQueues.iterator(), this.readyClassQueues.size(),
            maxQueuesPerReportCategory);

    writer.print("\n -----===== SNOOZED QUEUES =====-----\n");
    Object[] objs = snoozedClassQueues.toArray();
    DelayedWorkQueue[] qs = Arrays.copyOf(objs, objs.length, DelayedWorkQueue[].class);
    Arrays.sort(qs);
    appendQueueReports(writer, "SNOOZED", new ObjectArrayIterator(qs), getSnoozedCount(),
            maxQueuesPerReportCategory);

    writer.print("\n -----===== INACTIVE QUEUES =====-----\n");
    SortedMap<Integer, Queue<String>> sortedInactives = getInactiveQueuesByPrecedence();
    for (Integer prec : sortedInactives.keySet()) {
        Queue<String> inactiveQueues = sortedInactives.get(prec);
        appendQueueReports(writer, "INACTIVE-p" + prec, inactiveQueues.iterator(), inactiveQueues.size(),
                maxQueuesPerReportCategory);
    }

    writer.print("\n -----===== RETIRED QUEUES =====-----\n");
    appendQueueReports(writer, "RETIRED", getRetiredQueues().iterator(), getRetiredQueues().size(),
            maxQueuesPerReportCategory);

    writer.flush();
}

From source file:it.geosolutions.geobatch.postgres.shp2pg.Shp2pgAction.java

/**
 * Removes TemplateModelEvents from the queue and put
 *///from   w  w  w  . j av a 2s .c o m
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {
    listenerForwarder.setTask("config");
    listenerForwarder.started();
    if (configuration == null) {
        throw new IllegalStateException("ActionConfig is null.");
    }
    File workingDir = Path.findLocation(configuration.getWorkingDirectory(),
            ((FileBaseCatalog) CatalogHolder.getCatalog()).getConfigDirectory());
    if (workingDir == null) {
        throw new IllegalStateException("Working directory is null.");
    }
    if (!workingDir.exists() || !workingDir.isDirectory()) {
        throw new IllegalStateException((new StringBuilder()).append("Working directory does not exist (")
                .append(workingDir.getAbsolutePath()).append(").").toString());
    }
    FileSystemEvent event = (FileSystemEvent) events.peek();
    // String shapeName = null;
    File shapefile = null;
    File zippedFile = null;
    File files[];
    if (events.size() == 1) {
        zippedFile = event.getSource();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace((new StringBuilder()).append("Testing for compressed file: ")
                    .append(zippedFile.getAbsolutePath()).toString());
        }
        String tmpDirName = null;
        try {
            tmpDirName = Extract.extract(zippedFile.getAbsolutePath());
        } catch (Exception e) {
            final String message = "Shp2pgAction.execute(): Unable to read zip file: "
                    + e.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
        listenerForwarder.progressing(5F, "File extracted");
        File tmpDirFile = new File(tmpDirName);
        if (!tmpDirFile.isDirectory()) {
            throw new IllegalStateException("Not valid input: we need a zip file ");
        }
        Collector c = new Collector(null);
        List fileList = c.collect(tmpDirFile);
        if (fileList != null) {
            files = (File[]) fileList.toArray(new File[1]);
        } else {
            String message = "Input is not a zipped file nor a valid collection of files";
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(message);
            }
            throw new IllegalStateException(message);
        }
    } else if (events.size() >= 3) {
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Checking input collection...");
        }
        listenerForwarder.progressing(6F, "Checking input collection...");
        files = new File[events.size()];
        int i = 0;
        for (Iterator i$ = events.iterator(); i$.hasNext();) {
            FileSystemEvent ev = (FileSystemEvent) i$.next();
            files[i++] = ev.getSource();
        }

    } else {
        throw new IllegalStateException("Input is not a zipped file nor a valid collection of files");
    }
    if ((shapefile = acceptable(files)) == null) {
        throw new IllegalStateException("The file list do not contains mondadory files");
    }

    listenerForwarder.progressing(10F, "In progress");

    // At this moment i have the shape and a file list

    // connect to the shapefile
    final Map<String, Serializable> connect = new HashMap<String, Serializable>();
    connect.put("url", DataUtilities.fileToURL(shapefile));

    DataStore sourceDataStore = null;
    String typeName = null;
    SimpleFeatureType originalSchema = null;
    try {
        sourceDataStore = SHP_FACTORY.createDataStore(connect);
        String[] typeNames = sourceDataStore.getTypeNames();
        typeName = typeNames[0];

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Reading content " + typeName);
        }

        originalSchema = sourceDataStore.getSchema(typeName);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("SCHEMA HEADER: " + DataUtilities.spec(originalSchema));
        }
    } catch (IOException e) {
        final String message = "Error to create PostGres datastore" + e.getLocalizedMessage();
        if (LOGGER.isErrorEnabled())
            LOGGER.error(message);
        if (sourceDataStore != null)
            sourceDataStore.dispose();
        throw new ActionException(this, message);
    }
    // prepare to open up a reader for the shapefile
    Query query = new Query();
    query.setTypeName(typeName);
    CoordinateReferenceSystem prj = originalSchema.getCoordinateReferenceSystem();
    query.setCoordinateSystem(prj);

    DataStore destinationDataSource = null;
    try {
        destinationDataSource = createPostgisDataStore(configuration);

        // check if the schema is present in postgis
        boolean schema = false;
        if (destinationDataSource.getTypeNames().length != 0) {
            for (String tableName : destinationDataSource.getTypeNames()) {
                if (tableName.equalsIgnoreCase(typeName)) {
                    schema = true;
                }
            }
        } else {
            schema = false;
        }
        if (!schema)
            destinationDataSource.createSchema(originalSchema);
        LOGGER.info("SCHEMA: " + schema);

    } catch (IOException e) {
        String message = "Error to create postGis datastore";
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(message);
        }
        if (destinationDataSource != null)
            destinationDataSource.dispose();
        throw new IllegalStateException(message);
    }

    final Transaction transaction = new DefaultTransaction("create");
    FeatureWriter<SimpleFeatureType, SimpleFeature> fw = null;
    FeatureReader<SimpleFeatureType, SimpleFeature> fr = null;
    try {
        SimpleFeatureBuilder builder = new SimpleFeatureBuilder(destinationDataSource.getSchema(typeName));
        fw = destinationDataSource.getFeatureWriter(typeName, transaction);
        fr = sourceDataStore.getFeatureReader(query, transaction);
        SimpleFeatureType sourceSchema = sourceDataStore.getSchema(typeName);
        FeatureStore postgisStore = (FeatureStore) destinationDataSource.getFeatureSource(typeName);
        while (fr.hasNext()) {
            final SimpleFeature oldfeature = fr.next();

            for (AttributeDescriptor ad : sourceSchema.getAttributeDescriptors()) {
                String attribute = ad.getLocalName();
                builder.set(attribute, oldfeature.getAttribute(attribute));
            }
            postgisStore.addFeatures(DataUtilities.collection(builder.buildFeature(null)));

        }

        // close transaction
        transaction.commit();

    } catch (Throwable e) {
        try {
            transaction.rollback();
        } catch (IOException e1) {
            final String message = "Transaction rollback unsuccessful: " + e1.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
    } finally {
        try {
            transaction.close();
        } catch (IOException e) {
            final String message = "Transaction close unsuccessful: " + e.getLocalizedMessage();
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new ActionException(this, message);
        }
        if (fr != null) {
            try {
                fr.close();
            } catch (IOException e1) {
                final String message = "Feature reader IO exception: " + e1.getLocalizedMessage();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message);
                throw new ActionException(this, message);
            }
        }
        if (fw != null) {
            try {
                fw.close();
            } catch (IOException e1) {
                final String message = "Feature writer IO exception: " + e1.getLocalizedMessage();
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message);
                throw new ActionException(this, message);
            }
        }
        if (sourceDataStore != null) {
            try {
                sourceDataStore.dispose();
            } catch (Throwable t) {
            }
        }
        if (destinationDataSource != null) {
            try {
                destinationDataSource.dispose();
            } catch (Throwable t) {
            }
        }
    }

    GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(configuration.getGeoserverURL(),
            configuration.getGeoserverUID(), configuration.getGeoserverPWD());

    publisher.createWorkspace(configuration.getDefaultNamespace());

    GSPostGISDatastoreEncoder datastoreEncoder = new GSPostGISDatastoreEncoder();

    datastoreEncoder.setUser(configuration.getDbUID());
    datastoreEncoder.setDatabase(configuration.getDbName());
    datastoreEncoder.setPassword(configuration.getDbPWD());
    datastoreEncoder.setHost(configuration.getDbServerIp());
    datastoreEncoder.setPort(Integer.valueOf(configuration.getDbPort()));
    datastoreEncoder.setName(configuration.getDbName());

    publisher.createPostGISDatastore(configuration.getDefaultNamespace(), datastoreEncoder);
    String shapeFileName = FilenameUtils.getBaseName(shapefile.getName());

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Layer postgis publishing xml-> ");
        LOGGER.info("datastoreEncoder xml: " + datastoreEncoder.toString());
    }

    if (publisher.publishDBLayer(configuration.getDefaultNamespace(), configuration.getDbName(), shapeFileName,
            configuration.getCrs(), configuration.getDefaultStyle())) {
        String message = "PostGis layer SUCCESFULLY registered";
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info(message);
        }
        listenerForwarder.progressing(100F, message);
    } else {
        String message = "PostGis layer not registered";
        ActionException ae = new ActionException(this, message);
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(message, ae);
        }
        listenerForwarder.failed(ae);
    }
    events.clear();

    return events;
}

From source file:io.openvidu.test.e2e.OpenViduTestAppE2eTest.java

@Test
@DisplayName("Change publisher dynamically")
void changePublisherTest() throws Exception {

    Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>();

    setupBrowser("chrome");

    log.info("Change publisher dynamically");

    WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input"));
    oneToManyInput.clear();/*from   w w  w . j a v  a 2s  . c om*/
    oneToManyInput.sendKeys("1");

    user.getDriver().findElement(By.id("auto-join-checkbox")).click();

    final CountDownLatch latch1 = new CountDownLatch(2);

    // First publication (audio + video [CAMERA])
    user.getEventManager().on("streamPlaying", (event) -> {
        JsonObject stream = event.get("target").getAsJsonObject().get("stream").getAsJsonObject();
        threadAssertions.add("CAMERA".equals(stream.get("typeOfVideo").getAsString()));
        threadAssertions.add(stream.get("hasAudio").getAsBoolean());

        latch1.countDown();
    });
    user.getDriver().findElement(By.id("one2many-btn")).click();

    user.getEventManager().waitUntilEventReaches("connectionCreated", 4);
    user.getEventManager().waitUntilEventReaches("accessAllowed", 1);
    user.getEventManager().waitUntilEventReaches("streamCreated", 2);
    user.getEventManager().waitUntilEventReaches("streamPlaying", 2);

    if (!latch1.await(5000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail("Waiting for 2 streamPlaying events to happen in total");
        return;
    }

    user.getEventManager().off("streamPlaying");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    int numberOfVideos = user.getDriver().findElements(By.tagName("video")).size();
    Assert.assertEquals("Expected 2 videos but found " + numberOfVideos, 2, numberOfVideos);
    Assert.assertTrue("Videos were expected to have audio and video tracks", user.getEventManager()
            .assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true));

    final CountDownLatch latch2 = new CountDownLatch(2);

    // Second publication (only video (SCREEN))
    user.getEventManager().on("streamPlaying", (event) -> {
        JsonObject stream = event.get("target").getAsJsonObject().get("stream").getAsJsonObject();
        threadAssertions.add("SCREEN".equals(stream.get("typeOfVideo").getAsString()));
        threadAssertions.add(!stream.get("hasAudio").getAsBoolean());
        latch2.countDown();
    });
    user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click();

    user.getEventManager().waitUntilEventReaches("streamDestroyed", 2);
    user.getEventManager().waitUntilEventReaches("accessAllowed", 2);
    user.getEventManager().waitUntilEventReaches("streamCreated", 4);
    user.getEventManager().waitUntilEventReaches("streamPlaying", 4);

    if (!latch2.await(5000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail("Waiting for 4 streamPlaying events to happen in total");
        return;
    }

    user.getEventManager().off("streamPlaying");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    numberOfVideos = user.getDriver().findElements(By.tagName("video")).size();
    Assert.assertEquals("Expected 2 videos but found " + numberOfVideos, 2, numberOfVideos);
    Assert.assertTrue("Videos were expected to only have audio tracks", user.getEventManager()
            .assertMediaTracks(user.getDriver().findElements(By.tagName("video")), false, true));

    final CountDownLatch latch3 = new CountDownLatch(2);

    // Third publication (audio + video [CAMERA])
    user.getEventManager().on("streamPlaying", (event) -> {
        JsonObject stream = event.get("target").getAsJsonObject().get("stream").getAsJsonObject();
        threadAssertions.add("CAMERA".equals(stream.get("typeOfVideo").getAsString()));
        threadAssertions.add(stream.get("hasAudio").getAsBoolean());
        latch3.countDown();
    });
    user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .change-publisher-btn")).click();
    user.getEventManager().waitUntilEventReaches("streamDestroyed", 4);
    user.getEventManager().waitUntilEventReaches("accessAllowed", 3);
    user.getEventManager().waitUntilEventReaches("streamCreated", 6);
    user.getEventManager().waitUntilEventReaches("streamPlaying", 6);

    if (!latch3.await(8000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail("Waiting for 6 streamPlaying events to happen in total");
        return;
    }

    user.getEventManager().off("streamPlaying");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    numberOfVideos = user.getDriver().findElements(By.tagName("video")).size();
    Assert.assertEquals("Expected 2 videos but found " + numberOfVideos, 2, numberOfVideos);
    Assert.assertTrue("Videos were expected to have audio and video tracks", user.getEventManager()
            .assertMediaTracks(user.getDriver().findElements(By.tagName("video")), true, true));

    gracefullyLeaveParticipants(2);
}

From source file:io.openvidu.test.e2e.OpenViduTestAppE2eTest.java

@Test
@DisplayName("Stream property changed event")
void streamPropertyChangedEventTest() throws Exception {

    Queue<Boolean> threadAssertions = new ConcurrentLinkedQueue<Boolean>();

    setupBrowser("chromeAlternateScreenShare");

    log.info("Stream property changed event");

    WebElement oneToManyInput = user.getDriver().findElement(By.id("one2many-input"));
    oneToManyInput.clear();//  w w  w  .  j  av  a 2  s  . c  o  m
    oneToManyInput.sendKeys("1");

    user.getDriver().findElement(By.id("one2many-btn")).click();
    user.getDriver().findElement(By.className("screen-radio")).click();

    List<WebElement> joinButtons = user.getDriver().findElements(By.className("join-btn"));
    for (WebElement el : joinButtons) {
        el.sendKeys(Keys.ENTER);
    }

    user.getEventManager().waitUntilEventReaches("connectionCreated", 4);
    user.getEventManager().waitUntilEventReaches("accessAllowed", 1);
    user.getEventManager().waitUntilEventReaches("streamCreated", 2);
    user.getEventManager().waitUntilEventReaches("streamPlaying", 2);

    // Unpublish video
    final CountDownLatch latch1 = new CountDownLatch(2);
    user.getEventManager().on("streamPropertyChanged", (event) -> {
        threadAssertions.add("videoActive".equals(event.get("changedProperty").getAsString()));
        threadAssertions.add(!event.get("newValue").getAsBoolean());
        latch1.countDown();
    });
    user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-video-btn")).click();
    user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 2);

    if (!latch1.await(5000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail();
        return;
    }

    user.getEventManager().off("streamPropertyChanged");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    // Unpublish audio
    final CountDownLatch latch2 = new CountDownLatch(2);
    user.getEventManager().on("streamPropertyChanged", (event) -> {
        threadAssertions.add("audioActive".equals(event.get("changedProperty").getAsString()));
        threadAssertions.add(!event.get("newValue").getAsBoolean());
        latch2.countDown();
    });
    user.getDriver().findElement(By.cssSelector("#openvidu-instance-0 .pub-audio-btn")).click();
    user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 4);

    if (!latch2.await(5000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail();
        return;
    }

    user.getEventManager().off("streamPropertyChanged");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    // Resize captured window
    final CountDownLatch latch3 = new CountDownLatch(2);
    int newWidth = 1000;
    int newHeight = 700;

    final long[] expectedWidthHeight = new long[2];

    user.getEventManager().on("streamPropertyChanged", (event) -> {
        String expectedDimensions = "{\"width\":" + expectedWidthHeight[0] + ",\"height\":"
                + expectedWidthHeight[1] + "}";
        threadAssertions.add("videoDimensions".equals(event.get("changedProperty").getAsString()));
        threadAssertions.add(expectedDimensions.equals(event.get("newValue").getAsJsonObject().toString()));
        latch3.countDown();
    });

    user.getDriver().manage().window().setSize(new Dimension(newWidth, newHeight));

    String widthAndHeight = user.getEventManager().getDimensionOfViewport();
    JSONObject obj = (JSONObject) new JSONParser().parse(widthAndHeight);

    expectedWidthHeight[0] = (long) obj.get("width");
    expectedWidthHeight[1] = (long) obj.get("height");

    System.out.println("New viewport dimension: " + obj.toJSONString());

    user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6);

    if (!latch3.await(5000, TimeUnit.MILLISECONDS)) {
        gracefullyLeaveParticipants(2);
        fail();
        return;
    }

    user.getEventManager().off("streamPropertyChanged");
    log.info("Thread assertions: {}", threadAssertions.toString());
    for (Iterator<Boolean> iter = threadAssertions.iterator(); iter.hasNext();) {
        Assert.assertTrue("Some Event property was wrong", iter.next());
        iter.remove();
    }

    gracefullyLeaveParticipants(2);
}