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:org.sakaiproject.content.tool.FilePickerAction.java

/**
* Develop a list of all the site collections that there are to page.
* Sort them as appropriate, and apply search criteria.
*//*from   w  w  w.j  a  v  a2 s . c om*/
@SuppressWarnings("unchecked")
protected List<ListItem> readAllResources(SessionState state) {
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    ContentHostingService contentService = (ContentHostingService) toolSession
            .getAttribute(STATE_CONTENT_SERVICE);

    ResourceTypeRegistry registry = (ResourceTypeRegistry) toolSession
            .getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
    if (registry == null) {
        registry = (ResourceTypeRegistry) ComponentManager
                .get("org.sakaiproject.content.api.ResourceTypeRegistry");
        toolSession.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
    }

    List<ListItem> other_sites = new Vector<ListItem>();

    String homeCollectionId = (String) toolSession.getAttribute(STATE_HOME_COLLECTION_ID);

    // make sure the collectionId is set
    String collectionId = (String) toolSession.getAttribute(STATE_DEFAULT_COLLECTION_ID);
    if (collectionId == null) {
        collectionId = homeCollectionId;
    }

    Set<String> expandedCollections = getExpandedCollections(toolSession);

    Comparator userSelectedSort = (Comparator) toolSession.getAttribute(STATE_LIST_VIEW_SORT);

    ContentResourceFilter filter = (ContentResourceFilter) state.getAttribute(STATE_ATTACHMENT_FILTER);

    // add user's personal workspace
    User user = UserDirectoryService.getCurrentUser();
    String userId = user.getId();
    String wsId = SiteService.getUserSiteId(userId);
    String wsCollectionId = contentService.getSiteCollection(wsId);

    if (!collectionId.equals(wsCollectionId)) {
        try {
            ContentCollection wsCollection = contentService.getCollection(wsCollectionId);
            ListItem wsRoot = ListItem.getListItem(wsCollection, null, registry, false, expandedCollections,
                    null, null, 0, userSelectedSort, false, filter);
            other_sites.add(wsRoot);
        } catch (IdUnusedException e) {
            // TODO Auto-generated catch block
            logger.warn("IdUnusedException ", e);
        } catch (TypeException e) {
            // TODO Auto-generated catch block
            logger.warn("TypeException ", e);
        } catch (PermissionException e) {
            // TODO Auto-generated catch block
            logger.warn("PermissionException ", e);
        }
    }

    /*
    * add all other sites user has access to
    * NOTE: This does not (and should not) get all sites for admin.  
    *       Getting all sites for admin is too big a request and
    *       would result in too big a display to render in html.
    */
    Map othersites = contentService.getCollectionMap();
    SortedSet sort = new TreeSet();
    for (Iterator<Entry<String, String>> mapIter = othersites.entrySet().iterator(); mapIter.hasNext();) {
        Entry<String, String> entry = mapIter.next();
        sort.add(entry.getValue() + ResourcesAction.DELIM + entry.getKey());
    }

    Iterator<String> sortIt = sort.iterator();
    while (sortIt.hasNext()) {
        String keyvalue = sortIt.next();
        String displayName = keyvalue.substring(0, keyvalue.lastIndexOf(ResourcesAction.DELIM));
        String collId = keyvalue.substring(keyvalue.lastIndexOf(ResourcesAction.DELIM) + 1);
        if (!collectionId.equals(collId) && !wsCollectionId.equals(collId)) {
            ContentCollection collection;
            try {
                collection = contentService.getCollection(collId);
                ListItem root = ListItem.getListItem(collection, null, registry, false, expandedCollections,
                        null, null, 0, null, false, null);
                root.setName(displayName);
                other_sites.add(root);
            } catch (IdUnusedException e) {
                // its expected that some collections eg the drop box collection may not exit
                logger.debug("IdUnusedException (FilePickerAction.readAllResources()) collId == " + collId
                        + " --> " + e);
            } catch (TypeException e) {
                logger.warn("TypeException (FilePickerAction.readAllResources()) collId == " + collId + " --> "
                        + e);
            } catch (PermissionException e) {
                //SAK-18496 we don't show a user collections they don't have access to 
                logger.debug("PermissionException (FilePickerAction.readAllResources()) collId == " + collId
                        + " --> " + e);
            }
        }
    }

    return other_sites;
}

From source file:com.stratelia.silverpeas.pdcPeas.servlets.PdcSearchRequestRouter.java

/**
 * Cette mthode est appelle uniquement lorsque l'utilisateur fait une recherche combinant la
 * recherche classique  la recherche PDC. Elle rcupre dans une liste tous les documents se
 * trouvant positionns dans le PDC de ie. Puis elle ne garde, que les elements communs entre les
 * deux listes - celle cre et celle des silvercontentid. Ensuite, elle rcupre les
 * MatchinIndexEntry correspondant aux rsultats du tri des listes.
 *
 * @param ie - le tableau de MatchingIndexEntry trouv par la recherche classique
 * @return le nouveau tableau de MatchingIndexEntry.
 *//*from   www. j  a v a 2 s  .  co  m*/
private MatchingIndexEntry[] mixedSearch(MatchingIndexEntry[] ie, List<Integer> alSilverContentIds)
        throws Exception {

    // On crait une liste trie d'indexEntry
    SortedSet<Integer> basicSearchList = new TreeSet<Integer>();
    List<String> docFeature = new ArrayList<String>();
    for (int i = 0; ie != null && i < ie.length; i++) {
        String instanceId = ie[i].getComponent(); // recupere l'instanceId
        String objectId = ie[i].getObjectId(); // recupere l'id du document
        docFeature.add(objectId);
        docFeature.add(instanceId);
    }
    try {
        // on rcupre le silverContentId  partir de la recherche classique
        basicSearchList = contentManager.getSilverContentId(docFeature);
    } catch (Exception e) {
        SilverTrace.info("pdcPeas", "PdcSearchRequestRouteur.mixedSearch", "root.MSG_GEN_EXIT_METHOD");
    }

    // ne garde que les objets communs aux 2 listes basicSearchList - alSilverContentIds
    // en effet, la liste resultante du PDC n'est pas la meme que celle
    // labore  partir de la recherche classique
    if (alSilverContentIds != null) {
        basicSearchList.retainAll(alSilverContentIds);
    }

    // la liste basicSearchList ne contient maintenant que les silverContentIds des documents
    // trouvs
    // mais ces documents sont galement dans le tableau rsultat de la recherche classique
    // il faut donc crer un tableau de MatchingIndexEntry pour afficher le resultat
    List<MatchingIndexEntry> result = new ArrayList<MatchingIndexEntry>();

    if (basicSearchList != null && basicSearchList.size() > 0) {
        // la liste contient bien des rsultats
        Iterator<Integer> it = basicSearchList.iterator();
        for (; it.hasNext();) {
            int contentId = it.next().intValue(); // on rcupre le silverContentId de la
            // liste
            // on rcupre l'internalContentId car nous en avons besoin pour la construction d'un
            // matchingIndexEntry
            String internalContentId = contentManager.getInternalContentId(contentId);
            MatchingIndexEntry mie = getMatchingIndexEntry(ie, internalContentId);
            if (mie != null) {
                result.add(mie);
            }
        }
    }

    Collections.sort(result, ScoreComparator.comparator);
    return result.toArray(new MatchingIndexEntry[0]);
}

From source file:mondrian.olap.Util.java

/**
 * Returns the intersection of two sorted sets. Does not modify either set.
 *
 * <p>Optimized for the case that both sets are {@link ArraySortedSet}.</p>
 *
 * @param set1 First set/* w ww . ja v a  2  s .  com*/
 * @param set2 Second set
 * @return Intersection of the sets
 */
public static <E extends Comparable> SortedSet<E> intersect(SortedSet<E> set1, SortedSet<E> set2) {
    if (set1.isEmpty()) {
        return set1;
    }
    if (set2.isEmpty()) {
        return set2;
    }
    if (!(set1 instanceof ArraySortedSet) || !(set2 instanceof ArraySortedSet)) {
        final TreeSet<E> set = new TreeSet<E>(set1);
        set.retainAll(set2);
        return set;
    }
    final Comparable<?>[] result = new Comparable[Math.min(set1.size(), set2.size())];
    final Iterator<E> it1 = set1.iterator();
    final Iterator<E> it2 = set2.iterator();
    int i = 0;
    E e1 = it1.next();
    E e2 = it2.next();
    for (;;) {
        final int compare = e1.compareTo(e2);
        if (compare == 0) {
            result[i++] = e1;
            if (!it1.hasNext() || !it2.hasNext()) {
                break;
            }
            e1 = it1.next();
            e2 = it2.next();
        } else if (compare == 1) {
            if (!it2.hasNext()) {
                break;
            }
            e2 = it2.next();
        } else {
            if (!it1.hasNext()) {
                break;
            }
            e1 = it1.next();
        }
    }
    return new ArraySortedSet(result, 0, i);
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

public void initialise(PackageInfo p, Model m, Options o, ShapeChangeResult r, boolean diagOnly)
        throws ShapeChangeAbortException {
    pi = p;/*  w w  w. j ava  2 s . co  m*/
    model = m;
    options = o;
    result = r;

    try {

        if (!initialised) {
            initialised = true;

            String pathToJavaExe_ = options.parameter(this.getClass().getName(), PARAM_JAVA_EXE_PATH);
            if (pathToJavaExe_ != null && pathToJavaExe_.trim().length() > 0) {
                pathToJavaExe = pathToJavaExe_.trim();
                if (!pathToJavaExe.startsWith("\"")) {
                    pathToJavaExe = "\"" + pathToJavaExe;
                }
                if (!pathToJavaExe.endsWith("\"")) {
                    pathToJavaExe = pathToJavaExe + "\"";
                }

                String jo_tmp = options.parameter(this.getClass().getName(), PARAM_JAVA_OPTIONS);
                if (jo_tmp != null && jo_tmp.trim().length() > 0) {
                    javaOptions = jo_tmp.trim();
                }

                /*
                 * check path - and potentially also options - by invoking
                 * the exe
                 */
                List<String> cmds = new ArrayList<String>();
                cmds.add(pathToJavaExe);
                if (javaOptions != null) {
                    cmds.add(javaOptions);
                }
                cmds.add("-version");

                ProcessBuilder pb = new ProcessBuilder(cmds);

                try {
                    Process proc = pb.start();

                    StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream());
                    StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream());

                    errorGobbler.start();
                    outputGobbler.start();

                    errorGobbler.join();
                    outputGobbler.join();

                    int exitVal = proc.waitFor();

                    if (exitVal != 0) {
                        if (errorGobbler.hasResult()) {
                            MessageContext mc = result.addFatalError(this, 21, StringUtils.join(cmds, " "),
                                    "" + exitVal);
                            mc.addDetail(this, 27, errorGobbler.getResult());
                        } else {
                            result.addFatalError(this, 21, StringUtils.join(cmds, " "), "" + exitVal);
                        }
                        throw new ShapeChangeAbortException();
                    }

                } catch (InterruptedException e) {
                    result.addFatalError(this, 22);
                    throw new ShapeChangeAbortException();
                }
            }

            encounteredAppSchemasByName = new TreeMap<String, Integer>();

            initialiseFromOptions();

            String s = null;

            Model refModel_tmp = getReferenceModel();

            if (refModel_tmp != null) {

                /*
                 * Ensure that IDs used in the reference model are unique to
                 * that model and do not get mixed up with the IDs of the
                 * input model.
                 * 
                 * REQUIREMENT for model diff: two objects with equal ID
                 * must represent the same model element. If a model element
                 * is deleted in the reference model, then a new model
                 * element in the input model must not have the same ID.
                 * 
                 * It looks like this cannot be guaranteed. Therefore we add
                 * a prefix to the IDs of the model elements in the
                 * reference model.
                 */
                refModel = new GenericModel(refModel_tmp);
                refModel_tmp.shutdown();

                refModel.addPrefixToModelElementIDs("refmodel_");
            }

            String xmlName = outputFilename + ".tmp.xml";

            // Check whether we can use the given output directory
            File outputDirectoryFile = new File(outputDirectory);
            boolean exi = outputDirectoryFile.exists();
            if (!exi) {
                outputDirectoryFile.mkdirs();
                exi = outputDirectoryFile.exists();
            }
            boolean dir = outputDirectoryFile.isDirectory();
            boolean wrt = outputDirectoryFile.canWrite();
            boolean rea = outputDirectoryFile.canRead();
            if (!exi || !dir || !wrt || !rea) {
                result.addFatalError(this, 12, outputDirectory);
                throw new ShapeChangeAbortException();
            }

            String encoding_ = encoding == null ? "UTF-8" : model.characterEncoding();

            OutputStream fout = new FileOutputStream(outputDirectory + "/" + xmlName);
            OutputStream bout = new BufferedOutputStream(fout, streamBufferSize);
            OutputStreamWriter outputXML = new OutputStreamWriter(bout, encoding_);

            writer = new XMLWriter(outputXML, encoding_);

            writer.forceNSDecl("http://www.w3.org/2001/XMLSchema-instance", "xsi");

            writer.startDocument();

            writer.processingInstruction("xml-stylesheet", "type='text/xsl' href='./html.xsl'");

            writer.comment("Feature catalogue created using ShapeChange");

            AttributesImpl atts = new AttributesImpl();
            atts.addAttribute("http://www.w3.org/2001/XMLSchema-instance", "noNamespaceSchemaLocation",
                    "xsi:noNamespaceSchemaLocation", "CDATA", "FC.xsd");
            writer.startElement("", "FeatureCatalogue", "", atts);

            s = options.parameter(this.getClass().getName(), "name");
            if (s != null && s.length() > 0)
                writer.dataElement("name", s);
            else
                writer.dataElement("name", "unknown");

            s = options.parameter(this.getClass().getName(), "scope");

            if (s != null && s.length() > 0)
                PrintLineByLine(s, "scope", null);
            else {
                writer.dataElement("scope", "unknown");
            }

            s = options.parameter(this.getClass().getName(), "versionNumber");
            if (s != null && s.length() > 0)
                writer.dataElement("versionNumber", s);
            else
                writer.dataElement("versionNumber", "unknown");

            s = options.parameter(this.getClass().getName(), "versionDate");
            if (s != null && s.length() > 0)
                writer.dataElement("versionDate", s);
            else
                writer.dataElement("versionDate", "unknown");

            s = options.parameter(this.getClass().getName(), "producer");
            if (s != null && s.length() > 0)
                writer.dataElement("producer", s);
            else
                writer.dataElement("producer", "unknown");
        }

        // we need to compute the diff for each application schema
        if (refModel != null) {

            SortedSet<PackageInfo> set = refModel.schemas(p.name());

            if (set.size() == 1) {

                /*
                 * Get the full names of classes (in lower case) from the
                 * input schema so that later we can look them up by their
                 * full name (within the schema, not in the model).
                 */
                inputSchemaClassesByFullNameInSchema = new HashMap<String, ClassInfo>();
                for (ClassInfo ci : model.classes(pi)) {
                    inputSchemaClassesByFullNameInSchema.put(ci.fullNameInSchema().toLowerCase(Locale.ENGLISH),
                            ci);
                }

                // compute diffs
                differ = new Differ();
                refPackage = set.iterator().next();
                SortedMap<Info, SortedSet<DiffElement>> pi_diffs = differ.diff(p, refPackage);

                // merge diffs for pi with existing diffs (from other
                // schemas)
                differ.merge(diffs, pi_diffs);

                // log the diffs found for pi
                for (Entry<Info, SortedSet<DiffElement>> me : pi_diffs.entrySet()) {

                    MessageContext mc = result.addInfo(
                            "Model difference - " + me.getKey().fullName().replace(p.fullName(), p.name()));

                    for (DiffElement diff : me.getValue()) {
                        String s = diff.change + " " + diff.subElementType;
                        if (diff.subElementType == ElementType.TAG)
                            s += "(" + diff.tag + ")";
                        if (diff.subElement != null)
                            s += " " + diff.subElement.name();
                        else if (diff.diff != null)
                            s += " " + (new diff_match_patch()).diff_prettyHtml(diff.diff);
                        else
                            s += " ???";
                        mc.addDetail(s);
                    }
                }

                /*
                 * switch to default xslt for html diff - unless the
                 * configuration explicitly names an XSLT file to use
                 */
                if (options.parameter(this.getClass().getName(), "xslhtmlFile") == null) {
                    xslhtmlfileName = DEFAULT_XSL_HTML_DIFF_FILE_NAME;
                }

            } else {
                result.addWarning(null, 308, p.name());
                refModel = null;
            }
        }

        writer.startElement("ApplicationSchema", "id", "_P" + pi.id());

        /*
         * Determine if app schema with same name has been encountered
         * before, and choose name accordingly
         */

        String nameForAppSchema = null;

        if (encounteredAppSchemasByName.containsKey(pi.name())) {
            int count = encounteredAppSchemasByName.get(pi.name()).intValue();
            count++;
            nameForAppSchema = pi.name() + " (" + count + ")";
            encounteredAppSchemasByName.put(pi.name(), new Integer(count));
        } else {
            nameForAppSchema = pi.name();
            encounteredAppSchemasByName.put(pi.name(), new Integer(1));
        }

        // now set the name of the application schema
        writer.dataElement("name", nameForAppSchema);

        String s = pi.definition();
        if (s != null && s.length() > 0) {
            PrintLineByLine(s, "definition", null);
        }
        s = pi.description();
        if (s != null && s.length() > 0) {
            PrintLineByLine(s, "description", null);
        }

        s = pi.version();
        if (s != null && s.length() > 0) {
            writer.dataElement("versionNumber", s);
        }

        writer.startElement("taggedValues");

        s = pi.taggedValue(TransformationConstants.TRF_TV_NAME_GENERATIONDATETIME);
        if (s != null && s.trim().length() > 0) {
            writer.dataElement(TransformationConstants.TRF_TV_NAME_GENERATIONDATETIME, PrepareToPrint(s));
        }

        writer.endElement("taggedValues");

        if (pi.getDiagrams() != null) {
            appendImageInfo(pi.getDiagrams());
        }

        writer.endElement("ApplicationSchema");

        /*
         * Check if there are any deletions of classes or packages that are
         * owned by the application schema package.
         */

        if (hasDiff(pi, ElementType.SUBPACKAGE, Operation.DELETE)) {

            Set<DiffElement> pkgdiffs = getDiffs(pi, ElementType.SUBPACKAGE, Operation.DELETE);

            for (DiffElement diff : pkgdiffs) {

                // child package was deleted
                PrintPackage((PackageInfo) diff.subElement, Operation.DELETE);
            }

        }

        printContainedPackages(pi);

        /*
         * NOTE: inserted or unchanged classes are handled in
         * process(ClassInfo) method
         */
        printDeletedClasses(pi);

    } catch (Exception e) {

        String msg = e.getMessage();
        if (msg != null) {
            result.addError(msg);
        }
        e.printStackTrace(System.err);
    }
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

/**
 * Returns the Attr[]s to be output for the given element.
 * <br>/*  w ww  .j  a  v a 2  s  .c om*/
 * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a 
 * DOM which has been prepared using 
 * {@link org.apache.xml.security.utils.XMLUtils#circumventBug2650(
 * org.w3c.dom.Document)}.
 * 
 * @param element
 * @param ns
 * @return the Attr[]s to be output
 * @throws CanonicalizationException
 */
@Override
protected Iterator<Attr> handleAttributes(Element element, NameSpaceSymbTable ns)
        throws CanonicalizationException {
    // result will contain the attrs which have to be output
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(element, ns.getLevel()) == 1;
    final SortedSet<Attr> result = this.result;
    result.clear();

    if (element.hasAttributes()) {
        NamedNodeMap attrs = element.getAttributes();
        int attrsLength = attrs.getLength();

        for (int i = 0; i < attrsLength; i++) {
            Attr attribute = (Attr) attrs.item(i);
            String NUri = attribute.getNamespaceURI();
            String NName = attribute.getLocalName();
            String NValue = attribute.getValue();

            if (!XMLNS_URI.equals(NUri)) {
                //A non namespace definition node.
                if (XML_LANG_URI.equals(NUri)) {
                    if (NName.equals("id")) {
                        if (isRealVisible) {
                            // treat xml:id like any other attribute 
                            // (emit it, but don't inherit it)
                            result.add(attribute);
                        }
                    } else {
                        xmlattrStack.addXmlnsAttr(attribute);
                    }
                } else if (isRealVisible) {
                    //The node is visible add the attribute to the list of output attributes.
                    result.add(attribute);
                }
            } else if (!XML.equals(NName) || !XML_LANG_URI.equals(NValue)) {
                /* except omit namespace node with local name xml, which defines
                 * the xml prefix, if its string value is 
                 * http://www.w3.org/XML/1998/namespace.
                 */
                // add the prefix binding to the ns symb table.
                if (isVisible(attribute)) {
                    if (isRealVisible || !ns.removeMappingIfRender(NName)) {
                        // The xpath select this node output it if needed.
                        Node n = ns.addMappingAndRender(NName, NValue, attribute);
                        if (n != null) {
                            result.add((Attr) n);
                            if (C14nHelper.namespaceIsRelative(attribute)) {
                                Object exArgs[] = { element.getTagName(), NName, attribute.getNodeValue() };
                                throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace",
                                        exArgs);
                            }
                        }
                    }
                } else {
                    if (isRealVisible && !XMLNS.equals(NName)) {
                        ns.removeMapping(NName);
                    } else {
                        ns.addMapping(NName, NValue, attribute);
                    }
                }
            }
        }
    }

    if (isRealVisible) {
        //The element is visible, handle the xmlns definition        
        Attr xmlns = element.getAttributeNodeNS(XMLNS_URI, XMLNS);
        Node n = null;
        if (xmlns == null) {
            //No xmlns def just get the already defined.
            n = ns.getMapping(XMLNS);
        } else if (!isVisible(xmlns)) {
            //There is a definition but the xmlns is not selected by the xpath.
            //then xmlns=""
            n = ns.addMappingAndRender(XMLNS, "", nullNode);
        }
        //output the xmlns def if needed.
        if (n != null) {
            result.add((Attr) n);
        }
        //Float all xml:* attributes of the unselected parent elements to this one. 
        xmlattrStack.getXmlnsAttr(result);
        ns.getUnrenderedNodes(result);
    }

    return result.iterator();
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

/**
 * Write the status of tables to a file.
 *
 * @param db//from  ww  w.  j a va 2  s  .co  m
 *          The database in question.
 * @param showTblStatus
 *          tables we are interested in
 * @return Return 0 when execution succeeds and above 0 if it fails.
 */
private int showTableStatus(Hive db, ShowTableStatusDesc showTblStatus) throws HiveException {
    // get the tables for the desired pattern - populate the output stream
    List<Table> tbls = new ArrayList<Table>();
    Map<String, String> part = showTblStatus.getPartSpec();
    Partition par = null;
    if (part != null) {
        Table tbl = db.getTable(showTblStatus.getDbName(), showTblStatus.getPattern());
        par = db.getPartition(tbl, part, false);
        if (par == null) {
            throw new HiveException(
                    "Partition " + part + " for table " + showTblStatus.getPattern() + " does not exist.");
        }
        tbls.add(tbl);
    } else {
        LOG.info("pattern: " + showTblStatus.getPattern());
        List<String> tblStr = db.getTablesForDb(showTblStatus.getDbName(), showTblStatus.getPattern());
        SortedSet<String> sortedTbls = new TreeSet<String>(tblStr);
        Iterator<String> iterTbls = sortedTbls.iterator();
        while (iterTbls.hasNext()) {
            // create a row per table name
            String tblName = iterTbls.next();
            Table tbl = db.getTable(showTblStatus.getDbName(), tblName);
            tbls.add(tbl);
        }
        LOG.info("results : " + tblStr.size());
    }

    // write the results in the file
    DataOutputStream outStream = getOutputStream(showTblStatus.getResFile());
    try {
        formatter.showTableStatus(outStream, db, conf, tbls, part, par);
    } catch (Exception e) {
        throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show table status");
    } finally {
        IOUtils.closeStream(outStream);
    }
    return 0;
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

/**
 * Write a list of the user defined functions to a file.
 * @param db//from   w w  w. ja v a 2s  . c  om
 *
 * @param showFuncs
 *          are the functions we're interested in.
 * @return Returns 0 when execution succeeds and above 0 if it fails.
 * @throws HiveException
 *           Throws this exception if an unexpected error occurs.
 */
private int showFunctions(Hive db, ShowFunctionsDesc showFuncs) throws HiveException {
    // get the tables for the desired patten - populate the output stream
    Set<String> funcs = null;
    if (showFuncs.getPattern() != null) {
        LOG.info("pattern: " + showFuncs.getPattern());
        if (showFuncs.getIsLikePattern()) {
            funcs = FunctionRegistry.getFunctionNamesByLikePattern(showFuncs.getPattern());
        } else {
            console.printInfo("SHOW FUNCTIONS is deprecated, please use SHOW FUNCTIONS LIKE instead.");
            funcs = FunctionRegistry.getFunctionNames(showFuncs.getPattern());
        }
        LOG.info("results : " + funcs.size());
    } else {
        funcs = FunctionRegistry.getFunctionNames();
    }

    // write the results in the file
    DataOutputStream outStream = getOutputStream(showFuncs.getResFile());
    try {
        SortedSet<String> sortedFuncs = new TreeSet<String>(funcs);
        // To remove the primitive types
        sortedFuncs.removeAll(serdeConstants.PrimitiveTypes);
        Iterator<String> iterFuncs = sortedFuncs.iterator();

        while (iterFuncs.hasNext()) {
            // create a row per table name
            outStream.writeBytes(iterFuncs.next());
            outStream.write(terminator);
        }
    } catch (FileNotFoundException e) {
        LOG.warn("show function: " + stringifyException(e));
        return 1;
    } catch (IOException e) {
        LOG.warn("show function: " + stringifyException(e));
        return 1;
    } catch (Exception e) {
        throw new HiveException(e);
    } finally {
        IOUtils.closeStream(outStream);
    }
    return 0;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.UploadTable.java

/**
 * @param row/*www  .  j  av a2 s.  c  o m*/
 * @throws UploaderException
 * 
 * deletes all records uploaded for row.
 */
public void abortRow(final int row) throws UploaderException {
    UploadedRecordInfo arg1 = new UploadedRecordInfo(null, row, 0, null);
    UploadedRecordInfo arg2 = new UploadedRecordInfo(null, row + 1, 0, null);
    SortedSet<UploadedRecordInfo> recsForRow = uploadedRecs.subSet(arg1, arg2);
    if (recsForRow.size() > 0) {
        deleteObjects(recsForRow.iterator(), false);
        uploadedRecs.removeAll(recsForRow);
    }
}

From source file:uk.ac.liverpool.thumbnails.PDFService.java

@Override
public FontInformation[] extractFontList(URI u, File fff) throws MalformedURLException, IOException {

    SortedSet<FontInformation> ret = new TreeSet<FontInformation>();
    PDDocument document = getPages(u, fff);
    List pages = document.getDocumentCatalog().getAllPages();
    int i = 0;// w ww  .ja  v  a 2s  . c  o m
    // The code down here is easier as it gets all the fonts used in the document. Still, this would inlcude unused fonts, so we get the fonts page by page and add them to a Hash table.
    for (COSObject c : document.getDocument().getObjectsByType(COSName.FONT)) {
        if (c == null || !(c.getObject() instanceof COSDictionary))
            continue;
        //System.out.println(c.getObject());

        COSDictionary fontDictionary = (COSDictionary) c.getObject();
        // System.out.println(dic.getNameAsString(COSName.BASE_FONT));
        //            }
        //        }
        //        int pagen = document.getNumberOfPages();
        //        i=0;
        //        for (int p=0;p<pagen;p++){
        //            PDPage page = (PDPage)pages.get(p);
        //            PDResources res = page.findResources();
        //            //for each page resources
        //            if (res==null) continue; 
        //            // get the font dictionary
        //            COSDictionary fonts = (COSDictionary) res.getCOSDictionary().getDictionaryObject( COSName.FONT );
        //            for( COSName fontName : fonts.keySet() ) {
        //                COSObject font = (COSObject) fonts.getItem( fontName );
        //                // if the font has already been visited we ingore it
        //                long objectId = font.getObjectNumber().longValue();
        //                if (ret.get(objectId)!=null)
        //                    continue;
        //                if( font==null ||  ! (font.getObject() instanceof COSDictionary) )
        //                    continue;
        //                COSDictionary fontDictionary = (COSDictionary)font.getObject();

        // Type MUSt be font
        if (!fontDictionary.getNameAsString(COSName.TYPE).equals("Font"))
            continue;
        // get the variables
        FontInformation fi = new FontInformation();
        fi.fontType = fontDictionary.getNameAsString(COSName.SUBTYPE);

        String baseFont = fontDictionary.getNameAsString(COSName.BASE_FONT);
        if (baseFont == null)
            continue;
        if (Arrays.binarySearch(standard14, baseFont) >= 0)
            continue;
        COSDictionary fontDescriptor = (COSDictionary) fontDictionary.getDictionaryObject(COSName.FONT_DESC);
        COSBase enc = fontDictionary.getItem(COSName.ENCODING);
        COSBase uni = fontDictionary.getItem(COSName.TO_UNICODE);
        int firstChar = fontDictionary.getInt(COSName.FIRST_CHAR);
        int lastChar = fontDictionary.getInt(COSName.LAST_CHAR);
        String encoding;
        boolean toUnicode = uni != null;
        if (enc == null) {
            encoding = "standard14";
        }
        if (enc instanceof COSString) {
            encoding = ((COSString) enc).getString();
        } else {
            encoding = "table";
        }
        fi.isSubset = false;
        boolean t = true;
        // Type one and TT can have subsets defineing the basename see 5.5.3 pdfref 1.6
        //  if (fi.fontType.lastIndexOf(COSName.TYPE1.getName())!=-1 || fi.fontType.equals(COSName.TRUE_TYPE.getName()) )
        if (baseFont != null) {
            if (baseFont.length() > 6) {
                for (int k = 0; k < 6; k++)
                    if (!Character.isUpperCase(baseFont.charAt(k)))
                        t = false;
                if (baseFont.charAt(6) != '+')
                    t = false;
            } else
                t = false;
            fi.isSubset = t;
            if (fi.isSubset)
                baseFont = baseFont.substring(7);
        }
        fi.fontFlags = 0;
        if (fi.fontType.equals(COSName.TYPE0) || fi.fontType.equals(COSName.TYPE3))
            fi.isEmbedded = true;

        if (fontDescriptor != null) {
            // in Type1 charset indicates font is subsetted
            if (fontDescriptor.getItem(COSName.CHAR_SET) != null)
                fi.isSubset = true;
            if (fontDescriptor.getItem(COSName.FONT_FILE) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE3) != null
                    || fontDescriptor.getItem(COSName.FONT_FILE2) != null)
                fi.isEmbedded = true;
            fi.fontFlags = fontDescriptor.getInt(COSName.getPDFName("Flags"));
            fi.fontFamily = fontDescriptor.getString(COSName.FONT_FAMILY);
            fi.fontStretch = fontDescriptor.getString(COSName.FONT_STRETCH);
        }
        fi.charset = encoding;
        fi.fontName = baseFont;
        fi.isToUnicode = toUnicode;

        ret.add(fi);

    } // for all fonts 

    //    } // for all pages
    Iterator<FontInformation> it = ret.iterator();
    FontInformation prev = null;
    LinkedList<FontInformation> toDelete = new LinkedList<FontInformation>();
    while (it.hasNext()) {
        FontInformation current = it.next();

        if (prev != null && prev.fontName.equals(current.fontName) && prev.fontType.startsWith("CIDFontType"))
            toDelete.add(current);
        prev = current;
    }
    ret.removeAll(toDelete);
    FontInformation[] retArray = ret.toArray(new FontInformation[0]);

    return retArray;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.wbuploader.Uploader.java

/**
 * Builds form for upload UI.//from   ww  w  .ja  va2 s. c  o m
 */
protected void buildMainUI() {
    mainPanel = new UploadMainPanel(isUpdateUpload());

    SortedSet<UploadInfoRenderable> uts = new TreeSet<UploadInfoRenderable>();
    for (UploadTable ut : uploadTables) {
        UploadInfoRenderable render = new UploadInfoRenderable(ut);
        if (uts.contains(render)) {
            for (UploadInfoRenderable r : uts) {
                if (r.equals(render)) {
                    r.addTable(ut);
                    break;
                }
            }
        } else {
            uts.add(new UploadInfoRenderable(ut));
        }
    }
    mainPanel.addAffectedTables(uts.iterator());
    mainPanel.setActionListener(this);
}