Example usage for java.util TreeSet iterator

List of usage examples for java.util TreeSet iterator

Introduction

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

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this set in ascending order.

Usage

From source file:org.bigtextml.topics.ParallelTopicModel.java

public String displayTopWords(int numWords, boolean usingNewLines) {

    StringBuilder out = new StringBuilder();

    ArrayList<TreeSet<IDSorter>> topicSortedWords = getSortedWords();

    // Print results for each topic
    for (int topic = 0; topic < numTopics; topic++) {
        TreeSet<IDSorter> sortedWords = topicSortedWords.get(topic);
        int word = 1;
        Iterator<IDSorter> iterator = sortedWords.iterator();

        if (usingNewLines) {
            out.append(topic + "\t" + formatter.format(alpha[topic]) + "\n");
            while (iterator.hasNext() && word < numWords) {
                IDSorter info = iterator.next();
                out.append(//from  w ww .  ja v a 2 s . c o m
                        alphabet.lookupObject(info.getID()) + "\t" + formatter.format(info.getWeight()) + "\n");
                word++;
            }
        } else {
            out.append(topic + "\t" + formatter.format(alpha[topic]) + "\t");

            while (iterator.hasNext() && word < numWords) {
                IDSorter info = iterator.next();
                out.append(alphabet.lookupObject(info.getID()) + " ");
                word++;
            }
            out.append("\n");
        }
    }

    return out.toString();
}

From source file:org.apache.myfaces.trinidadbuild.plugin.tagdoc.TagdocReport.java

private void _writeComponentAttributes(Writer out, ComponentBean bean) throws IOException {
    // Sort the names
    TreeSet<String> attributes = new TreeSet<String>();
    Iterator<PropertyBean> attrs = bean.properties(true);
    attrs = new FilteredIterator(attrs, new NonHiddenFilter());

    while (attrs.hasNext()) {
        PropertyBean property = attrs.next();
        if (!property.isTagAttributeExcluded())
            attributes.add(property.getPropertyName());
    }/*  www.j ava  2  s  . c  o m*/

    // Now get a list of PropertyBeans
    List<PropertyBean> list = new ArrayList<PropertyBean>();
    Iterator<String> iter = attributes.iterator();
    while (iter.hasNext()) {
        String attrName = iter.next();
        list.add(bean.findProperty(attrName, true));
    }

    TreeSet<String> groups = new TreeSet<String>(new GroupComparator());
    /* No current support for grouping
    // Make sure "null" is the representative for unknown groups
    Iterator iter = attributes.iterator();
    while (iter.hasNext())
    {
      String group = ((AttributeDoc) iter.next()).group;
      if (group != null)
        groups.add(group);
    }
    */

    _writeComponentAttributes(out, list.iterator(), bean.getComponentClass(),
            groups.isEmpty() ? null : "Ungrouped");

    Iterator<String> groupIter = groups.iterator();
    while (groupIter.hasNext()) {
        _writeComponentAttributes(out, list.iterator(), bean.getComponentClass(), groupIter.next());
    }
}

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader/*from  ww w.jav a 2  s  .  c om*/
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws javax.xml.bind.JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH:
    //    Pros: preferred way of doing this.
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list.
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Create a JAXBContext using the contextPackages
 *
 * @param contextPackages Set<String>
 * @param cl              ClassLoader/* ww  w  .  j av a  2s . c om*/
 * @param forceArrays     boolean (true if JAXBContext must include all arrays)
 * @param properties      Map of properties for the JAXBContext.newInstance creation method
 * @param classRefs       List of class references
 * @return JAXBContextValue (JAXBContext + constructionType)
 * @throws JAXBException
 */
private static JAXBContextValue createJAXBContextValue(TreeSet<String> contextPackages, ClassLoader cl,
        boolean forceArrays, Map<String, ?> properties, List<String> classRefs) throws JAXBException {

    JAXBContextValue contextValue = null;
    if (log.isDebugEnabled()) {

        log.debug("Following packages are in this batch of getJAXBContext() :");

        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
        log.debug("This classloader will be used to construct the JAXBContext" + cl);
    }
    // The contextPackages is a set of package names that are constructed using PackageSetBuilder.
    // PackageSetBuilder gets the packages names from various sources.
    //   a) It walks the various annotations on the WebService collecting package names.
    //   b) It walks the wsdl/schemas and builds package names for each target namespace.
    //
    // The combination of these two sources should produce all of the package names.
    // -------------
    // Note that (b) is necessary for the following case:
    // An operation has a parameter named BASE.
    // Object DERIVED is an extension of BASE and is defined in a different package/schema.
    // In this case, there will not be any annotations on the WebService that reference DERIVED.
    // The only way to find the package for DERIVED is to walk the schemas.
    // -------------

    Iterator<String> it = contextPackages.iterator();
    while (it.hasNext()) {
        String p = it.next();
        // Don't consider java and javax packages
        // REVIEW: We might have to refine this
        if (p.startsWith("javax.xml.ws.wsaddressing")) {
            continue;
        }
        if (p.startsWith("java.") || p.startsWith("javax.")) {
            it.remove();
        }
    }

    // There are two ways to construct the context.
    // 1) USE A CONTEXTPATH, which is a string containing
    //    all of the packages separated by colons.
    // 2) USE A CLASS[], which is an array of all of the classes
    //    involved in the marshal/unmarshal.
    //   
    // There are pros/cons with both approaches.
    // USE A CONTEXTPATH: 
    //    Pros: preferred way of doing this.  
    //          performant
    //          most dynamic
    //    Cons: Each package in context path must have an ObjectFactory
    //        
    //
    // USE CLASS[]:
    //    Pros: Doesn't require ObjectFactory in each package
    //    Cons: Hard to set up, must account for JAX-WS classes, etc.
    //          Does not work if arrays of classes are needed
    //          slower
    //
    //  The following code attempts to build a context path.  It then
    //  choose one of the two constructions above (prefer USE A CONTEXT_PATH)
    //

    // The packages are examined to see if they have ObjectFactory/package-info classes.
    // Invalid packages are removed from the list
    it = contextPackages.iterator();
    boolean contextConstruction = (!forceArrays);
    boolean isJAXBFound = false;
    while (it.hasNext()) {
        String p = it.next();
        // See if this package has an ObjectFactory or package-info
        if (checkPackage(p, cl)) {
            // Flow to here indicates package can be used for CONTEXT construction
            isJAXBFound = true;
            if (log.isDebugEnabled()) {
                log.debug("Package " + p + " contains an ObjectFactory or package-info class.");
            }
        } else {
            // Flow to here indicates that the package is not valid for context construction.
            // Perhaps the package is invalid.
            if (log.isDebugEnabled()) {
                log.debug("Package " + p
                        + " does not contain an ObjectFactory or package-info class.  Searching for JAXB classes");
            }
            List<Class> classes = null;
            classes = getAllClassesFromPackage(p, cl);
            if (classes == null || classes.size() == 0) {
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not have any JAXB classes.  It is removed from the JAXB context path.");
                }
                it.remove();
            } else {
                // Classes are found in the package.  We cannot use the CONTEXT construction
                contextConstruction = false;
                if (log.isDebugEnabled()) {
                    log.debug("Package " + p
                            + " does not contain ObjectFactory, but it does contain other JAXB classes.");
                }
            }
        }
    }

    if (!isJAXBFound) {
        if (log.isDebugEnabled()) {
            log.debug("ObjectFactory & package-info are not found in package hierachy");
        }
    }

    // The code above may have removed some packages from the list. 
    // Retry our lookup with the updated list
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache Start: Some packages have been removed from the list.  Rechecking cache.");
        }
        String key = contextPackages.toString();
        ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
        SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);
        if (softRef != null) {
            innerMap = softRef.get();
        }

        if (innerMap != null) {
            contextValue = innerMap.get(cl);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                if (log.isDebugEnabled()) {
                    log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                            + "  but the caller requested a JAXBContext "
                            + " that includes arrays.  A new JAXBContext will be built");
                }
                contextValue = null;
            }

            if (contextValue != null) {
                if (log.isDebugEnabled()) {
                    log.debug("Successfully found JAXBContext with updated context list:"
                            + contextValue.jaxbContext.toString());
                }
                return contextValue;
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Recheck Cache End: Did not find a JAXBContext.  Will build a new JAXBContext.");
        }
    }

    // CONTEXT construction
    if (contextConstruction) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using the packages only.");
        }
        JAXBContext context = createJAXBContextUsingContextPath(contextPackages, cl, classRefs);
        if (context != null) {
            contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CONTEXT_PATH);
        }
        if (log.isDebugEnabled()) {
            log.debug("Building a JAXBContext with packages only success=" + (contextValue != null));
        }
    }

    // CLASS construction
    if (contextValue == null) {
        if (log.isDebugEnabled()) {
            log.debug("Try building a JAXBContext using a list of classes.");
            log.debug("Start finding classes");
        }
        it = contextPackages.iterator();
        List<Class> fullList = new ArrayList<Class>();
        while (it.hasNext()) {
            String pkg = it.next();
            fullList.addAll(getAllClassesFromPackage(pkg, cl));
        }
        //Lets add all common array classes
        addCommonArrayClasses(fullList);
        Class[] classArray = fullList.toArray(new Class[0]);
        if (log.isDebugEnabled()) {
            log.debug("End finding classes");
        }
        JAXBContext context = JAXBContext_newInstance(classArray, cl, properties, classRefs);
        if (context != null) {
            if (forceArrays) {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS);
            } else {
                contextValue = new JAXBContextValue(context, CONSTRUCTION_TYPE.BY_CLASS_ARRAY);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully created JAXBContext " + contextValue.jaxbContext.toString());
    }
    return contextValue;
}

From source file:org.codehaus.enunciate.modules.jersey.JerseyDeploymentModule.java

@Override
protected void doBuild() throws EnunciateException, IOException {
    super.doBuild();

    File webappDir = getBuildDir();
    webappDir.mkdirs();/* w  w  w.  ja  v a2  s  .  com*/
    File webinf = new File(webappDir, "WEB-INF");
    File webinfClasses = new File(webinf, "classes");
    getEnunciate().copyFile(new File(getGenerateDir(), "jaxrs-providers.list"),
            new File(webinfClasses, "jaxrs-providers.list"));
    getEnunciate().copyFile(new File(getGenerateDir(), "jaxrs-root-resources.list"),
            new File(webinfClasses, "jaxrs-root-resources.list"));
    getEnunciate().copyFile(new File(getGenerateDir(), "jaxrs-jaxb-types.list"),
            new File(webinfClasses, "jaxrs-jaxb-types.list"));
    getEnunciate().copyFile(new File(getGenerateDir(), "media-type-mappings.properties"),
            new File(webinfClasses, "media-type-mappings.properties"));
    getEnunciate().copyFile(new File(getGenerateDir(), "ns2prefix.properties"),
            new File(webinfClasses, "ns2prefix.properties"));

    BaseWebAppFragment webappFragment = new BaseWebAppFragment(getName());
    webappFragment.setBaseDir(webappDir);
    WebAppComponent servletComponent = new WebAppComponent();
    servletComponent.setName("jersey");
    servletComponent.setClassname(EnunciateJerseyServletContainer.class.getName());
    TreeMap<String, String> initParams = new TreeMap<String, String>();
    initParams.putAll(getServletInitParams());
    if (!isUsePathBasedConneg()) {
        initParams.put(JerseyAdaptedHttpServletRequest.FEATURE_PATH_BASED_CONNEG, Boolean.FALSE.toString());
    }
    if (isUseSubcontext()) {
        initParams.put(JerseyAdaptedHttpServletRequest.PROPERTY_SERVLET_PATH, getRestSubcontext());
    }
    if (getResourceProviderFactory() != null) {
        initParams.put(JerseyAdaptedHttpServletRequest.PROPERTY_RESOURCE_PROVIDER_FACTORY,
                getResourceProviderFactory());
    }
    if (getApplicationClass() != null) {
        initParams.put("javax.ws.rs.Application", getApplicationClass());
    }
    if (getLoadOnStartup() != null) {
        servletComponent.setLoadOnStartup(getLoadOnStartup());
    }
    servletComponent.setInitParams(initParams);

    TreeSet<String> urlMappings = new TreeSet<String>();
    for (RootResource rootResource : getModel().getRootResources()) {
        for (ResourceMethod resourceMethod : rootResource.getResourceMethods(true)) {
            String resourceMethodPattern = resourceMethod.getServletPattern();
            for (Set<String> subcontextList : ((Map<String, Set<String>>) resourceMethod.getMetaData()
                    .get("subcontexts")).values()) {
                for (String subcontext : subcontextList) {
                    String servletPattern;
                    if ("".equals(subcontext)) {
                        servletPattern = isUseWildcardServletMapping() ? "/*" : resourceMethodPattern;
                    } else {
                        servletPattern = isUseWildcardServletMapping() ? subcontext + "/*"
                                : subcontext + resourceMethodPattern;
                    }

                    if (urlMappings.add(servletPattern)) {
                        debug("Resource method %s of resource %s to be made accessible by servlet pattern %s.",
                                resourceMethod.getSimpleName(), resourceMethod.getParent().getQualifiedName(),
                                servletPattern);
                    }
                }
            }
        }
    }

    if (urlMappings.contains("/*")) {
        urlMappings.clear();
        urlMappings.add("/*");
    } else {
        Iterator<String> iterator = urlMappings.iterator();
        while (iterator.hasNext()) {
            String mapping = iterator.next();
            if (!mapping.endsWith("/*") && urlMappings.contains(mapping + "/*")) {
                iterator.remove();
            }
        }
    }

    servletComponent.setUrlMappings(urlMappings);
    webappFragment.setServlets(Arrays.asList(servletComponent));
    getEnunciate().addWebAppFragment(webappFragment);
}

From source file:ca.sqlpower.architect.diff.CompareSQL.java

/**
 * Creates a List of DiffChunks that describe the differences between the
 * columns of the given tables./*  w  w w .j a v  a2  s.c o m*/
 *
 * @param sourceTable The "left side" for the comparison.  If null, then all columns
 * in the target table will be considered obsolete.
 * @param targetTable The "right side" for the comparison.  If null, then all columns
 * in the source table will be considered new.
 * @throws SQLObjectException If the getColumns() methods of the source or target
 * tables run into trouble.
 */
private List<DiffChunk<SQLObject>> generateColumnDiffs(SQLTable sourceTable, SQLTable targetTable)
        throws SQLObjectException {
    TreeSet<SQLColumn> sourceColumnList;
    TreeSet<SQLColumn> targetColumnList;
    Iterator<SQLColumn> sourceColIter;
    Iterator<SQLColumn> targetColIter;
    SQLColumn sourceColumn;
    SQLColumn targetColumn;
    boolean sourceColContinue;
    boolean targetColContinue;
    boolean keyChangeFlag = false;

    sourceColumnList = new TreeSet<SQLColumn>(getObjectComparator());
    targetColumnList = new TreeSet<SQLColumn>(getObjectComparator());
    sourceColContinue = false;
    targetColContinue = false;
    sourceColIter = null;
    targetColIter = null;
    sourceColumn = null;
    targetColumn = null;

    // We store the diffs in here, then return this list
    List<DiffChunk<SQLObject>> diffs = new ArrayList<DiffChunk<SQLObject>>();

    if (sourceTable != null) {
        sourceColumnList.addAll(sourceTable.getColumns());
    }
    if (targetTable != null) {
        targetColumnList.addAll(targetTable.getColumns());
    }
    if (sourceColumnList.size() == 0) {
        sourceColumnList = null;
        sourceColContinue = false;
    } else {
        sourceColIter = sourceColumnList.iterator();
        sourceColumn = sourceColIter.next();
        sourceColContinue = true;
    }

    if (targetColumnList.size() == 0) {
        targetColumnList = null;
        targetColContinue = false;
    } else {

        targetColIter = targetColumnList.iterator();
        targetColumn = targetColIter.next();
        targetColContinue = true;
    }

    while (sourceColContinue && targetColContinue) {

        int compareResult = getObjectComparator().compare(sourceColumn, targetColumn);
        // Comparing Columns
        if (compareResult < 0) {
            diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.LEFTONLY));
            logger.debug("The source column is " + sourceColumn);
            if (sourceColumn.isPrimaryKey()) {
                keyChangeFlag = true;
            }
            if (sourceColIter.hasNext()) {
                sourceColumn = sourceColIter.next();
            } else {
                sourceColContinue = false;

            }

        }
        // Comparing Columns
        if (compareResult > 0) {
            diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.RIGHTONLY));
            logger.debug("The target column is " + targetColumn);
            if (targetColumn.isPrimaryKey()) {
                keyChangeFlag = true;
            }
            if (targetColIter.hasNext()) {
                targetColumn = targetColIter.next();
            } else {
                targetColContinue = false;

            }
        }

        // Comparing Columns
        if (compareResult == 0) {

            if (targetColumn.isPrimaryKey() != sourceColumn.isPrimaryKey()) {
                keyChangeFlag = true;
                //diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.KEY_CHANGED));
            }

            List<PropertyChange> changes = generatePropertyChanges(sourceColumn, targetColumn);
            if (changes.size() > 0) {
                DiffChunk<SQLObject> chunk = null;

                if (nameComparator.compare(sourceColumn, targetColumn) != 0) {
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.NAME_CHANGED);
                    chunk.setOriginalData(sourceColumn);
                } else if (ArchitectUtils.columnsDiffer(targetColumn, sourceColumn)) {
                    // Make sure the changes are worthy of a SQL script generation:
                    if (logger.isDebugEnabled()) {
                        logger.debug("Column " + sourceColumn.getName() + " differs!");
                        logger.debug(String.format("  Type:      %10d %10d", targetColumn.getType(),
                                sourceColumn.getType()));
                        logger.debug(String.format("  Precision: %10d %10d", targetColumn.getPrecision(),
                                sourceColumn.getPrecision()));
                        logger.debug(String.format("  Scale:     %10d %10d", targetColumn.getScale(),
                                sourceColumn.getScale()));
                        logger.debug(String.format("  Nullable:  %10d %10d", targetColumn.getNullable(),
                                sourceColumn.getNullable()));
                    }
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.SQL_MODIFIED);
                } else {
                    chunk = new DiffChunk<SQLObject>(targetColumn, DiffType.MODIFIED);
                }

                for (PropertyChange change : changes) {
                    chunk.addPropertyChange(change);
                }
                diffs.add(chunk);

            } else {
                if (!suppressSimilarities) {
                    diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.SAME));
                }
            }

            if (targetColIter.hasNext()) {
                targetColumn = targetColIter.next();
            } else {
                targetColContinue = false;
            }

            if (sourceColIter.hasNext()) {
                sourceColumn = sourceColIter.next();
            } else {
                sourceColContinue = false;
            }
        }
    }
    while (sourceColContinue) {
        diffs.add(new DiffChunk<SQLObject>(sourceColumn, DiffType.LEFTONLY));
        if (sourceColIter.hasNext()) {
            sourceColumn = sourceColIter.next();
        } else {
            sourceColContinue = false;
        }
    }

    while (targetColContinue) {
        diffs.add(new DiffChunk<SQLObject>(targetColumn, DiffType.RIGHTONLY));
        if (targetColIter.hasNext()) {
            targetColumn = targetColIter.next();
        } else {
            targetColContinue = false;
        }
    }

    if (keyChangeFlag) {
        if (sourceTable.getPkSize() > 0) {
            diffs.add(new DiffChunk<SQLObject>(sourceTable, DiffType.DROP_KEY));
        }
        diffs.add(new DiffChunk<SQLObject>(targetTable, DiffType.KEY_CHANGED));
    }
    return diffs;
}

From source file:net.sf.mzmine.modules.peaklistmethods.alignment.ransac.RansacAlignerTask.java

/**
 * //from w w  w  .j  a va2 s .c om
 * @param peakList
 * @return
 */
private HashMap<PeakListRow, PeakListRow> getAlignmentMap(PeakList peakList) {

    // Create a table of mappings for best scores
    HashMap<PeakListRow, PeakListRow> alignmentMapping = new HashMap<PeakListRow, PeakListRow>();

    if (alignedPeakList.getNumberOfRows() < 1) {
        return alignmentMapping;
    }

    // Create a sorted set of scores matching
    TreeSet<RowVsRowScore> scoreSet = new TreeSet<RowVsRowScore>();

    // RANSAC algorithm
    List<AlignStructMol> list = ransacPeakLists(alignedPeakList, peakList);
    PolynomialFunction function = this.getPolynomialFunction(list);

    PeakListRow allRows[] = peakList.getRows();

    for (PeakListRow row : allRows) {
        // Calculate limits for a row with which the row can be aligned
        Range mzRange = mzTolerance.getToleranceRange(row.getAverageMZ());

        double rt;
        try {
            rt = function.value(row.getAverageRT());
        } catch (NullPointerException e) {
            rt = row.getAverageRT();
        }
        if (Double.isNaN(rt) || rt == -1) {
            rt = row.getAverageRT();
        }

        Range rtRange = rtToleranceAfter.getToleranceRange(rt);

        // Get all rows of the aligned peaklist within parameter limits
        PeakListRow candidateRows[] = alignedPeakList.getRowsInsideScanAndMZRange(rtRange, mzRange);

        for (PeakListRow candidate : candidateRows) {
            RowVsRowScore score;
            if (sameChargeRequired && (!PeakUtils.compareChargeState(row, candidate))) {
                continue;
            }

            try {
                score = new RowVsRowScore(row, candidate, mzRange.getSize() / 2, rtRange.getSize() / 2, rt);

                scoreSet.add(score);
                errorMessage = score.getErrorMessage();

            } catch (Exception e) {
                e.printStackTrace();
                setStatus(TaskStatus.ERROR);
                return null;
            }
        }
        processedRows++;
    }

    // Iterate scores by descending order
    Iterator<RowVsRowScore> scoreIterator = scoreSet.iterator();
    while (scoreIterator.hasNext()) {

        RowVsRowScore score = scoreIterator.next();

        // Check if the row is already mapped
        if (alignmentMapping.containsKey(score.getPeakListRow())) {
            continue;
        }

        // Check if the aligned row is already filled
        if (alignmentMapping.containsValue(score.getAlignedRow())) {
            continue;
        }

        alignmentMapping.put(score.getPeakListRow(), score.getAlignedRow());

    }

    return alignmentMapping;
}

From source file:org.pentaho.platform.web.servlet.AdhocWebService.java

public void searchTable(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap) throws IOException {
    String domainId = (String) parameterProvider.getParameter("modelId"); //$NON-NLS-1$
    String modelId = (String) parameterProvider.getParameter("viewId"); //$NON-NLS-1$
    String tableId = (String) parameterProvider.getParameter("tableId"); //$NON-NLS-1$
    String columnId = (String) parameterProvider.getParameter("columnId"); //$NON-NLS-1$
    String searchStr = (String) parameterProvider.getParameter("searchStr"); //$NON-NLS-1$

    ByteArrayOutputStream xactionOutputStream = new ByteArrayOutputStream();
    createMQLQueryActionSequence(domainId, modelId, tableId, columnId, searchStr, xactionOutputStream,
            userSession.getName());/* w  w w  . ja  v  a  2  s  . c  o m*/
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element resultsElement = document.addElement("results"); //$NON-NLS-1$

    IRuntimeContext runtimeContext = AdhocWebService.executeActionSequence(
            xactionOutputStream.toString(LocaleHelper.getSystemEncoding()), "mqlQuery.xaction", //$NON-NLS-1$
            new SimpleParameterProvider(), userSession, new ByteArrayOutputStream());
    if (runtimeContext.getStatus() == IRuntimeContext.RUNTIME_STATUS_SUCCESS) {
        IActionParameter actionParameter = runtimeContext.getOutputParameter("query_result"); //$NON-NLS-1$
        IPentahoResultSet pentahoResultSet = actionParameter.getValueAsResultSet();
        TreeSet treeSet = new TreeSet();
        for (int i = 0; i < pentahoResultSet.getRowCount(); i++) {
            Object[] rowValues = pentahoResultSet.getDataRow(i);
            if (rowValues[0] != null) {
                treeSet.add(rowValues[0]);
            }
        }
        for (Iterator iterator = treeSet.iterator(); iterator.hasNext();) {
            resultsElement.addElement("row").setText(iterator.next().toString()); //$NON-NLS-1$
        }
        runtimeContext.dispose();
    }
    WebServiceUtil.writeString(outputStream, document.asXML(), wrapWithSoap);
}

From source file:com.cyberway.issue.crawler.admin.StatisticsTracker.java

protected Iterator<SeedRecord> getSeedRecordsSortedByStatusCode(Iterator<String> i) {
    TreeSet<SeedRecord> sortedSet = new TreeSet<SeedRecord>(new Comparator<SeedRecord>() {
        public int compare(SeedRecord sr1, SeedRecord sr2) {
            int code1 = sr1.getStatusCode();
            int code2 = sr2.getStatusCode();
            if (code1 == code2) {
                // If the values are equal, sort by URIs.
                return sr1.getUri().compareTo(sr2.getUri());
            }/*from w  w  w  .  j  a v  a 2 s. co  m*/
            // mirror and shift the nubmer line so as to
            // place zero at the beginning, then all negatives 
            // in order of ascending absolute value, then all 
            // positives descending
            code1 = -code1 - Integer.MAX_VALUE;
            code2 = -code2 - Integer.MAX_VALUE;

            return new Integer(code1).compareTo(new Integer(code2));
        }
    });
    while (i.hasNext()) {
        String seed = i.next();
        SeedRecord sr = (SeedRecord) processedSeedsRecords.get(seed);
        if (sr == null) {
            sr = new SeedRecord(seed, SEED_DISPOSITION_NOT_PROCESSED);
            processedSeedsRecords.put(seed, sr);
        }
        sortedSet.add(sr);
    }
    return sortedSet.iterator();
}

From source file:org.codehaus.enunciate.modules.jboss.JBossDeploymentModule.java

@Override
protected void doBuild() throws EnunciateException, IOException {
    super.doBuild();

    BaseWebAppFragment webappFragment = new BaseWebAppFragment(getName());
    HashMap<String, String> jbossContextParameters = new HashMap<String, String>();
    webappFragment.setContextParameters(jbossContextParameters);

    ArrayList<WebAppComponent> servlets = new ArrayList<WebAppComponent>();
    if (this.enableJaxws) {
        for (WsdlInfo wsdlInfo : getModelInternal().getNamespacesToWSDLs().values()) {
            for (EndpointInterface ei : wsdlInfo.getEndpointInterfaces()) {
                String path = (String) ei.getMetaData().get("soapPath");
                WebAppComponent wsComponent = new WebAppComponent();
                wsComponent.setName(ei.getServiceName());
                wsComponent.setClassname(ei.getEndpointImplementations().iterator().next().getQualifiedName());
                wsComponent.setUrlMappings(new TreeSet<String>(Arrays.asList(path)));
                servlets.add(wsComponent);
            }/*from   www.ja  va  2s. com*/
        }
    }

    if (this.enableJaxrs) {
        WebAppComponent jaxrsServletComponent = new WebAppComponent();
        jaxrsServletComponent.setName("resteasy-jaxrs");
        jaxrsServletComponent.setClassname(EnunciateJBossHttpServletDispatcher.class.getName());
        TreeSet<String> jaxrsUrlMappings = new TreeSet<String>();
        StringBuilder resources = new StringBuilder();
        for (RootResource rootResource : getModel().getRootResources()) {
            if (resources.length() > 0) {
                resources.append(',');
            }
            resources.append(rootResource.getQualifiedName());

            for (ResourceMethod resourceMethod : rootResource.getResourceMethods(true)) {
                String resourceMethodPattern = resourceMethod.getServletPattern();
                for (Set<String> subcontextList : ((Map<String, Set<String>>) resourceMethod.getMetaData()
                        .get("subcontexts")).values()) {
                    for (String subcontext : subcontextList) {
                        String servletPattern;
                        if ("".equals(subcontext)) {
                            servletPattern = resourceMethodPattern;
                        } else {
                            servletPattern = subcontext + resourceMethodPattern;
                        }

                        if (jaxrsUrlMappings.add(servletPattern)) {
                            debug("Resource method %s of resource %s to be made accessible by servlet pattern %s.",
                                    resourceMethod.getSimpleName(),
                                    resourceMethod.getParent().getQualifiedName(), servletPattern);
                        }
                    }
                }
            }
        }

        if (jaxrsUrlMappings.contains("/*")) {
            jaxrsUrlMappings.clear();
            jaxrsUrlMappings.add("/*");
        } else {
            Iterator<String> iterator = jaxrsUrlMappings.iterator();
            while (iterator.hasNext()) {
                String mapping = iterator.next();
                if (!mapping.endsWith("/*") && jaxrsUrlMappings.contains(mapping + "/*")) {
                    iterator.remove();
                }
            }
        }

        StringBuilder providers = new StringBuilder();
        for (TypeDeclaration provider : getModel().getJAXRSProviders()) {
            if (providers.length() > 0) {
                providers.append(',');
            }

            providers.append(provider.getQualifiedName());
        }

        if (jacksonAvailable) {
            if (providers.length() > 0) {
                providers.append(',');
            }

            providers.append("org.codehaus.enunciate.jboss.ResteasyJacksonJaxbProvider");
        }

        if (getEnunciate().isModuleEnabled("amf")) {
            if (providers.length() > 0) {
                providers.append(',');
            }

            providers.append("org.codehaus.enunciate.modules.amf.JAXRSProvider");
        }

        jaxrsServletComponent.setUrlMappings(jaxrsUrlMappings);
        jbossContextParameters.put(ResteasyContextParameters.RESTEASY_RESOURCES, resources.toString());
        jbossContextParameters.put(ResteasyContextParameters.RESTEASY_PROVIDERS, providers.toString());
        String mappingPrefix = this.useSubcontext ? getRestSubcontext() : "";
        if (!"".equals(mappingPrefix)) {
            jbossContextParameters.put("resteasy.servlet.mapping.prefix", mappingPrefix);
            jaxrsServletComponent.addInitParam("resteasy.servlet.mapping.prefix", mappingPrefix);
        }
        if (isUsePathBasedConneg()) {
            Map<String, String> contentTypesToIds = getModelInternal().getContentTypesToIds();
            if (contentTypesToIds != null && contentTypesToIds.size() > 0) {
                StringBuilder builder = new StringBuilder();
                Iterator<Map.Entry<String, String>> contentTypeIt = contentTypesToIds.entrySet().iterator();
                while (contentTypeIt.hasNext()) {
                    Map.Entry<String, String> contentTypeEntry = contentTypeIt.next();
                    builder.append(contentTypeEntry.getValue()).append(" : ").append(contentTypeEntry.getKey());
                    if (contentTypeIt.hasNext()) {
                        builder.append(", ");
                    }
                }
                jbossContextParameters.put(ResteasyContextParameters.RESTEASY_MEDIA_TYPE_MAPPINGS,
                        builder.toString());
            }
        }
        jbossContextParameters.put(ResteasyContextParameters.RESTEASY_SCAN_RESOURCES, Boolean.FALSE.toString());
        servlets.add(jaxrsServletComponent);
    }

    webappFragment.setServlets(servlets);
    if (!this.options.isEmpty()) {
        webappFragment.setContextParameters(this.options);
    }
    getEnunciate().addWebAppFragment(webappFragment);
}