Example usage for java.util LinkedHashSet add

List of usage examples for java.util LinkedHashSet add

Introduction

In this page you can find the example usage for java.util LinkedHashSet add.

Prototype

boolean add(E e);

Source Link

Document

Adds the specified element to this set if it is not already present (optional operation).

Usage

From source file:org.alfresco.bm.dataload.rm.unfiled.ScheduleUnfiledRecordLoaders.java

/**
 * Obtains all unfiled record folders underneath specified parent folder plus the parent folder
 *
 * @param parentFolder - the parent folder that we need to get unfiled record folders from
 * @return all unfiled record folders underneath specified parent folder plus the parent folder
 *//*w w  w .  j a  v a2 s  . co  m*/
private Set<FolderData> getUnfiledRecordFolders(FolderData parentFolder) {
    LinkedHashSet<FolderData> result = new LinkedHashSet<FolderData>();
    int skip = 0;
    int limit = 100;
    List<FolderData> directChildren = new ArrayList<FolderData>();
    List<FolderData> childFolders = fileFolderService.getChildFolders(UNFILED_CONTEXT, parentFolder.getPath(),
            skip, limit);
    while (childFolders.size() > 0) {
        directChildren.addAll(childFolders);
        skip += limit;
        childFolders = fileFolderService.getChildFolders(UNFILED_CONTEXT, parentFolder.getPath(), skip, limit);
    }
    if (directChildren.size() > 0) {
        for (FolderData childFolder : directChildren) {
            result.addAll(getUnfiledRecordFolders(childFolder));
        }
    }
    result.add(parentFolder);
    return result;
}

From source file:org.osaf.cosmo.calendar.EntityConverter.java

/**
 * Expands an event calendar and returns a set of notes representing the
 * master and exception items.//  w w w. ja  v  a2  s. c om
 * <p>
 * The provided note corresponds to the recurrence master or, for
 * non-recurring items, the single event in the calendar. The result set
 * includes both the master note as well as a modification note for
 * exception event in the calendar.
 * </p>
 * <p>
 * If the master note does not already have a UUID or an event stamp, one
 * is assigned to it. A UUID is assigned because any modification items
 * that are created require the master's UUID in order to construct
 * their own.
 * </p>
 * <p>
 * If the given note is already persistent, and the calendar does not
 * contain an exception event matching an existing modification, that
 * modification is set inactive. It is still returned in the result set.
 * </p>
 */
public Set<NoteItem> convertEventCalendar(NoteItem note, Calendar calendar) {
    EventStamp eventStamp = (EventStamp) note.getStamp(EventStamp.class);

    if (eventStamp == null) {
        eventStamp = entityFactory.createEventStamp(note);
        note.addStamp(eventStamp);
    }

    if (note.getUid() == null)
        note.setUid(entityFactory.generateUid());

    updateEventInternal(note, calendar);

    LinkedHashSet<NoteItem> items = new LinkedHashSet<NoteItem>();
    items.add(note);

    // add modifications to set of items
    for (Iterator<NoteItem> it = note.getModifications().iterator(); it.hasNext();) {
        NoteItem mod = it.next();
        items.add(mod);
    }

    return items;
}

From source file:com.cwctravel.hudson.plugins.extended_choice_parameter_artifactory.ExtendedChoiceParameterArtifactoryDefinition.java

LinkedHashMap<String, LinkedHashSet<String>> calculateChoicesByDropdownId() throws Exception {
    List<String[]> fileLines = Collections.emptyList();
    if (propertyFileMulti != null) {
        File file = new File(propertyFileMulti);
        if (file.isFile()) {
            CSVReader csvReader = null;//w  w  w.  j  ava 2s  .c om
            try {
                csvReader = new CSVReader(new FileReader(file), '\t');
                fileLines = csvReader.readAll();
            } finally {
                csvReader.close();
            }
        } else {
            URL propertyFileUrl = new URL(propertyFileMulti);
            CSVReader csvReader = null;
            try {
                csvReader = new CSVReader(new InputStreamReader(propertyFileUrl.openStream()), '\t');
                fileLines = csvReader.readAll();
            } finally {
                csvReader.close();
            }
        }
    } else if (artifactoryURL != null) {
        String[] repos = artifactoryRepositories.split(",");
        HttpClient httpclient = new HttpClient();
        fileLines = new ArrayList();
        propertyValueMulti = "REPOSITORY,ARTIFACT";
        fileLines.add(propertyValueMulti.split(","));
        for (String repo : repos) {
            try {
                GetMethod method = new GetMethod(artifactoryURL + "/artifactory/api/storage/" + repo);
                httpclient.executeMethod(method);

                if (method != null) {
                    String jsonString = new String(method.getResponseBody());
                    org.json.JSONObject obj = new org.json.JSONObject(jsonString);
                    org.json.JSONArray array = obj.getJSONArray("children");
                    List<String> artifacts;
                    for (int i = 0; i < array.length(); i++) {
                        if (array.getJSONObject(i).getString("folder").equals("false")) {
                            Boolean pass = true;
                            if (mustExclude != null && !mustExclude.equals("")) {
                                for (String exclude : mustExclude.split(",")) {
                                    if (array.getJSONObject(i).getString("uri").contains(exclude)) {
                                        pass = false;
                                        break;
                                    }
                                }
                            }
                            if (mustInclude != null && !mustInclude.equals("")) {
                                for (String include : mustInclude.split(",")) {
                                    if (!array.getJSONObject(i).getString("uri").contains(include)) {
                                        pass = false;
                                        break;
                                    }
                                }
                            }
                            if (pass) {
                                fileLines.add(new String[] { repo,
                                        array.getJSONObject(i).getString("uri").substring(1) });
                            }
                        }
                    }

                }
            } catch (Exception e) {
                continue;
            }
        }
    }

    if (fileLines.size() < 2) {
        throw new Exception("Multi level tab delimited file must have at least 2 "
                + "lines (one for the header, and one or more for the data)");
    }

    ArrayList<Integer> columnIndicesForDropDowns = columnIndicesForDropDowns(fileLines.get(0));

    List<String[]> dataLines = fileLines.subList(1, fileLines.size());

    LinkedHashMap<String, LinkedHashSet<String>> choicesByDropdownId = new LinkedHashMap<String, LinkedHashSet<String>>();

    String prefix = getName() + " dropdown MultiLevelMultiSelect 0";
    choicesByDropdownId.put(prefix, new LinkedHashSet<String>());

    for (int i = 0; i < columnIndicesForDropDowns.size(); ++i) {
        String prettyCurrentColumnName = propertyValueMulti.split(",")[i];
        prettyCurrentColumnName = prettyCurrentColumnName.toLowerCase();
        prettyCurrentColumnName = prettyCurrentColumnName.replace("_", " ");

        for (String[] dataLine : dataLines) {
            String priorLevelDropdownId = prefix;
            String currentLevelDropdownId = prefix;

            int column = 0;
            for (int j = 0; j <= i; ++j) {
                column = columnIndicesForDropDowns.get(j);

                if (j < i) {
                    priorLevelDropdownId += " " + dataLine[column];
                }
                currentLevelDropdownId += " " + dataLine[column];
            }
            if (i != columnIndicesForDropDowns.size() - 1) {
                choicesByDropdownId.put(currentLevelDropdownId, new LinkedHashSet<String>());
            }
            LinkedHashSet<String> choicesForPriorDropdown = choicesByDropdownId.get(priorLevelDropdownId);
            choicesForPriorDropdown.add("Select a " + prettyCurrentColumnName + "...");
            choicesForPriorDropdown.add(dataLine[column]);
        }
    }

    return choicesByDropdownId;
}

From source file:org.jahia.services.sites.JahiaSitesBaseService.java

public void initAfterAllServicesAreStarted() throws JahiaInitializationException {
    try {// w w  w .j av a2 s.c o m
        JahiaUser jahiaUser = JCRSessionFactory.getInstance().getCurrentUser();
        if (getNbSites() == 0) {
            Locale selectedLocale = LanguageCodeConverters.languageCodeToLocale(systemSiteDefaultLanguage);
            JahiaSite site = addSite(jahiaUser, systemSiteTitle, systemSiteServername, SYSTEM_SITE_KEY, "",
                    selectedLocale, systemSiteTemplateSetName, null, "noImport", null, null, false, false,
                    null);
            site.setMixLanguagesActive(true);
            site.setLanguages(systemSiteLanguages);
            updateSite(site);
            final LinkedHashSet<String> languages = new LinkedHashSet<String>();
            languages.add(selectedLocale.toString());
            final List<String> uuids = new ArrayList<String>();
            try {
                JCRNodeWrapper node = (JCRNodeWrapper) sessionFactory.getCurrentUserSession()
                        .getNode(SITES_JCR_PATH).getNodes().nextNode();
                node.checkout();
                //                     node.changeRoles("g:users","re---");
                uuids.add(node.getIdentifier());
                List<PublicationInfo> publicationInfos = JCRPublicationService.getInstance().getPublicationInfo(
                        node.getIdentifier(), languages, true, true, true, Constants.EDIT_WORKSPACE,
                        Constants.LIVE_WORKSPACE);
                for (PublicationInfo publicationInfo : publicationInfos) {
                    if (publicationInfo.needPublication(null)) {
                        uuids.addAll(publicationInfo.getAllUuids());
                    }
                }
                JCRPublicationService.getInstance().publish(uuids, Constants.EDIT_WORKSPACE,
                        Constants.LIVE_WORKSPACE, null);
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            } finally {
                JCRSessionFactory.getInstance().closeAllSessions();
            }
        }
    } catch (JahiaException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.espertech.esper.epl.spec.PatternStreamSpecRaw.java

private PatternStreamSpecCompiled compileInternal(StatementContext context, Set<String> eventTypeReferences,
        boolean isInsertInto, Collection<Integer> assignedTypeNumberStack, MatchEventSpec tags,
        Set<String> priorAllTags) throws ExprValidationException {
    if (tags == null) {
        tags = new MatchEventSpec();
    }// w  ww  .jav a2  s . c o m
    Deque<Integer> subexpressionIdStack = new ArrayDeque<Integer>(assignedTypeNumberStack);
    ExprEvaluatorContext evaluatorContextStmt = new ExprEvaluatorContextStatement(context);
    Stack<EvalFactoryNode> nodeStack = new Stack<EvalFactoryNode>();

    // detemine ordered tags
    Set<EvalFactoryNode> filterFactoryNodes = EvalNodeUtil.recursiveGetChildNodes(evalFactoryNode,
            FilterForFilterFactoryNodes.INSTANCE);
    LinkedHashSet<String> allTagNamesOrdered = new LinkedHashSet<String>();
    if (priorAllTags != null) {
        allTagNamesOrdered.addAll(priorAllTags);
    }
    for (EvalFactoryNode filterNode : filterFactoryNodes) {
        EvalFilterFactoryNode factory = (EvalFilterFactoryNode) filterNode;
        int tagNumber;
        if (factory.getEventAsName() != null) {
            if (!allTagNamesOrdered.contains(factory.getEventAsName())) {
                allTagNamesOrdered.add(factory.getEventAsName());
                tagNumber = allTagNamesOrdered.size() - 1;
            } else {
                tagNumber = findTagNumber(factory.getEventAsName(), allTagNamesOrdered);
            }
            factory.setEventAsTagNumber(tagNumber);
        }
    }

    recursiveCompile(evalFactoryNode, context, evaluatorContextStmt, eventTypeReferences, isInsertInto, tags,
            subexpressionIdStack, nodeStack, allTagNamesOrdered);

    Audit auditPattern = AuditEnum.PATTERN.getAudit(context.getAnnotations());
    Audit auditPatternInstance = AuditEnum.PATTERNINSTANCES.getAudit(context.getAnnotations());
    EvalFactoryNode compiledEvalFactoryNode = evalFactoryNode;
    if (auditPattern != null || auditPatternInstance != null) {
        EvalAuditInstanceCount instanceCount = new EvalAuditInstanceCount();
        compiledEvalFactoryNode = recursiveAddAuditNode(null, auditPattern != null,
                auditPatternInstance != null, evalFactoryNode, evalNodeExpressions, instanceCount);
    }

    return new PatternStreamSpecCompiled(compiledEvalFactoryNode, tags.getTaggedEventTypes(),
            tags.getArrayEventTypes(), allTagNamesOrdered, this.getViewSpecs(), this.getOptionalStreamName(),
            this.getOptions());
}

From source file:org.broadinstitute.gatk.utils.commandline.ParsingEngine.java

/**
 * Gets a collection of the container instances of the given type stored within the given target.
 * @param source Argument source.//from  w ww  . j  a  v a2  s .  c o m
 * @param instance Container.
 * @return A collection of containers matching the given argument source.
 */
private Collection<Object> findTargets(ArgumentSource source, Object instance) {
    LinkedHashSet<Object> targets = new LinkedHashSet<Object>();
    for (Class clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {
        for (Field field : clazz.getDeclaredFields()) {
            if (field.equals(source.field)) {
                targets.add(instance);
            } else if (field.isAnnotationPresent(ArgumentCollection.class)) {
                targets.addAll(findTargets(source, JVMUtils.getFieldValue(field, instance)));
            }
        }
    }
    return targets;
}

From source file:org.apache.marmotta.platform.security.services.SecurityServiceImpl.java

private Configuration loadProfile(String profile, LinkedHashSet<String> profiles) {
    URL securityConfigUrl = this.getClass().getClassLoader()
            .getResource("security-profile." + profile + ".properties");
    if (securityConfigUrl != null) {
        try {/*from   w  w  w. jav  a 2  s  .c o  m*/
            Configuration securityConfig = null;
            securityConfig = new PropertiesConfiguration(securityConfigUrl);

            if (securityConfig.containsKey("security.profile.base")) {
                final String baseP = securityConfig.getString("security.profile.base");
                if (profiles.contains(baseP)) {
                    log.warn("Cycle in security configuration detected: {} -> {}", profiles, baseP);
                    return securityConfig;
                } else {
                    profiles.add(baseP);
                    final Configuration baseProfile = loadProfile(baseP, profiles);

                    for (Iterator<String> keys = securityConfig.getKeys(); keys.hasNext();) {
                        String key = keys.next();

                        baseProfile.setProperty(key, securityConfig.getProperty(key));
                    }
                    return baseProfile;
                }
            } else {
                return securityConfig;
            }
        } catch (ConfigurationException e) {
            log.error("error parsing security-profile.{}.properties file at {}: {}",
                    new Object[] { profile, securityConfigUrl, e.getMessage() });
        }

    }
    return null;
}

From source file:annis.visualizers.iframe.partitur.PartiturVisualizer.java

@Override
public void writeOutput(VisualizerInput input, Writer writer) {
    try {/*from   w  ww .j  a v a  2 s .  co m*/

        nodes = input.getResult().getGraph().getNodes();
        token = input.getResult().getGraph().getTokens();

        // get partitur
        PartiturParser partitur = new PartiturParser(input.getResult().getGraph(), input.getNamespace());

        // check right to left
        boolean isRTL = checkRTL(input.getResult().getTokenList());

        List<String> tierNames = new LinkedList<String>(partitur.getKnownTiers());
        Collections.sort(tierNames);

        // get keys that are allowed to select
        LinkedHashSet<String> keys = new LinkedHashSet<String>();
        String mapping = input.getMappings().getProperty("annos");
        if (mapping == null) {
            // default to the alphabetical order
            keys.addAll(partitur.getNameslist());
        } else {
            String[] splitted = mapping.split(",");
            for (int k = 0; k < splitted.length; k++) {
                String s = splitted[k].trim();
                if (partitur.getNameslist().contains(s)) {
                    keys.add(s);
                }
            }
        }

        writer.append(
                "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
        writer.append("<link href=\"" + input.getResourcePath("jbar.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.tooltip.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("jquery.noty.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<link href=\"" + input.getResourcePath("partitur.css")
                + "\" rel=\"stylesheet\" type=\"text/css\" >");
        writer.append("<script src=\"" + input.getResourcePath("jquery-1.7.1.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.jbar.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.tooltip.min.js") + "\"></script>");
        writer.append("<script src=\"" + input.getResourcePath("jquery.noty.js") + "\"></script>");
        writer.append("<script>");
        writer.append(convertToJavacSriptArray(new LinkedList<String>()));
        writer.append("\nvar levelNames = [");
        int i = 0;
        for (String levelName : tierNames) {
            if (keys.contains(levelName)) {
                writer.append((i++ > 0 ? ", " : "") + "\"" + levelName + "\"");
            }
        }
        writer.append("];\n</script>");
        writer.append("<script type=\"text/javascript\" src=\"" + input.getResourcePath("PartiturVisualizer.js")
                + "\"></script>");

        writer.append("</head>");
        writer.append("<body>\n");

        writer.append("<ul id=\"toolbar\"></ul>");
        writer.append("<div id=\"partiture\">");

        if (isRTL) {
            writer.append("<table class=\"partitur_table\" dir=\"rtl\">\n");
        } else {
            writer.append("<table class=\"partitur_table\")\">\n");
        }

        for (String tier : keys) {
            List<String> indexlist = new ArrayList<String>();

            for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) {
                for (PartiturParser.ResultElement strr : span) {
                    if (strr.getName().equals(tier) && !indexlist.contains(strr.getId())) {
                        indexlist.add(strr.getId());
                    }
                }
            }

            String[] currentarray; //Saves annotation-ids of the current row

            while (!indexlist.isEmpty()) { //Create Rows until all Annotations fit in
                List<String> currentdontuselist = new LinkedList<String>(); //Lists all Annotations that should not be added to the current row
                writer.append("<tr class=\"level_" + tier + "\"><th>" + tier + "</th>"); //new row

                currentarray = new String[partitur.getResultlist().size()];
                for (int iterator3 = 0; iterator3 < partitur.getResultlist().size(); iterator3++) {
                    currentarray[iterator3] = null;
                }

                int spanCounter = 0;
                for (List<PartiturParser.ResultElement> span : partitur.getResultlist()) { //for each Token
                    for (PartiturParser.ResultElement annotationelement : span) { // for each Annotation annotationelement of that Token
                        if (indexlist.contains(annotationelement.getId())
                                && !currentdontuselist.contains(annotationelement.getId())) {
                            boolean neu = false; //Should the Annotation be added?
                            if (currentarray[spanCounter] == null) {
                                indexlist.remove(annotationelement.getId());
                                currentarray[spanCounter] = annotationelement.getId();
                                neu = true;
                            }
                            //get all other annotationelement.id (earlier Ids => dontuselist)
                            int span2Counter = 0;
                            for (List<PartiturParser.ResultElement> span2 : partitur.getResultlist()) {
                                for (PartiturParser.ResultElement strr2 : span2) {
                                    if (strr2.getId().equals(annotationelement.getId()) && neu) //{
                                    {
                                        if (currentarray[span2Counter] == null) {
                                            currentarray[span2Counter] = annotationelement.getId();
                                        }
                                    }
                                    if (span2Counter <= spanCounter
                                            && !currentdontuselist.contains(strr2.getId())) {
                                        currentdontuselist.add(strr2.getId());
                                    }
                                }
                                span2Counter++;
                            }
                            //break; //Not needed?
                        }
                    }
                    spanCounter++;
                }

                //Write Row
                int length = 1;
                for (int iterator5 = 0; iterator5 < currentarray.length; iterator5 += length) {
                    StringBuffer tokenIdsArray = new StringBuffer();
                    StringBuffer eventIdsArray = new StringBuffer();
                    boolean unused = true;
                    length = 1;
                    if (currentarray[iterator5] == null) { //empty entry
                        writer.append("<td></td>");
                    } else {
                        PartiturParser.ResultElement element = null;
                        HashSet<Integer> common = new HashSet<Integer>();
                        boolean found = false;
                        int outputSpanCounter = 0;
                        for (List<PartiturParser.ResultElement> outputSpan : partitur.getResultlist()) {
                            for (PartiturParser.ResultElement strr : outputSpan) {
                                if (strr.getId().equals(currentarray[iterator5])) {
                                    if (!found) {
                                        element = strr;
                                    }
                                    if (!common.contains(outputSpanCounter)) {
                                        common.add(outputSpanCounter);
                                    }
                                    found = true;
                                    if (unused) {
                                        tokenIdsArray.append("" + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray
                                                .append(tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                        unused = false;
                                    } else {
                                        tokenIdsArray.append("," + strr.getId() + "_" + outputSpanCounter);
                                        eventIdsArray.append(
                                                "," + tier + "_" + strr.getId() + "_" + outputSpanCounter);
                                    }
                                }
                            }
                            outputSpanCounter++;
                        }
                        for (int iterator7 = iterator5 + 1; iterator7 < currentarray.length; iterator7++) {
                            if (common.contains(iterator7)) {
                                length++;
                            } else {
                                break;
                            }
                        }

                        for (int iterator8 = 0; iterator8 < currentarray.length; iterator8++) {
                            if (common.contains(iterator8)) {
                                Long id = ((PartiturParser.Token) partitur.getToken().toArray()[iterator8])
                                        .getId();
                                if (unused) {
                                    tokenIdsArray.append("" + id);
                                    eventIdsArray.append(tier + "_" + id);
                                    unused = false;
                                } else {
                                    tokenIdsArray.append("," + id);
                                    eventIdsArray.append("," + tier + "_" + id);
                                }
                            }
                        }

                        String color = "black";
                        if (input.getMarkableExactMap().containsKey("" + element.getNodeId())) {
                            color = input.getMarkableExactMap().get("" + element.getNodeId());
                        }
                        if (found) {
                            writer.append("<td class=\"single_event\" " + "id=\"event_" + tier + "_"
                                    + element.getId() + "_" + iterator5 + "\" " + "style=\"color:" + color
                                    + ";\" " + "colspan=" + length + " " + "annis:tokenIds=\"" + tokenIdsArray
                                    + "\" " + "annis:eventIds=\"" + eventIdsArray + "\" " + "title=\""
                                    + partitur.namespaceForTier(tier) + ":" + tier + " = "
                                    + StringEscapeUtils.escapeXml(element.getValue()) + "\"  " //tier =tier, event.getValue()= element.name
                                    + "onMouseOver=\"toggleAnnotation(this, true);\" "
                                    + "onMouseOut=\"toggleAnnotation(this, false);\" "
                                    + addTimeAttribute(element.getNodeId()) + ">" + element.getValue()
                                    + "</td>");
                        } else {
                            writer.append("<td class=\"single_event\" >error</td>");
                        }
                    }
                }
                writer.append("</tr>"); //finish row
            }
        }

        // add token itself
        writer.append("<tr><th>tok</th>");

        for (PartiturParser.Token token : partitur.getToken()) {
            String color = "black";

            if (input.getMarkableExactMap().containsKey("" + token.getId())) {
                color = input.getMarkableExactMap().get("" + token.getId());
            }
            writer.append("<td class=\"tok\" style=\"color:" + color + ";\" " + "id=\"token_" + token.getId()
                    + "\" " + ">" + token.getValue() + "</td>");
        }
        writer.append("</tr>");

        writer.append("</table>\n");
        writer.append("</div>\n");
        writer.append("</body></html>");

    } catch (Exception ex) {
        log.error(null, ex);
        try {
            String annisLine = "";
            for (int i = 0; i < ex.getStackTrace().length; i++) {
                if (ex.getStackTrace()[i].getClassName().startsWith("annis.")) {
                    annisLine = ex.getStackTrace()[i].toString();
                }
            }

            writer.append("<html><body>Error occured (" + ex.getClass().getName() + "): "
                    + ex.getLocalizedMessage() + "<br/>" + annisLine + "</body></html>");
        } catch (IOException ex1) {
            log.error(null, ex1);
        }
    }
}

From source file:se.inera.certificate.web.security.saml.MetadataGenerator.java

/**
 * Method iterates all values in the input, for each tries to resolve correct alias. When alias value is found,
 * it is entered into the return collection, otherwise warning is logged. Values are returned in order of input
 * with all duplicities removed.// w  w  w.  j  a va 2  s  .  com
 *
 * @param values input collection
 * @return result with resolved aliases
 */
protected Collection<String> mapAliases(Collection<String> values) {
    LinkedHashSet<String> result = new LinkedHashSet<String>();
    for (String value : values) {
        String alias = aliases.get(value);
        if (alias != null) {
            result.add(alias);
        } else {
            LOGGER.warn("Unsupported value " + value + " found");
        }
    }
    return result;
}

From source file:com.alibaba.wasp.plan.parser.druid.DruidDDLParser.java

/**
 * Process Create Index Statement and generate Execute Plan
 * /* w w w. j  a  v a2s. co m*/
 */
private void getCreateIndexPlan(ParseContext context, WaspSqlCreateIndexStatement sqlCreateIndexStatement,
        MetaEventOperation metaEventOperation) throws IOException {

    // Index Name
    SQLName name = sqlCreateIndexStatement.getName();
    String indexName = parseName(name);
    metaEventOperation.isLegalIndexName(indexName);
    LOG.debug("Create Index SQL IndexName " + name);

    // Table Name
    SQLName table = sqlCreateIndexStatement.getTable();
    String tableName = parseName(table);
    LOG.debug("Create Index SQL TableName " + table);

    // check if table exists and get Table info
    FTable fTable = metaEventOperation.checkAndGetTable(tableName, true);

    // check the index not exists
    metaEventOperation.checkIndexNotExists(fTable, indexName);

    // Field
    List<SQLSelectOrderByItem> items = sqlCreateIndexStatement.getItems();
    LinkedHashSet<String> columns = new LinkedHashSet<String>(items.size());
    List<String> desc = new ArrayList<String>();
    for (SQLSelectOrderByItem item : items) {
        String columnName = parseName(item.getExpr());
        if (columns.contains(columnName)) {
            throw new UnsupportedException("Index have two same field '" + columnName + "'");
        } else {
            columns.add(columnName);
        }
        if (item.getType() == SQLOrderingSpecification.DESC) {
            desc.add(columnName);
        }
    }

    if (!metaEventOperation.isLegalDescFields(fTable, desc)) {
        throw new UnsupportedException("Currently we only support the ascending and descending time field.");
    }

    List<String> colList = new ArrayList<String>();
    colList.addAll(columns);
    if (metaEventOperation.arePrimaryKeys(fTable, colList)) {
        throw new UnsupportedException("Index keys is Primary Keys.");
    }
    if (metaEventOperation.containPrimaryKeys(fTable, colList)) {
        throw new UnsupportedException("Index keys contain all Primary Keys.");
    }

    LinkedHashMap<String, Field> indexKeys = metaEventOperation.checkAndGetFields(fTable, columns);
    // Check the indexKeys whether have Duplicate column name
    metaEventOperation.areLegalTableColumns(null, indexKeys.values());

    Index index = new Index(indexName, tableName, indexKeys);
    // Check if two index have the same columns and the same columns order
    metaEventOperation.checkTwoIndexWithSameColumn(fTable, index);

    index.setDesc(desc);
    index.setStoring(parse(sqlCreateIndexStatement.getStoringCols(), fTable.getColumns()));
    CreateIndexPlan createIndexPlan = new CreateIndexPlan(index);

    context.setPlan(createIndexPlan);
    LOG.debug("CreateIndexPlan " + createIndexPlan.toString());
}