Example usage for java.util SortedSet iterator

List of usage examples for java.util SortedSet iterator

Introduction

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

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:de.fischer.thotti.reportgen.diagram.ChartGenerator.java

public ChartMetaData generateAllVariantsChart(final String testId) {
    File chartFile;/*w  w w .java2 s .  c om*/
    try {
        final List<TestVariant> variants = persistenceHelper.findAllVariants(testId);
        final TimeSeriesCollection collection = new TimeSeriesCollection();

        String svgFilename = String.format("%s.svg", testId);

        chartFile = new File(baseDir, svgFilename);

        for (TestVariant variant : variants) {
            TimeSeries series = new TimeSeries(String.format("Average of %s", variant.getCombinedId()),
                    Day.class);
            TimeSeries mediaSeries = new TimeSeries("Median of " + variant, Day.class);

            List<NDResultEntity> results = persistenceHelper.findAllResultsForVariant(variant);

            SortedSet<NDResultEntity> sortedSet = new TreeSet<NDResultEntity>(
                    new TestVariantModel.DateComparator());

            sortedSet.addAll(results);

            Calendar now = Calendar.getInstance();

            now.add(Calendar.DATE, 1);

            Iterator<Measurement> itr = new AverageDayCombinerIterator(sortedSet.iterator());
            Iterator<DatePoint> medianItr = new MedianIterator(sortedSet.iterator());

            while (itr.hasNext()) {
                Measurement singleResult = itr.next();

                Date startDate = singleResult.getPointInTime();

                double timeInMS = singleResult.getDuration();
                double timeInSecs = convertMilliSecsToSeconds(timeInMS);

                series.add(new Day(startDate), timeInSecs);
            }

            while (medianItr.hasNext()) {
                DatePoint singleResult = medianItr.next();

                Day day = new Day(singleResult.getPointInTime());
                double value = convertMilliSecsToSeconds(singleResult.getValue());

                mediaSeries.add(day, value);
            }

            collection.addSeries(series);
            collection.addSeries(mediaSeries);
        }

        final JFreeChart chart = createChart(testId, collection);

        saveChartAsSVG(chart, svgFilename);

        System.out.println(String.format("Written %s", chartFile.toString()));

        return new ChartMetaData().withFilename(chartFile.getName()).withWidth(DEFAULT_CHAR_WIDTH)
                .withHeight(DEFAULT_CHAR_HEIGHT).withFormat("SVG");

    } catch (Exception ioe) {
        // @todo Throw an better exception!
        ioe.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }

    return null;
}

From source file:au.edu.uq.cmm.paul.grabber.Analyser.java

private void determineFolderRange(SortedSet<DatasetMetadata> inFolder) {
    if (inFolder.isEmpty()) {
        fStart = null;// w  w w.  jav  a 2s . c  o  m
        fEnd = null;
    } else {
        Iterator<DatasetMetadata> it = inFolder.iterator();
        DatasetMetadata ds = it.next();
        fStart = fEnd = ds.getLastFileTimestamp();
        while (it.hasNext()) {
            ds = it.next();
            Date ts = ds.getLastFileTimestamp();
            if (ts.getTime() < fStart.getTime()) {
                fStart = ts;
            } else if (ts.getTime() > fEnd.getTime()) {
                fEnd = ts;
            }
        }
    }
}

From source file:com.espertech.esper.filter.TestStringRangeComparator.java

public void testComparator() {
    SortedSet<StringRange> sorted = new TreeSet<StringRange>(new StringRangeComparator());

    final String[][] TEST_SET = { { "B", "G" }, { "B", "F" }, { null, "E" }, { "A", "F" }, { "A", "G" }, };

    final int[] EXPECTED_INDEX = { 2, 3, 4, 1, 0 };

    // Sort//  w  w w.  j  a v a  2s  .co  m
    StringRange ranges[] = new StringRange[TEST_SET.length];
    for (int i = 0; i < TEST_SET.length; i++) {
        ranges[i] = new StringRange(TEST_SET[i][0], TEST_SET[i][1]);
        sorted.add(ranges[i]);
    }
    System.out.println("sorted=" + sorted);

    // Check results
    int count = 0;
    for (Iterator<StringRange> i = sorted.iterator(); i.hasNext();) {
        StringRange range = i.next();
        int indexExpected = EXPECTED_INDEX[count];
        StringRange expected = ranges[indexExpected];

        log.debug(".testComparator count=" + count + " range=" + range + " expected=" + expected);

        assertEquals("failed at count " + count, range, expected);
        count++;
    }
    assertEquals(count, TEST_SET.length);
}

From source file:org.bibsonomy.recommender.tags.meta.TagsFromFirstWeightedBySecondTagRecommender.java

protected double doFirstRound(final Collection<RecommendedTag> recommendedTags,
        final SortedSet<RecommendedTag> firstRecommendedTags,
        final MapBackedSet<String, RecommendedTag> secondRecommendedTags) {
    /* //from  ww w  .  ja va  2  s  .c o m
     * First round:
     * Iterate over tags from first recommender and check them against second recommender.
     * Add only those tags, which are contained in the second recommender
     */
    final Iterator<RecommendedTag> iterator1 = firstRecommendedTags.iterator();
    /*
     * We need to find the minimum to add the remaining tags with lower scores
     */
    double minScore = Double.MAX_VALUE;
    while (recommendedTags.size() < numberOfTagsToRecommend && iterator1.hasNext()) {
        final RecommendedTag recommendedTag = iterator1.next();
        if (secondRecommendedTags.contains(recommendedTag)) {
            /*
             * this tag is also recommended by the second recommender: give it his score
             */

            final RecommendedTag secondRecommendedTag = secondRecommendedTags.get(recommendedTag);
            recommendedTags.add(secondRecommendedTag);
            /*
             * remember minimal score
             */
            final double score = secondRecommendedTag.getScore();
            if (score < minScore)
                minScore = score;
            /*
             * remove tag, such that don't use it again in the second round
             */
            iterator1.remove();
        }
    }
    /*
     * We would like to have values not larger than 1.0 ... but basically
     * this prevents to have minScore = Double.MAX_VALUE, when no tags from
     * the first recommender were recommended by the second recommender.
     */
    if (minScore > 1.0)
        minScore = 1.0;
    return minScore;
}

From source file:com.splout.db.qnode.QNodeHandlerContext.java

/**
 * Rotates the versions (deletes versions that are old or useless). To be executed at startup and after a deployment.
 *///from  ww w  .j  a v  a2 s  . co  m
public List<com.splout.db.thrift.TablespaceVersion> synchronizeTablespaceVersions()
        throws InterruptedException {
    log.info("Starting to look for old tablespace versions to remove...");

    int maxVersionsPerTablespace = config.getInt(QNodeProperties.VERSIONS_PER_TABLESPACE);

    // Will contain the list of versions per each tablespace, sorted by creation date descendant
    TreeMultimap<String, Tablespace> tablespaces = TreeMultimap.create(Ordering.natural(),
            new Comparator<Tablespace>() {
                @Override
                public int compare(Tablespace tb1, Tablespace tb2) {
                    // reverse ordering. Older dates appears LAST. If same date, then version is compared.
                    int comp = -((Long) tb1.getCreationDate()).compareTo(tb2.getCreationDate());
                    if (comp == 0) {
                        return -((Long) tb1.getVersion()).compareTo(tb2.getVersion());
                    } else {
                        return comp;
                    }
                }
            });

    Map<TablespaceVersion, Tablespace> myTablespaces = getTablespaceVersionsMap();

    // We build a in memory version of tablespaces for analyzing it
    // and prune old ones.
    for (Entry<TablespaceVersion, Tablespace> entry : myTablespaces.entrySet()) {
        tablespaces.put(entry.getKey().getTablespace(), entry.getValue());
    }
    log.info("Analyzing " + tablespaces.keySet().size() + " tablespaces with a total of " + tablespaces.size()
            + " versions...");

    // We will remove only versions older than the one being served
    Map<String, Long> hzVersionsBeingServed = coordinationStructures.getCopyVersionsBeingServed();
    if (hzVersionsBeingServed == null) {
        log.info("... No versions yet being served.");
        return null; // nothing to do yet
    }
    log.info("Number of versions being served: " + hzVersionsBeingServed.size());

    List<com.splout.db.thrift.TablespaceVersion> tablespacesToRemove = new ArrayList<com.splout.db.thrift.TablespaceVersion>();

    for (Entry<String, Long> entry : hzVersionsBeingServed.entrySet()) {
        String tablespace = entry.getKey();
        Long versionBeingServed = entry.getValue();
        // Tablespaces are sorted by creation date desc.
        SortedSet<Tablespace> allVersions = tablespaces.get(tablespace);
        Iterator<Tablespace> it = allVersions.iterator();
        boolean foundVersionBeingServed = false;
        int countVersionsAfter = 0;
        while (it.hasNext()) {
            Tablespace tb = it.next();
            if (versionBeingServed.equals(tb.getVersion())) {
                foundVersionBeingServed = true;
            } else {
                if (foundVersionBeingServed) {
                    countVersionsAfter++;
                    if (countVersionsAfter >= maxVersionsPerTablespace) {
                        // This is the case where we remove the version
                        // 1 - This tablespace has a version being served
                        // 2 - This version is older than the current tablespace being served
                        // 3 - We are already keeping maxVersionsPerTablespace versions
                        tablespacesToRemove
                                .add(new com.splout.db.thrift.TablespaceVersion(tablespace, tb.getVersion()));
                        log.info("Tablespace [" + tablespace + "] Version [" + tb.getVersion() + "] "
                                + "created at [" + new Date(tb.getCreationDate())
                                + "] REMOVED. We already keep younger versions.");
                    } else {
                        log.info("Tablespace [" + tablespace + "] Version [" + tb.getVersion() + "] "
                                + "created at [" + new Date(tb.getCreationDate()) + "] KEPT.");
                    }
                } else {
                    log.info("Tablespace [" + tablespace + "] Version [" + tb.getVersion() + "] "
                            + "created at [" + new Date(tb.getCreationDate())
                            + "] either younger than served one or without version being served. Keeping.");
                }
            }
        }

        if (!foundVersionBeingServed) {
            log.info("Tablespace [" + tablespace
                    + "] without any version being served. Please, have a look, and remove them if not used");
        }

        if (tablespacesToRemove.size() > 0) {
            log.info("Sending [" + tablespacesToRemove + "] to all alive DNodes.");
            for (DNodeInfo dnode : coordinationStructures.getDNodes().values()) {
                DNodeService.Client client = null;
                boolean renew = false;
                try {
                    client = getDNodeClientFromPool(dnode.getAddress());
                    client.deleteOldVersions(tablespacesToRemove);
                } catch (TTransportException e) {
                    renew = true;
                    log.warn("Failed sending delete TablespaceVersions order to (" + dnode
                            + "). Not critical as they will be removed after other deployments.", e);
                } catch (Exception e) {
                    log.warn("Failed sending delete TablespaceVersions order to (" + dnode
                            + "). Not critical as they will be removed after other deployments.", e);
                } finally {
                    if (client != null) {
                        returnDNodeClientToPool(dnode.getAddress(), client, renew);
                    }
                }
            }
        }
        log.info("... done looking for old tablespace versions to remove...");
    }

    return tablespacesToRemove; // Return for unit test
}

From source file:org.terasoluna.gfw.common.codelist.ExistInCodeListTest.java

@Test
public void test_invalidMultipleExistInCodeList() {
    {//  w ww .  jav  a  2s .  c  o m
        Order order = new Order("1");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("2");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("4");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("5");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("7");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("8");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("9");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
    }
    {
        Order order = new Order("10");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(1));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        Order order = new Order("11");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
    {
        // out of range!
        Order order = new Order("18");
        Set<ConstraintViolation<Order>> result = validator.validate(order);
        assertThat(result.size(), is(2));
        SortedSet<String> messages = new TreeSet<String>();
        for (ConstraintViolation<Order> violation : result) {
            messages.add(violation.getMessage());
        }
        Iterator<String> iterator = messages.iterator();
        assertThat(iterator.next(), is("number must be even"));
        assertThat(iterator.next(), is("number must be multiples of 3"));
    }
}

From source file:org.geotools.coverage.io.netcdf.NetCDFPolyphemusTest.java

@Test
public void geoToolsReader() throws IllegalArgumentException, IOException, NoSuchAuthorityCodeException {
    boolean isInteractiveTest = TestData.isInteractiveTest();

    // create a base driver
    final DefaultFileDriver driver = new NetCDFDriver();
    final File[] files = TestData.file(this, ".").listFiles(new FileFilter() {

        @Override//from  w  ww . ja  v a2 s.  c  o  m
        public boolean accept(File pathname) {
            return FilenameUtils.getName(pathname.getAbsolutePath()).equalsIgnoreCase("O3-NO2.nc");
        }

    });

    for (File f : files) {

        // move to test directory
        final File file = new File(testDirectory, "O3-NO2.nc");
        FileUtils.copyFile(f, file);

        // get the file
        final URL source = file.toURI().toURL();
        assertTrue(driver.canProcess(DriverCapabilities.CONNECT, source, null));

        LOGGER.info("ACCEPTED: " + source.toString());

        // getting access to the file
        CoverageAccess access = null;

        try {
            access = driver.process(DriverCapabilities.CONNECT, source, null, null, null);
            if (access == null) {
                throw new IOException("Unable to connect");
            }
            // get the names
            final List<Name> names = access.getNames(null);
            for (Name name : names) {
                // get a source
                final CoverageSource gridSource = access.access(name, null, AccessType.READ_ONLY, null, null);
                if (gridSource == null) {
                    throw new IOException("Unable to access");
                }
                LOGGER.info("Connected to coverage: " + name.toString());

                // TEMPORAL DOMAIN
                final TemporalDomain temporalDomain = gridSource.getTemporalDomain();
                if (temporalDomain == null) {
                    LOGGER.info("Temporal domain is null");
                } else {
                    // temporal crs
                    LOGGER.info("TemporalCRS: " + temporalDomain.getCoordinateReferenceSystem());

                    // print the temporal domain elements
                    for (DateRange tg : temporalDomain.getTemporalElements(true, null)) {
                        LOGGER.info("Global Temporal Domain: " + tg.toString());
                    }

                    // print the temporal domain elements with overall = true
                    StringBuilder overallTemporal = new StringBuilder(
                            "Temporal domain element (overall = true):\n");
                    for (DateRange tg : temporalDomain.getTemporalElements(false, null)) {
                        overallTemporal.append(tg.toString()).append("\n");
                    }
                    LOGGER.info(overallTemporal.toString());
                }

                // VERTICAL DOMAIN
                final VerticalDomain verticalDomain = gridSource.getVerticalDomain();
                if (verticalDomain == null) {
                    LOGGER.info("Vertical domain is null");
                } else {
                    // vertical crs
                    LOGGER.info("VerticalCRS: " + verticalDomain.getCoordinateReferenceSystem());

                    // print the Vertical domain elements
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(true, null)) {
                        LOGGER.info("Vertical domain element: " + vg.toString());
                    }

                    // print the Vertical domain elements with overall = true
                    StringBuilder overallVertical = new StringBuilder(
                            "Vertical domain element (overall = true):\n");
                    for (NumberRange<Double> vg : verticalDomain.getVerticalElements(false, null)) {
                        overallVertical.append(vg.toString()).append("\n");
                    }
                    LOGGER.info(overallVertical.toString());
                }

                // HORIZONTAL DOMAIN
                final SpatialDomain spatialDomain = gridSource.getSpatialDomain();
                if (spatialDomain == null) {
                    LOGGER.info("Horizontal domain is null");
                } else {
                    // print the horizontal domain elements
                    final CoordinateReferenceSystem crs2D = spatialDomain.getCoordinateReferenceSystem2D();
                    assert crs2D != null;
                    final MathTransform2D g2w = spatialDomain.getGridToWorldTransform(null);
                    assert g2w != null;
                    final Set<? extends BoundingBox> spatialElements = spatialDomain.getSpatialElements(true,
                            null);
                    assert spatialElements != null && !spatialElements.isEmpty();

                    final StringBuilder buf = new StringBuilder();
                    buf.append("Horizontal domain is as follows:\n");
                    buf.append("G2W:").append("\t").append(g2w).append("\n");
                    buf.append("CRS2D:").append("\t").append(crs2D).append("\n");
                    for (BoundingBox bbox : spatialElements) {
                        buf.append("BBOX:").append("\t").append(bbox).append("\n");
                    }
                    LOGGER.info(buf.toString());
                }

                CoverageReadRequest readRequest = new CoverageReadRequest();
                // //
                //
                // Setting up a limited range for the request.
                //
                // //

                LinkedHashSet<NumberRange<Double>> requestedVerticalSubset = new LinkedHashSet<NumberRange<Double>>();
                SortedSet<? extends NumberRange<Double>> verticalElements = verticalDomain
                        .getVerticalElements(false, null);
                final int numLevels = verticalElements.size();
                final Iterator<? extends NumberRange<Double>> iterator = verticalElements.iterator();
                for (int i = 0; i < numLevels; i++) {
                    NumberRange<Double> level = iterator.next();
                    if (i % (numLevels / 5) == 1) {
                        requestedVerticalSubset.add(level);
                    }
                }
                readRequest.setVerticalSubset(requestedVerticalSubset);

                SortedSet<DateRange> requestedTemporalSubset = new DateRangeTreeSet();
                SortedSet<? extends DateRange> temporalElements = temporalDomain.getTemporalElements(false,
                        null);
                final int numTimes = temporalElements.size();
                Iterator<? extends DateRange> iteratorT = temporalElements.iterator();
                for (int i = 0; i < numTimes; i++) {
                    DateRange time = iteratorT.next();
                    if (i % (numTimes / 5) == 1) {
                        requestedTemporalSubset.add(time);
                    }
                }
                readRequest.setTemporalSubset(requestedTemporalSubset);

                CoverageResponse response = gridSource.read(readRequest, null);
                if (response == null || response.getStatus() != Status.SUCCESS
                        || !response.getExceptions().isEmpty()) {
                    throw new IOException("Unable to read");
                }

                final Collection<? extends Coverage> results = response.getResults(null);
                int index = 0;
                for (Coverage c : results) {
                    GridCoverageResponse resp = (GridCoverageResponse) c;
                    GridCoverage2D coverage = resp.getGridCoverage2D();
                    String title = coverage.getSampleDimension(0).getDescription().toString();
                    // Crs and envelope
                    if (isInteractiveTest) {
                        // ImageIOUtilities.visualize(coverage.getRenderedImage(), "tt",true);
                        coverage.show(title + " " + index++);
                    } else {
                        PlanarImage.wrapRenderedImage(coverage.getRenderedImage()).getTiles();
                    }

                    final StringBuilder buffer = new StringBuilder();
                    buffer.append("GridCoverage CRS: ")
                            .append(coverage.getCoordinateReferenceSystem2D().toWKT()).append("\n");
                    buffer.append("GridCoverage GG: ").append(coverage.getGridGeometry().toString())
                            .append("\n");
                    LOGGER.info(buffer.toString());
                }
                gridSource.dispose();
            }
        } catch (Throwable t) {
            if (LOGGER.isLoggable(Level.WARNING)) {
                LOGGER.log(Level.WARNING, t.getLocalizedMessage(), t);
            }
        } finally {
            if (access != null) {
                try {
                    access.dispose();
                } catch (Throwable t) {
                    // Does nothing
                }
            }
        }
    }
}

From source file:org.apache.forrest.conf.ForrestConfModule.java

public Iterator getAttributeNames(Configuration modeConf, Map objectModel) throws ConfigurationException {

    SortedSet matchset = new TreeSet();
    Enumeration enumeration = filteringProperties.keys();
    while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        matchset.add(key);//  ww w  .  j av a2 s.c  om
    }
    Iterator iterator = super.getAttributeNames(modeConf, objectModel);
    while (iterator.hasNext())
        matchset.add(iterator.next());
    return matchset.iterator();
}

From source file:ca.travelagency.components.fields.TravelDocumentField.java

@Override
protected Iterator<String> getChoices(String input) {
    if (StringUtils.isEmpty(input)) {
        return Collections.<String>emptyList().iterator();
    }/* w ww  . j a  v a2s.  c o  m*/
    SortedSet<String> choices = new TreeSet<String>();
    Locale[] locales = Locale.getAvailableLocales();
    for (Locale locale : locales) {
        String country = locale.getDisplayCountry().toUpperCase();
        if (country.startsWith(input.toUpperCase())) {
            String value = getLocalizer().getString(country, this, country);
            if (StringUtils.isBlank(value)) {
                value = country;
            }
            choices.add(WordUtils.capitalize(StringUtils.lowerCase(value + " " + suffix)));
            if (choices.size() == DISPLAY_MAX_SIZE) {
                break;
            }
        }
    }
    return choices.iterator();
}

From source file:org.wymiwyg.rdfserializer.ResourceSerializer.java

/**
 * @param resource/*www. j ava2 s .  c  o m*/
 * @param sink
 */
private void appendInlineResource(Resource resource, Style style, Map variables, int deepness, String urlBase,
        String[] languages, UnavailableLocalisationHandler localisationHandler, ContentSink sink,
        Collection remainingResources) throws IOException, LanguageUnavailableException {
    if (variables.containsKey(resource)) {
        return;
    }
    deepness++;
    if (log.isDebugEnabled()) {
        log.debug("Deepness :" + deepness);
        log.debug("Appending resource of type (stmt): " + resource.getProperty(RDF.type));
    }
    Set usedStatements = new HashSet();
    ResourceTag resourceTag = new ResourceTag(resource, style, usedStatements, variables, urlBase);
    sink.append(resourceTag);
    StmtIterator propertiesIter = resource.listProperties();
    Set propertyTypes = new HashSet();
    while (propertiesIter.hasNext()) {
        propertyTypes.add(propertiesIter.nextStatement().getPredicate());
    }
    PropertyDescriptor propertyDescriptors[] = style.getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor current = propertyDescriptors[i];
        Property property = current.getProperty();
        if (propertyTypes.contains(property)) {
            propertyTypes.remove(property);
            appendProperties(resource, property, usedStatements, current.getStyle(), variables, deepness,
                    urlBase, languages, localisationHandler, sink, remainingResources);
        }
    }
    //remaning property-types:
    Iterator remainingProperties = propertyTypes.iterator();
    SortedSet sortedProperties = new TreeSet(new PropertyComparator());
    while (remainingProperties.hasNext()) {
        sortedProperties.add(remainingProperties.next());
    }
    remainingProperties = sortedProperties.iterator();
    while (remainingProperties.hasNext()) {
        Property property = (Property) remainingProperties.next();
        appendProperties(resource, property, usedStatements, style, variables, deepness, urlBase, languages,
                localisationHandler, sink, remainingResources);
    }
    sink.append(resourceTag.getClosingTag());
}