Example usage for com.google.common.collect ListMultimap get

List of usage examples for com.google.common.collect ListMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect ListMultimap get.

Prototype

@Override
List<V> get(@Nullable K key);

Source Link

Document

Because the values for a given key may have duplicates and follow the insertion ordering, this method returns a List , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.floragunn.searchguard.configuration.PrivilegesEvaluator.java

public boolean evaluate(final User user, final String action, final ActionRequest<?> request) {

    if (action.startsWith("cluster:admin/snapshot/restore")) {
        auditLog.logMissingPrivileges(action, request);
        log.warn(action + " is not allowed for a regular user");
        return false;
    }//from  ww  w. ja  v a2s  .  c o  m

    final TransportAddress caller = Objects
            .requireNonNull((TransportAddress) request.getFromContext(ConfigConstants.SG_REMOTE_ADDRESS));

    if (log.isDebugEnabled()) {
        log.debug("evaluate permissions for {}", user);
        log.debug("requested {} from {}", action, caller);
    }

    final ClusterState clusterState = clusterService.state();
    final MetaData metaData = clusterState.metaData();
    final Tuple<Set<String>, Set<String>> requestedResolvedAliasesIndicesTypes = resolve(user, action, request,
            metaData);

    final Set<String> requestedResolvedIndices = Collections
            .unmodifiableSet(requestedResolvedAliasesIndicesTypes.v1());
    final Set<IndexType> requestedResolvedIndexTypes;

    {
        final Set<IndexType> requestedResolvedIndexTypes0 = new HashSet<IndexType>(
                requestedResolvedAliasesIndicesTypes.v1().size()
                        * requestedResolvedAliasesIndicesTypes.v2().size());

        for (String index : requestedResolvedAliasesIndicesTypes.v1()) {
            for (String type : requestedResolvedAliasesIndicesTypes.v2()) {
                requestedResolvedIndexTypes0.add(new IndexType(index, type));
            }
        }

        requestedResolvedIndexTypes = Collections.unmodifiableSet(requestedResolvedIndexTypes0);
    }

    if (log.isDebugEnabled()) {
        log.debug("requested resolved indextypes: {}", requestedResolvedIndexTypes);
    }

    if (requestedResolvedIndices.contains(searchguardIndex)
            && WildcardMatcher.matchAny(deniedActionPatterns, action)) {
        auditLog.logSgIndexAttempt(request, action);
        log.warn(action + " for '{}' index is not allowed for a regular user", searchguardIndex);
        return false;
    }

    if (requestedResolvedIndices.contains("_all") && WildcardMatcher.matchAny(deniedActionPatterns, action)) {
        auditLog.logSgIndexAttempt(request, action);
        log.warn(action + " for '_all' indices is not allowed for a regular user");
        return false;
    }

    if (requestedResolvedIndices.contains(searchguardIndex) || requestedResolvedIndices.contains("_all")) {

        if (request instanceof SearchRequest) {
            ((SearchRequest) request).requestCache(Boolean.FALSE);
            if (log.isDebugEnabled()) {
                log.debug("Disable search request cache for this request");
            }
        }

        if (request instanceof RealtimeRequest) {
            ((RealtimeRequest) request).realtime(Boolean.FALSE);
            if (log.isDebugEnabled()) {
                log.debug("Disable realtime for this request");
            }
        }
    }

    final Set<String> sgRoles = mapSgRoles(user, caller);

    if (log.isDebugEnabled()) {
        log.debug("mapped roles for {}: {}", user.getName(), sgRoles);
    }

    if (privilegesInterceptor.getClass() != PrivilegesInterceptor.class) {

        final boolean denyRequest = privilegesInterceptor.replaceKibanaIndex(request, action, user, config,
                requestedResolvedIndices, mapTenants(user, caller));

        if (denyRequest) {
            auditLog.logMissingPrivileges(action, request);
            return false;
        }
    }

    boolean allowAction = false;

    final Map<String, Set<String>> dlsQueries = new HashMap<String, Set<String>>();
    final Map<String, Set<String>> flsFields = new HashMap<String, Set<String>>();

    final Set<IndexType> leftovers = new HashSet<PrivilegesEvaluator.IndexType>();

    for (final Iterator<String> iterator = sgRoles.iterator(); iterator.hasNext();) {
        final String sgRole = (String) iterator.next();
        final Settings sgRoleSettings = roles.getByPrefix(sgRole);

        if (sgRoleSettings.names().isEmpty()) {

            if (log.isDebugEnabled()) {
                log.debug("sg_role {} is empty", sgRole);
            }

            continue;
        }

        if (log.isDebugEnabled()) {
            log.debug("---------- evaluate sg_role: {}", sgRole);
        }

        final boolean compositeEnabled = config.getAsBoolean("searchguard.dynamic.composite_enabled", false);

        if (action.startsWith("cluster:") || action.startsWith("indices:admin/template/delete")
                || action.startsWith("indices:admin/template/get")
                || action.startsWith("indices:admin/template/put")
                || action.startsWith("indices:data/read/scroll")
                //M*
                || (compositeEnabled && action.equals(BulkAction.NAME))
                || (compositeEnabled && action.equals(IndicesAliasesAction.NAME))
                || (compositeEnabled && action.equals(MultiGetAction.NAME))
                || (compositeEnabled && action.equals(MultiPercolateAction.NAME))
                || (compositeEnabled && action.equals(MultiSearchAction.NAME))
                || (compositeEnabled && action.equals(MultiTermVectorsAction.NAME))
                || (compositeEnabled && action.equals("indices:data/read/coordinate-msearch"))
        //|| (compositeEnabled && action.startsWith(MultiPercolateAction.NAME))
        ) {

            final Set<String> resolvedActions = resolveActions(
                    sgRoleSettings.getAsArray(".cluster", new String[0]));

            if (log.isDebugEnabled()) {
                log.debug("  resolved cluster actions:{}", resolvedActions);
            }

            if (WildcardMatcher.matchAny(resolvedActions.toArray(new String[0]), action)) {
                if (log.isDebugEnabled()) {
                    log.debug("  found a match for '{}' and {}, skip other roles", sgRole, action);
                }
                return true;
            } else {
                //check other roles #108
                if (log.isDebugEnabled()) {
                    log.debug("  not match found a match for '{}' and {}, check next role", sgRole, action);
                }
                continue;
            }
        }

        final Map<String, Settings> permittedAliasesIndices0 = sgRoleSettings.getGroups(".indices");
        final Map<String, Settings> permittedAliasesIndices = new HashMap<String, Settings>(
                permittedAliasesIndices0.size());

        for (String origKey : permittedAliasesIndices0.keySet()) {
            permittedAliasesIndices.put(
                    origKey.replace("${user.name}", user.getName()).replace("${user_name}", user.getName()),
                    permittedAliasesIndices0.get(origKey));
        }

        /*
        sg_role_starfleet:
        indices:
        sf: #<--- is an alias or cindex, can contain wildcards, will be resolved to concrete indices
        # if this contain wildcards we do a wildcard based check
        # if contains no wildcards we resolve this to concrete indices an do a exact check
        #
                
        ships:  <-- is a type, can contain wildcards
        - READ
        public:
        - 'indices:*'
        students:
        - READ
        alumni:
        - READ
        'admin*':
        - READ
        'pub*':
        '*':
        - READ
         */

        final ListMultimap<String, String> resolvedRoleIndices = Multimaps
                .synchronizedListMultimap(ArrayListMultimap.<String, String>create());

        final Set<IndexType> _requestedResolvedIndexTypes = new HashSet<IndexType>(requestedResolvedIndexTypes);
        //iterate over all beneath indices:
        permittedAliasesIndices: for (final String permittedAliasesIndex : permittedAliasesIndices.keySet()) {

            //final Map<String, Settings> permittedTypes = sgRoleSettings.getGroups(".indices."+permittedAliasesIndex);

            //System.out.println(permittedTypes);

            if (WildcardMatcher.containsWildcard(permittedAliasesIndex)) {
                if (log.isDebugEnabled()) {
                    log.debug("  Try wildcard match for {}", permittedAliasesIndex);
                }

                handleIndicesWithWildcard(action, permittedAliasesIndex, permittedAliasesIndices,
                        requestedResolvedIndexTypes, _requestedResolvedIndexTypes, requestedResolvedIndices);

            } else {
                if (log.isDebugEnabled()) {
                    log.debug("  Resolve and match {}", permittedAliasesIndex);
                }

                handleIndicesWithoutWildcard(action, permittedAliasesIndex, permittedAliasesIndices,
                        requestedResolvedIndexTypes, _requestedResolvedIndexTypes);
            }

            if (log.isDebugEnabled()) {
                log.debug("For index {} remaining requested indextype: {}", permittedAliasesIndex,
                        _requestedResolvedIndexTypes);
            }

            if (_requestedResolvedIndexTypes.isEmpty()) {

                int filteredAliasCount = 0;

                //check filtered aliases
                for (String requestAliasOrIndex : requestedResolvedIndices) {

                    //System.out.println(clusterState.metaData().getAliasAndIndexLookup().get(requestAliasOrIndex));
                    IndexMetaData indexMetaData = clusterState.metaData().getIndices().get(requestAliasOrIndex);

                    if (indexMetaData == null) {
                        log.warn("{} does not exist in cluster metadata", requestAliasOrIndex);
                        continue;
                    }

                    ImmutableOpenMap<String, AliasMetaData> aliases = indexMetaData.getAliases();

                    log.debug("Aliases for {}: {}", requestAliasOrIndex, aliases);

                    if (aliases != null && aliases.size() > 0) {

                        UnmodifiableIterator<String> it = aliases.keysIt();
                        while (it.hasNext()) {
                            String a = it.next();
                            AliasMetaData aliasMetaData = aliases.get(a);

                            if (aliasMetaData != null && aliasMetaData.filteringRequired()) {
                                filteredAliasCount++;
                                log.debug(a + " is a filtered alias " + aliasMetaData.getFilter());
                            } else {
                                log.debug(a + " is not an alias or does not have a filter");
                            }

                        }

                    }
                }

                if (filteredAliasCount > 1) {
                    //TODO add queries as dls queries (works only if dls module is installed)
                    log.warn(
                            "More than one ({}) filtered alias found for same index ({}). This is currently not supported",
                            filteredAliasCount, permittedAliasesIndex);
                    continue permittedAliasesIndices;
                }

                if (log.isDebugEnabled()) {
                    log.debug("found a match for '{}.{}', evaluate other roles", sgRole, permittedAliasesIndex);
                }

                resolvedRoleIndices.put(sgRole, permittedAliasesIndex);
            }

        } // end loop permittedAliasesIndices

        if (!resolvedRoleIndices.isEmpty()) {
            for (String resolvedRole : resolvedRoleIndices.keySet()) {
                for (String indexPattern : resolvedRoleIndices.get(resolvedRole)) {
                    String dls = roles.get(resolvedRole + ".indices." + indexPattern + "._dls_");
                    final String[] fls = roles.getAsArray(resolvedRole + ".indices." + indexPattern + "._fls_");

                    //only when dls and fls != null
                    String[] concreteIndices = new String[0];

                    if ((dls != null && dls.length() > 0) || (fls != null && fls.length > 0)) {
                        concreteIndices = resolver.concreteIndices(clusterService.state(),
                                DEFAULT_INDICES_OPTIONS/*??*/, indexPattern);
                    }

                    if (dls != null && dls.length() > 0) {

                        //TODO use UserPropertyReplacer, make it registerable for ldap user
                        dls = dls.replace("${user.name}", user.getName()).replace("${user_name}",
                                user.getName());

                        if (dlsQueries.containsKey(indexPattern)) {
                            dlsQueries.get(indexPattern).add(dls);
                        } else {
                            dlsQueries.put(indexPattern, new HashSet<String>());
                            dlsQueries.get(indexPattern).add(dls);
                        }

                        for (int i = 0; i < concreteIndices.length; i++) {
                            final String ci = concreteIndices[i];
                            if (dlsQueries.containsKey(ci)) {
                                dlsQueries.get(ci).add(dls);
                            } else {
                                dlsQueries.put(ci, new HashSet<String>());
                                dlsQueries.get(ci).add(dls);
                            }
                        }

                        if (log.isDebugEnabled()) {
                            log.debug("dls query {} for {}", dls, Arrays.toString(concreteIndices));
                        }

                    }

                    if (fls != null && fls.length > 0) {

                        if (flsFields.containsKey(indexPattern)) {
                            flsFields.get(indexPattern).addAll(Sets.newHashSet(fls));
                        } else {
                            flsFields.put(indexPattern, new HashSet<String>());
                            flsFields.get(indexPattern).addAll(Sets.newHashSet(fls));
                        }

                        for (int i = 0; i < concreteIndices.length; i++) {
                            final String ci = concreteIndices[i];
                            if (flsFields.containsKey(ci)) {
                                flsFields.get(ci).addAll(Sets.newHashSet(fls));
                            } else {
                                flsFields.put(ci, new HashSet<String>());
                                flsFields.get(ci).addAll(Sets.newHashSet(fls));
                            }
                        }

                        if (log.isDebugEnabled()) {
                            log.debug("fls fields {} for {}", Sets.newHashSet(fls),
                                    Arrays.toString(concreteIndices));
                        }

                    }

                }
            }

            allowAction = true;
        }

        leftovers.addAll(_requestedResolvedIndexTypes);

    } // end sg role loop

    if (!allowAction && log.isInfoEnabled()) {
        log.info("No perm match for {} {} [Action [{}]] [RolesChecked {}]", user, requestedResolvedIndexTypes,
                action, sgRoles);
    }

    if (!dlsQueries.isEmpty()) {
        request.putHeader(ConfigConstants.SG_DLS_QUERY,
                Base64Helper.serializeObject((Serializable) dlsQueries));
    }

    if (!flsFields.isEmpty()) {
        request.putHeader(ConfigConstants.SG_FLS_FIELDS,
                Base64Helper.serializeObject((Serializable) flsFields));
    }

    if (!allowAction && privilegesInterceptor.getClass() != PrivilegesInterceptor.class) {
        return privilegesInterceptor.replaceAllowedIndices(request, action, user, config, leftovers);
    }

    return allowAction;
}

From source file:com.samskivert.depot.impl.DepotMarshaller.java

/**
 * Creates a marshaller for the specified persistent object class.
 *///from w  ww  .  j  av a2s .  co  m
public DepotMarshaller(Class<T> pClass, PersistenceContext context) {
    _pClass = pClass;

    checkArgument(!java.lang.reflect.Modifier.isAbstract(pClass.getModifiers()),
            "Can't handle reference to abstract record: " + pClass.getName());

    Entity entity = pClass.getAnnotation(Entity.class);

    // see if this is a computed entity
    _computed = pClass.getAnnotation(Computed.class);
    if (_computed == null) {
        // if not, this class has a corresponding SQL table
        _tableName = DepotUtil.justClassName(_pClass);

        // see if there are Entity values specified
        if (entity != null) {
            if (entity.name().length() > 0) {
                _tableName = entity.name();
            }
        }
    }

    // if the entity defines a new TableGenerator, map that in our static table as those are
    // shared across all entities
    TableGenerator generator = pClass.getAnnotation(TableGenerator.class);
    if (generator != null) {
        context.tableGenerators.put(generator.name(), generator);
    }

    boolean seenIdentityGenerator = false;

    // introspect on the class and create marshallers and indices for persistent fields
    List<ColumnExp<?>> fields = Lists.newArrayList();
    ListMultimap<String, IndexDesc> namedFieldIndices = ArrayListMultimap.create();
    ListMultimap<String, IndexDesc> uniqueNamedFieldIndices = ArrayListMultimap.create();
    for (Field field : _pClass.getFields()) {
        int mods = field.getModifiers();

        // check for a static constant schema version
        if (java.lang.reflect.Modifier.isStatic(mods) && field.getName().equals(SCHEMA_VERSION_FIELD)) {
            try {
                _schemaVersion = (Integer) field.get(null);
            } catch (Exception e) {
                log.warning("Failed to read schema version", "class", pClass, e);
            }
        }

        // the field must be public, non-static and non-@Transient
        if (!java.lang.reflect.Modifier.isPublic(mods) || java.lang.reflect.Modifier.isStatic(mods)
                || field.getAnnotation(Transient.class) != null) {
            continue;
        }

        FieldMarshaller<?> fm = FieldMarshaller.createMarshaller(field);
        _fields.put(field.getName(), fm);
        ColumnExp<?> fieldColumn = new ColumnExp<Object>(_pClass, field.getName());
        fields.add(fieldColumn);

        // check to see if this is our primary key
        if (field.getAnnotation(Id.class) != null) {
            _pkColumns.add(fm);
        }

        // check if this field defines a new TableGenerator
        generator = field.getAnnotation(TableGenerator.class);
        if (generator != null) {
            context.tableGenerators.put(generator.name(), generator);
        }

        // check if this field is auto-generated
        GeneratedValue gv = fm.getGeneratedValue();
        if (gv != null) {
            // we can only do this on numeric fields
            Class<?> ftype = field.getType();
            boolean isNumeric = (ftype.equals(Byte.TYPE) || ftype.equals(Byte.class) || ftype.equals(Short.TYPE)
                    || ftype.equals(Short.class) || ftype.equals(Integer.TYPE) || ftype.equals(Integer.class)
                    || ftype.equals(Long.TYPE) || ftype.equals(Long.class));
            checkArgument(isNumeric, "Cannot use @GeneratedValue on non-numeric column: %s", field.getName());
            switch (gv.strategy()) {
            case AUTO:
            case IDENTITY:
                checkArgument(!seenIdentityGenerator,
                        "Persistent records can have at " + "most one AUTO/IDENTITY generator.");
                _valueGenerators.put(field.getName(), new IdentityValueGenerator(gv, this, fm));
                seenIdentityGenerator = true;
                break;

            case TABLE:
                String name = gv.generator();
                generator = context.tableGenerators.get(name);
                checkArgument(generator != null, "Unknown generator [generator=" + name + "]");
                _valueGenerators.put(field.getName(), new TableValueGenerator(generator, gv, this, fm));
                break;

            case SEQUENCE: // TODO
                throw new IllegalArgumentException("SEQUENCE key generation strategy not yet supported.");
            }
        }

        // check whether this field is indexed
        Index index = field.getAnnotation(Index.class);
        if (index != null) {
            Column column = field.getAnnotation(Column.class);
            checkArgument(column == null || !column.unique(),
                    "Unique columns are implicitly indexed and should not be @Index'd.");

            String name = index.name().equals("") ? field.getName() + "Index" : index.name();
            IndexDesc entry = new IndexDesc(fieldColumn, Order.ASC);
            if (index.unique()) {
                checkArgument(!namedFieldIndices.containsKey(index.name()),
                        "All @Index for a particular name must be unique or non-unique");
                uniqueNamedFieldIndices.put(name, entry);
            } else {
                checkArgument(!uniqueNamedFieldIndices.containsKey(index.name()),
                        "All @Index for a particular name must be unique or non-unique");
                namedFieldIndices.put(name, entry);
            }
        }
    }

    for (String indexName : namedFieldIndices.keySet()) {
        _indexes.add(buildIndex(indexName, false, namedFieldIndices.get(indexName)));
    }
    for (String indexName : uniqueNamedFieldIndices.keySet()) {
        _indexes.add(buildIndex(indexName, true, uniqueNamedFieldIndices.get(indexName)));
    }

    // if we did not find a schema version field, freak out (but not for computed records, for
    // whom there is no table)
    if (_tableName != null && _schemaVersion <= 0) {
        throw new IllegalStateException(
                pClass.getName() + "." + SCHEMA_VERSION_FIELD + " must be greater than zero.");
    }

    // generate our full list of fields/columns for use in queries
    _allFields = fields.toArray(new ColumnExp<?>[fields.size()]);

    // now check for @Entity annotations on the entire superclass chain
    Class<? extends PersistentRecord> iterClass = pClass.asSubclass(PersistentRecord.class);
    do {
        entity = iterClass.getAnnotation(Entity.class);
        if (entity != null) {
            // add any indices needed for uniqueness constraints
            for (UniqueConstraint constraint : entity.uniqueConstraints()) {
                ColumnExp<?>[] colExps = new ColumnExp<?>[constraint.fields().length];
                int ii = 0;
                for (String field : constraint.fields()) {
                    FieldMarshaller<?> fm = _fields.get(field);
                    checkArgument(fm != null, "Unknown unique constraint field: " + field);
                    colExps[ii++] = new ColumnExp<Object>(_pClass, field);
                }
                _indexes.add(buildIndex(constraint.name(), true, colExps));
            }

            // add any explicit multicolumn or complex indices
            for (Index index : entity.indices()) {
                _indexes.add(buildIndex(index.name(), index.unique()));
            }

            // note any FTS indices
            for (FullTextIndex fti : entity.fullTextIndices()) {
                if (_fullTextIndexes.containsKey(fti.name())) {
                    continue;
                }
                _fullTextIndexes.put(fti.name(), fti);
            }
        }

        iterClass = iterClass.getSuperclass().asSubclass(PersistentRecord.class);

    } while (PersistentRecord.class.isAssignableFrom(iterClass) && !PersistentRecord.class.equals(iterClass));
}

From source file:ca.sqlpower.architect.swingui.TablePane.java

/**
 * Inserts the list of SQLObjects into this table at the specified location.
 *
 * @param items A list of SQLTable and/or SQLColumn objects.  Other types are not allowed.
 * @param insertionPoint The position that the first item in the item list should go into.
 * This can be a nonnegative integer to specify a position in the column list, or one
 * of the constants COLUMN_INDEX_END_OF_PK or COLUMN_INDEX_START_OF_NON_PK to indicate a special position.
 * @return True if the insert worked; false otherwise
 * @throws SQLObjectException If there are problems in the business model
 *///w  w w.j a  va  2 s.c o  m
public boolean insertObjects(List<? extends SQLObject> items, int insertionPoint, boolean deleteSource)
        throws SQLObjectException {
    boolean newColumnsInPk = false;
    if (insertionPoint == COLUMN_INDEX_END_OF_PK) {
        insertionPoint = getModel().getPkSize();
        newColumnsInPk = true;
    } else if (insertionPoint == COLUMN_INDEX_START_OF_NON_PK) {
        insertionPoint = getModel().getPkSize();
        newColumnsInPk = false;
    } else if (insertionPoint == ITEM_INDEX_TITLE) {
        insertionPoint = 0;
        newColumnsInPk = true;
    } else if (insertionPoint < 0) {
        insertionPoint = getModel().getColumns().size();
        newColumnsInPk = false;
    } else if (insertionPoint < getModel().getPkSize()) {
        newColumnsInPk = true;
    }

    ListMultimap<String, SQLColumn> newColumns = ArrayListMultimap.create();

    for (int i = items.size() - 1; i >= 0; i--) {
        SQLObject someData = items.get(i);
        DuplicateProperties duplicateProperties = ASUtils
                .createDuplicateProperties(getParent().getPlayPen().getSession(), someData);
        logger.debug("insertObjects: got item of type " + someData.getClass().getName()); //$NON-NLS-1$
        if (someData instanceof SQLTable) {
            SQLTable table = (SQLTable) someData;
            newColumns.putAll(table.getParentDatabase().getDataSource().getParentType().getName(),
                    getModel().inherit(insertionPoint, table, duplicateProperties.getDefaultTransferStyle(),
                            duplicateProperties.isPreserveColumnSource()));
            for (SQLColumn column : table.getColumns()) {
                SQLColumn targetCol = getModel().getColumnByName(column.getName());
                ASUtils.correctSourceColumn(column, duplicateProperties, targetCol,
                        getPlayPen().getSession().getDBTree());
            }
        } else if (someData instanceof SQLColumn) {
            SQLColumn col = (SQLColumn) someData;
            if (deleteSource) {
                if (col.getParent() == getModel()) {
                    // moving column inside the same table
                    int oldIndex = col.getParent().getColumns().indexOf(col);
                    if (insertionPoint > oldIndex) {
                        insertionPoint--;
                    }
                    getModel().changeColumnIndex(oldIndex, insertionPoint, newColumnsInPk);
                } else if (col.getParent().getParentDatabase() == getModel().getParentDatabase()) {
                    // moving column within playpen

                    try {
                        getModel().begin("Moving column " + col.getName() + " to table " + getName());
                        InsertionPointWatcher<SQLTable> ipWatcher = new InsertionPointWatcher<SQLTable>(
                                getModel(), insertionPoint, SQLColumn.class);
                        col.getParent().removeColumn(col);
                        ipWatcher.dispose();

                        if (logger.isDebugEnabled()) {
                            logger.debug("Moving column '" + col.getName() //$NON-NLS-1$
                                    + "' to table '" + getModel().getName() //$NON-NLS-1$
                                    + "' at position " + ipWatcher.getInsertionPoint()); //$NON-NLS-1$
                        }
                        getModel().addColumn(col, newColumnsInPk, ipWatcher.getInsertionPoint());
                        getModel().commit();
                    } catch (RuntimeException e) {
                        getModel().rollback(e.getMessage());
                        throw e;
                    }
                    // You need to disable the normalization otherwise it goes around
                    // the property change events and causes undo to fail when dragging
                    // into the primary key of a table
                    logger.debug("Column listeners are " + col.getSPListeners());

                } else {
                    // importing column from a source database
                    newColumns.put(
                            col.getParent().getParentDatabase().getDataSource().getParentType().getName(),
                            getModel().inherit(insertionPoint, col, newColumnsInPk,
                                    duplicateProperties.getDefaultTransferStyle(),
                                    duplicateProperties.isPreserveColumnSource()));
                    if (logger.isDebugEnabled())
                        logger.debug("Inherited " + col.getName() + " to table with precision " //$NON-NLS-1$//$NON-NLS-2$
                                + col.getPrecision());
                }

            } else {
                newColumns.put(col.getParent().getParentDatabase().getDataSource().getParentType().getName(),
                        getModel().inherit(insertionPoint, col, newColumnsInPk,
                                duplicateProperties.getDefaultTransferStyle(),
                                duplicateProperties.isPreserveColumnSource()));
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Inherited " + col.getName() + " to table with precision " + col.getPrecision()); //$NON-NLS-1$ //$NON-NLS-2$
                ASUtils.correctSourceColumn(col, duplicateProperties, getModel().getColumnByName(col.getName()),
                        getPlayPen().getSession().getDBTree());
            }
        } else {
            return false;
        }
    }

    DataSourceCollection<SPDataSource> dsCollection = getModel().getParentDatabase().getDataSource()
            .getParentCollection();
    for (String platform : newColumns.keySet()) {
        SQLColumn.assignTypes(newColumns.get(platform), dsCollection, platform == null ? "" : platform,
                getPlayPen().getSession());
    }
    return true;
}

From source file:com.google.devtools.build.lib.rules.cpp.CppConfiguration.java

protected CppConfiguration(CppConfigurationParameters params) throws InvalidConfigurationException {
    CrosstoolConfig.CToolchain toolchain = params.toolchain;
    cppOptions = params.cppOptions;//from   w  ww . ja va  2 s.c  o  m
    this.hostSystemName = toolchain.getHostSystemName();
    this.compiler = toolchain.getCompiler();
    this.targetCpu = toolchain.getTargetCpu();
    this.lipoMode = cppOptions.getLipoMode();
    this.targetSystemName = toolchain.getTargetSystemName();
    this.targetLibc = toolchain.getTargetLibc();
    this.targetOS = toolchain.getCcTargetOs();
    this.crosstoolTop = params.crosstoolTop;
    this.ccToolchainLabel = params.ccToolchainLabel;
    this.compilationMode = params.commonOptions.compilationMode;
    this.useLLVMCoverageMap = params.commonOptions.useLLVMCoverageMapFormat;
    this.lipoContextCollector = cppOptions.lipoCollector;

    this.crosstoolTopPathFragment = crosstoolTop.getPackageIdentifier().getPathUnderExecRoot();

    try {
        this.staticRuntimeLibsLabel = crosstoolTop
                .getRelative(toolchain.hasStaticRuntimesFilegroup() ? toolchain.getStaticRuntimesFilegroup()
                        : "static-runtime-libs-" + targetCpu);
        this.dynamicRuntimeLibsLabel = crosstoolTop
                .getRelative(toolchain.hasDynamicRuntimesFilegroup() ? toolchain.getDynamicRuntimesFilegroup()
                        : "dynamic-runtime-libs-" + targetCpu);
    } catch (LabelSyntaxException e) {
        // All of the above label.getRelative() calls are valid labels, and the crosstool_top
        // was already checked earlier in the process.
        throw new AssertionError(e);
    }

    if (cppOptions.lipoMode == LipoMode.BINARY) {
        // TODO(bazel-team): implement dynamic linking with LIPO
        this.dynamicMode = DynamicMode.OFF;
    } else {
        switch (cppOptions.dynamicMode) {
        case DEFAULT:
            this.dynamicMode = DynamicMode.DEFAULT;
            break;
        case OFF:
            this.dynamicMode = DynamicMode.OFF;
            break;
        case FULLY:
            this.dynamicMode = DynamicMode.FULLY;
            break;
        default:
            throw new IllegalStateException("Invalid dynamicMode.");
        }
    }

    this.fdoZip = params.fdoZip;
    this.stripBinaries = (cppOptions.stripBinaries == StripMode.ALWAYS
            || (cppOptions.stripBinaries == StripMode.SOMETIMES
                    && compilationMode == CompilationMode.FASTBUILD));

    CrosstoolConfigurationIdentifier crosstoolConfig = CrosstoolConfigurationIdentifier
            .fromToolchain(toolchain);
    Preconditions.checkState(crosstoolConfig.getCpu().equals(targetCpu));
    Preconditions.checkState(crosstoolConfig.getCompiler().equals(compiler));
    Preconditions.checkState(crosstoolConfig.getLibc().equals(targetLibc));

    this.solibDirectory = "_solib_" + targetCpu;

    this.toolchainIdentifier = toolchain.getToolchainIdentifier();

    toolchain = addLegacyFeatures(toolchain);
    this.toolchainFeatures = new CcToolchainFeatures(toolchain);
    this.supportsGoldLinker = toolchain.getSupportsGoldLinker();
    this.supportsStartEndLib = toolchain.getSupportsStartEndLib();
    this.supportsInterfaceSharedObjects = toolchain.getSupportsInterfaceSharedObjects();
    this.supportsEmbeddedRuntimes = toolchain.getSupportsEmbeddedRuntimes();
    this.supportsFission = toolchain.getSupportsFission();
    this.toolchainNeedsPic = toolchain.getNeedsPic();
    this.usePicForBinaries = toolchain.getNeedsPic() && compilationMode != CompilationMode.OPT;

    this.toolPaths = Maps.newHashMap();
    for (CrosstoolConfig.ToolPath tool : toolchain.getToolPathList()) {
        PathFragment path = new PathFragment(tool.getPath());
        if (!path.isNormalized()) {
            throw new IllegalArgumentException("The include path '" + tool.getPath() + "' is not normalized.");
        }
        toolPaths.put(tool.getName(), crosstoolTopPathFragment.getRelative(path));
    }

    if (toolPaths.isEmpty()) {
        // If no paths are specified, we just use the names of the tools as the path.
        for (Tool tool : Tool.values()) {
            toolPaths.put(tool.getNamePart(), crosstoolTopPathFragment.getRelative(tool.getNamePart()));
        }
    } else {
        Iterable<Tool> neededTools = Iterables.filter(EnumSet.allOf(Tool.class), new Predicate<Tool>() {
            @Override
            public boolean apply(Tool tool) {
                if (tool == Tool.DWP) {
                    // When fission is unsupported, don't check for the dwp tool.
                    return supportsFission();
                } else if (tool == Tool.GCOVTOOL || tool == Tool.OBJCOPY) {
                    // gcov-tool and objcopy are optional, don't check whether they're present
                    return false;
                } else {
                    return true;
                }
            }
        });
        for (Tool tool : neededTools) {
            if (!toolPaths.containsKey(tool.getNamePart())) {
                throw new IllegalArgumentException("Tool path for '" + tool.getNamePart() + "' is missing");
            }
        }
    }

    ListMultimap<CompilationMode, String> cFlags = ArrayListMultimap.create();
    ListMultimap<CompilationMode, String> cxxFlags = ArrayListMultimap.create();
    linkOptionsFromCompilationMode = ArrayListMultimap.create();
    for (CrosstoolConfig.CompilationModeFlags flags : toolchain.getCompilationModeFlagsList()) {
        // Remove this when CROSSTOOL files no longer contain 'coverage'.
        if (flags.getMode() == CrosstoolConfig.CompilationMode.COVERAGE) {
            continue;
        }
        CompilationMode realmode = importCompilationMode(flags.getMode());
        cFlags.putAll(realmode, flags.getCompilerFlagList());
        cxxFlags.putAll(realmode, flags.getCxxFlagList());
        linkOptionsFromCompilationMode.putAll(realmode, flags.getLinkerFlagList());
    }

    ListMultimap<LipoMode, String> lipoCFlags = ArrayListMultimap.create();
    ListMultimap<LipoMode, String> lipoCxxFlags = ArrayListMultimap.create();
    linkOptionsFromLipoMode = ArrayListMultimap.create();
    for (CrosstoolConfig.LipoModeFlags flags : toolchain.getLipoModeFlagsList()) {
        LipoMode realmode = flags.getMode();
        lipoCFlags.putAll(realmode, flags.getCompilerFlagList());
        lipoCxxFlags.putAll(realmode, flags.getCxxFlagList());
        linkOptionsFromLipoMode.putAll(realmode, flags.getLinkerFlagList());
    }

    linkOptionsFromLinkingMode = ArrayListMultimap.create();

    // If a toolchain supports dynamic libraries at all, there must be at least one
    // of the following:
    // - a "DYNAMIC" section in linking_mode_flags (even if no flags are needed)
    // - a non-empty list in one of the dynamicLibraryLinkerFlag fields
    // If none of the above contain data, then the toolchain can't do dynamic linking.
    boolean haveDynamicMode = false;

    for (LinkingModeFlags flags : toolchain.getLinkingModeFlagsList()) {
        LinkingMode realmode = importLinkingMode(flags.getMode());
        if (realmode == LinkingMode.DYNAMIC) {
            haveDynamicMode = true;
        }
        linkOptionsFromLinkingMode.putAll(realmode, flags.getLinkerFlagList());
    }

    this.commonLinkOptions = ImmutableList.copyOf(toolchain.getLinkerFlagList());
    List<String> linkerFlagList = toolchain.getDynamicLibraryLinkerFlagList();
    List<CToolchain.OptionalFlag> optionalLinkerFlagList = toolchain.getOptionalDynamicLibraryLinkerFlagList();
    if (!linkerFlagList.isEmpty() || !optionalLinkerFlagList.isEmpty()) {
        haveDynamicMode = true;
    }
    this.supportsDynamicLinker = haveDynamicMode;
    dynamicLibraryLinkFlags = new FlagList(ImmutableList.copyOf(linkerFlagList),
            convertOptionalOptions(optionalLinkerFlagList), ImmutableList.<String>of());

    this.objcopyOptions = ImmutableList.copyOf(toolchain.getObjcopyEmbedFlagList());
    this.ldOptions = ImmutableList.copyOf(toolchain.getLdEmbedFlagList());
    this.arOptions = copyOrDefaultIfEmpty(toolchain.getArFlagList(), "rcsD");

    this.abi = toolchain.getAbiVersion();
    this.abiGlibcVersion = toolchain.getAbiLibcVersion();

    // The default value for optional string attributes is the empty string.
    PathFragment defaultSysroot = toolchain.getBuiltinSysroot().length() == 0 ? null
            : new PathFragment(toolchain.getBuiltinSysroot());
    if ((defaultSysroot != null) && !defaultSysroot.isNormalized()) {
        throw new IllegalArgumentException("The built-in sysroot '" + defaultSysroot + "' is not normalized.");
    }

    if ((cppOptions.libcTop != null) && (defaultSysroot == null)) {
        throw new InvalidConfigurationException(
                "The selected toolchain " + toolchainIdentifier + " does not support setting --grte_top.");
    }
    LibcTop libcTop = cppOptions.libcTop;
    if ((libcTop == null) && !toolchain.getDefaultGrteTop().isEmpty()) {
        try {
            libcTop = new CppOptions.LibcTopConverter().convert(toolchain.getDefaultGrteTop());
        } catch (OptionsParsingException e) {
            throw new InvalidConfigurationException(e.getMessage(), e);
        }
    }
    if ((libcTop != null) && (libcTop.getLabel() != null)) {
        libcLabel = libcTop.getLabel();
    } else {
        libcLabel = null;
    }

    ImmutableList.Builder<PathFragment> builtInIncludeDirectoriesBuilder = ImmutableList.builder();
    sysroot = libcTop == null ? defaultSysroot : libcTop.getSysroot();
    for (String s : toolchain.getCxxBuiltinIncludeDirectoryList()) {
        builtInIncludeDirectoriesBuilder.add(resolveIncludeDir(s, sysroot, crosstoolTopPathFragment));
    }
    builtInIncludeDirectories = builtInIncludeDirectoriesBuilder.build();

    // The runtime sysroot should really be set from --grte_top. However, currently libc has no
    // way to set the sysroot. The CROSSTOOL file does set the runtime sysroot, in the
    // builtin_sysroot field. This implies that you can not arbitrarily mix and match Crosstool
    // and libc versions, you must always choose compatible ones.
    runtimeSysroot = defaultSysroot;

    String sysrootFlag;
    if (sysroot != null) {
        sysrootFlag = "--sysroot=" + sysroot;
    } else {
        sysrootFlag = null;
    }

    ImmutableList.Builder<String> unfilteredCoptsBuilder = ImmutableList.builder();
    if (sysrootFlag != null) {
        unfilteredCoptsBuilder.add(sysrootFlag);
    }
    unfilteredCoptsBuilder.addAll(toolchain.getUnfilteredCxxFlagList());
    unfilteredCompilerFlags = new FlagList(unfilteredCoptsBuilder.build(),
            convertOptionalOptions(toolchain.getOptionalUnfilteredCxxFlagList()), ImmutableList.<String>of());

    ImmutableList.Builder<String> linkoptsBuilder = ImmutableList.builder();
    linkoptsBuilder.addAll(cppOptions.linkoptList);
    if (cppOptions.experimentalOmitfp) {
        linkoptsBuilder.add("-Wl,--eh-frame-hdr");
    }
    if (sysrootFlag != null) {
        linkoptsBuilder.add(sysrootFlag);
    }
    this.linkOptions = linkoptsBuilder.build();

    ImmutableList.Builder<String> ltoindexoptsBuilder = ImmutableList.builder();
    ltoindexoptsBuilder.addAll(cppOptions.ltoindexoptList);
    this.ltoindexOptions = ltoindexoptsBuilder.build();

    ImmutableList.Builder<String> coptsBuilder = ImmutableList.<String>builder()
            .addAll(toolchain.getCompilerFlagList()).addAll(cFlags.get(compilationMode))
            .addAll(lipoCFlags.get(cppOptions.getLipoMode()));
    if (cppOptions.experimentalOmitfp) {
        coptsBuilder.add("-fomit-frame-pointer");
        coptsBuilder.add("-fasynchronous-unwind-tables");
        coptsBuilder.add("-DNO_FRAME_POINTER");
    }
    this.compilerFlags = new FlagList(coptsBuilder.build(),
            convertOptionalOptions(toolchain.getOptionalCompilerFlagList()),
            ImmutableList.copyOf(cppOptions.coptList));

    this.cOptions = ImmutableList.copyOf(cppOptions.conlyoptList);

    ImmutableList.Builder<String> cxxOptsBuilder = ImmutableList.<String>builder()
            .addAll(toolchain.getCxxFlagList()).addAll(cxxFlags.get(compilationMode))
            .addAll(lipoCxxFlags.get(cppOptions.getLipoMode()));

    this.cxxFlags = new FlagList(cxxOptsBuilder.build(),
            convertOptionalOptions(toolchain.getOptionalCxxFlagList()),
            ImmutableList.copyOf(cppOptions.cxxoptList));

    this.ldExecutable = getToolPathFragment(CppConfiguration.Tool.LD);

    fullyStaticLinkFlags = new FlagList(
            configureLinkerOptions(compilationMode, lipoMode, LinkingMode.FULLY_STATIC, ldExecutable),
            convertOptionalOptions(toolchain.getOptionalLinkerFlagList()), ImmutableList.<String>of());
    mostlyStaticLinkFlags = new FlagList(
            configureLinkerOptions(compilationMode, lipoMode, LinkingMode.MOSTLY_STATIC, ldExecutable),
            convertOptionalOptions(toolchain.getOptionalLinkerFlagList()), ImmutableList.<String>of());
    mostlyStaticSharedLinkFlags = new FlagList(
            configureLinkerOptions(compilationMode, lipoMode, LinkingMode.MOSTLY_STATIC_LIBRARIES,
                    ldExecutable),
            convertOptionalOptions(toolchain.getOptionalLinkerFlagList()), ImmutableList.<String>of());
    dynamicLinkFlags = new FlagList(
            configureLinkerOptions(compilationMode, lipoMode, LinkingMode.DYNAMIC, ldExecutable),
            convertOptionalOptions(toolchain.getOptionalLinkerFlagList()), ImmutableList.<String>of());
    testOnlyLinkFlags = ImmutableList.copyOf(toolchain.getTestOnlyLinkerFlagList());

    Map<String, String> makeVariablesBuilder = new HashMap<>();
    // The following are to be used to allow some build rules to avoid the limits on stack frame
    // sizes and variable-length arrays. Ensure that these are always set.
    makeVariablesBuilder.put("STACK_FRAME_UNLIMITED", "");
    makeVariablesBuilder.put("CC_FLAGS", "");
    for (CrosstoolConfig.MakeVariable variable : toolchain.getMakeVariableList()) {
        makeVariablesBuilder.put(variable.getName(), variable.getValue());
    }
    if (sysrootFlag != null) {
        String ccFlags = makeVariablesBuilder.get("CC_FLAGS");
        ccFlags = ccFlags.isEmpty() ? sysrootFlag : ccFlags + " " + sysrootFlag;
        makeVariablesBuilder.put("CC_FLAGS", ccFlags);
    }
    this.additionalMakeVariables = ImmutableMap.copyOf(makeVariablesBuilder);
}

From source file:sql.SQL.java

public static void main(String[] args) {

    COutput c = new COutput();
    String command = "sql>";
    String s[] = new String[1000];
    Scanner sc = new Scanner(System.in); //import java.util.*
    String last_w;/*  w w  w .jav a2 s. co  m*/
    String str = null;
    String pr = null;
    CreateTable CT = new CreateTable();

    boolean InsertWithKey = false;
    boolean Index = false;
    ListMultimap<String, String> index_attri = ArrayListMultimap.create(); //key:table, values:atrribute for indexing

    Map<String, ListMultimap<String, String>> map = new HashMap<>();
    Map<String, Hashtable<String, List<String>>> Hashing = new HashMap<>();// key:table name     value:Hashing 

    String regEx = "[`~!@#$%^&()+=|{}':',\\[\\]/?~?@#%&+|{}????]"; // delete *
    Pattern p = Pattern.compile(regEx);

    //words put into array
    while (true) {

        int i = 0, j = 0, k = 0, l = 0;
        int temp = 0, index = 0;
        int cal = 0;
        boolean flag = false;
        InsertWithKey = false;
        boolean samekey = false;
        boolean error = false;
        Arrays.fill(s, null);
        System.out.print(command);
        //preprocessing: put words in array, ; deletion
        while (true) {
            s[i] = sc.next();
            last_w = String.valueOf(s[i].charAt(s[i].length() - 1));
            // ;-->"  "
            if (last_w.equals(";")) {
                if (s[i].length() > 1) {
                    s[i] = s[i].substring(0, s[i].length() - 1);
                } else {
                    s[i] = null;
                }
                break;
            }
            i++;
        }
        while (true) {

            //preprocessing: parenthesis
            if ((s[2].charAt(s[2].length() - 1) + "").equals("(")) {
                // x( y ---> x  (y 
                if ((s[2].charAt(s[2].length() - 1) + "").equals("(")) {
                    s[2] = s[2].substring(0, s[2].length() - 1);
                    s[3] = "(" + s[3];
                } // x(y ---> x  (y
                else if (!s[2].contains("(") && (s[2].charAt(s[2].length() - 1) + "").equals("(")) {
                    while (true) {
                        if ((s[2].charAt(cal) + "").equals("(")) {
                            break;
                        }
                        cal++;
                    }
                    s[3] = s[3].substring(cal, s[2].length()) + s[3];
                    s[2] = s[2].substring(0, cal);
                }
            }

            // handle x ( y 
            for (k = 0; s[k] != null; k++) {
                if (s[k].equals("(")) {
                    for (j = k; s[j + 1] != null; j++) {
                        if (j == k) {
                            s[j] = s[j] + s[j + 1];
                        } else {
                            s[j] = s[j + 1];
                        }
                    }
                    s[j] = null;

                }
            }
            /*
            if(s[0].equalsIgnoreCase("CREATE") &&!s[3].contains("(")){
            System.out.println("SQL syntax error! Losing left parenthesis...");
            break;
            }
            if(s[0].equalsIgnoreCase("INSERT") &&!s[4].contains("(")){
            System.out.println("SQL syntax error! Losing left parenthesis...");
            break;
            }*/

            for (j = 0; s[j] != null; j++) {
                if (s[j].equalsIgnoreCase("VALUES")) {
                    if (!s[j + 1].contains("(")) {
                        System.out.println("SQL syntax error! Losing left parenthesis...");
                        break;
                    }

                }
            }
            if (s[0].equalsIgnoreCase("CREATE") && s[k - 2].contains(",") || s[k - 1].contains(",")) {
                System.out.println("SQL syntax error! Found unnecessary semicolon...");
                break;
            }
            // remove "," "(" ")"
            for (j = 0; s[j] != null; j++) {
                if (s[0].equalsIgnoreCase("SELECT")) {
                    if (s[j].contains(",")) {
                        s[j] = s[j].substring(0, s[j].length() - 1);
                    }
                } else {
                    if (String.valueOf(s[j].charAt(0)).equals("(")) {
                        s[j] = s[j].substring(1, s[j].length());
                    }
                    if (s[j].equals(")")) {
                        s[j] = null;
                        break;
                    }
                    if (String.valueOf(s[j].charAt(s[j].length() - 1)).equals(",")
                            || (String.valueOf(s[j].charAt(s[j].length() - 1)).equals(")")
                                    && !(Character.isDigit(s[j].charAt(s[j].length() - 2)))
                                    && s[0].equalsIgnoreCase("CREATE"))
                            || (String.valueOf(s[j].charAt(s[j].length() - 1)).equals(")")
                                    && s[0].equalsIgnoreCase("INSERT"))) {
                        s[j] = s[j].substring(0, s[j].length() - 1);
                    }
                }
            }

            // handle case like: '  John Snow  ' 
            int countdot = 0;
            for (j = 0; s[j] != null; j++) {
                if (s[j].contains("'")) {
                    countdot++;
                }
                if (String.valueOf(s[j].charAt(0)).equals("'") && s[j].length() == 1 && countdot == 1) {
                    for (k = j; s[k + 1] != null; k++) {
                        if (k == j) {
                            s[k] = s[k] + s[k + 1];
                        } else {
                            s[k] = s[k + 1];
                        }
                    }
                    s[k] = null;
                }
                if (String.valueOf(s[j].charAt(0)).equals("'") && s[j].length() == 1 && countdot == 2) {
                    for (k = j; s[k - 1] != null; k++) {
                        if (k == j) {
                            s[k - 1] = s[k - 1] + s[k];
                        } else {
                            s[k - 1] = s[k];
                        }
                    }
                    s[k] = null;
                }

            }
            // handle case like: 'John Snow' 
            String cache;
            int move;
            for (j = 0; s[j] != null; j++) {
                if (s[j].contains("'")) {
                    cache = s[j];
                    int m;
                    if (String.valueOf(s[j].charAt(0)).equals("'")
                            && String.valueOf(s[j].charAt(s[j].length() - 1)).equals("'")) {
                        if (!s[0].equalsIgnoreCase("SELECT")) {
                            s[j] = s[j].substring(1, s[j].length() - 1);
                        }
                    } else {
                        for (k = j + 1; s[k] != null; k++) {
                            if (s[k].contains("'")) {
                                break;
                            }
                        }
                        for (l = j; l < k; l++) {
                            cache = cache + " " + s[l + 1];
                        }
                        s[j] = cache;
                        move = k - j;
                        for (m = j + 1; s[m + move] != null; m++) {
                            s[m] = s[m + move];
                        }
                        for (; s[m] != null; m++) {
                            s[m] = null;
                        }
                        if (!s[0].equalsIgnoreCase("SELECT")) {
                            //System.out.println("**********");
                            s[j] = s[j].substring(1, s[j].length() - 1);
                        }
                    }
                }
            }
            for (j = 0; s[j] != null; j++) {
                if (s[j].equalsIgnoreCase("PRIMARY") && s[j + 1].equalsIgnoreCase("KEY")) {

                    for (k = j; s[k + 2] != null; k++) {
                        if (k == j) {
                            s[k - 1] = s[k - 1] + "*";
                            s[k] = s[k + 2];
                        } else {
                            s[k] = s[k + 2];
                        }
                    }
                    s[k] = null;
                    s[k + 1] = null;
                }
            }

            //check for valid
            Matcher m = p.matcher(s[2]);
            if (m.find()) {
                System.out.println("??\n");
                break;
            } else {
                /*for (j = 0; s[j] != null; j++) {
                System.out.println(s[j]);
                }*/

                //Syntax c.correct, action.
                try {

                    ListMultimap<String, String> newmap = ArrayListMultimap.create();
                    MyLinkedMap<String, String> tables = new MyLinkedMap<>(); // name and alias
                    int aggrenum = 0;

                    ListMultimap<String, String> SelAtr = ArrayListMultimap.create(); // index,  <selected attributes, table>
                    List<String> coltitle = new ArrayList<String>();

                    MyLinkedMap<String, Integer> syntax = new MyLinkedMap<>();

                    Map<String, BTree<String, List<String>>> BT = new HashMap<>(); // key:index name     value:Btree 

                    //Hashtable<String, List<String>> ht = new Hashtable<>();
                    //indexes of syntax
                    int from = 0; //index of FROM
                    int where = 0;
                    int[] as = new int[10]; //The system must allow SQL SELECT from up to 10 attributes in a table.
                    int as_n = 0;
                    boolean innerJoin = false;
                    String key = null;
                    boolean ambuguous = false;
                    c.aggre_b = false;

                    if (s[0].equalsIgnoreCase("CREATE") && s[1].equalsIgnoreCase("INDEX")) {
                        //s[2]: index name
                        //s[4]: table name
                        //s[5]: attribute
                        Index = true;
                        for (i = 0; s[i] != null; i++) {
                            if (s[i + 1] == null) {
                                break;
                            }
                        }
                        if (s[i].equalsIgnoreCase("BTREE")) {
                            BTree<String, List<String>> tree = new BTree<>();

                            List<String> tuple = new ArrayList<>();
                            String attriName = null;
                            String temp_tupleData = null;

                            for (i = 0; i < map.get(s[4]).get("attribute").size(); i++) {
                                if (map.get(s[4]).get("attribute").get(i).contains(s[5])) {
                                    attriName = map.get(s[4]).get("attribute").get(i);
                                    break;
                                }
                            }
                            index_attri.put(s[4], attriName + "-btree");
                            //System.out.println(tree.height());
                            if (attriName != null) {
                                for (i = 0; i < map.get(s[4]).get(attriName).size(); i++) {
                                    List<String> tempList = new ArrayList<>();
                                    for (j = 0; j < map.get(s[4]).get("attribute").size(); j++) {

                                        temp_tupleData = map.get(s[4])
                                                .get(map.get(s[4]).get("attribute").get(j)).get(i);
                                        tempList.add(temp_tupleData);

                                    }
                                    tree.put(String.valueOf(map.get(s[4]).get(attriName).get(i)), tempList);
                                    tuple.add(String.valueOf(map.get(s[4]).get(attriName).get(i)));
                                }

                                Collections.sort(tuple);
                                BT.put(s[2], tree);
                                System.out.println("tuple: " + tuple);
                                /*for(i=0; i<map.get(s[4]).get(attriName).size(); i++){
                                System.out.println("tree: "+ tree.get(tuple.get(i)));
                                }*/
                            } else {
                                System.out.println("Wrong attribute");
                            }
                        } else if (s[i].equalsIgnoreCase("HASHING")) {
                            Hashtable<String, List<String>> ht = new Hashtable<>(); //key:index value: data

                            String attriName = null;
                            String temp_tupleData = null;

                            for (i = 0; i < map.get(s[4]).get("attribute").size(); i++) {
                                if (map.get(s[4]).get("attribute").get(i).contains(s[5])) {
                                    attriName = map.get(s[4]).get("attribute").get(i);
                                    break;
                                }
                            }
                            index_attri.put(s[4], attriName);

                            if (attriName != null) {
                                for (i = 0; i < map.get(s[4]).get(attriName).size(); i++) {
                                    List<String> tempList = new ArrayList<>();
                                    for (j = 0; j < map.get(s[4]).get("attribute").size(); j++) {
                                        temp_tupleData = map.get(s[4])
                                                .get(map.get(s[4]).get("attribute").get(j)).get(i);
                                        tempList.add(temp_tupleData);
                                    }
                                    //System.out.println("key is: "+map.get(s[4]).get(attriName).get(i));
                                    ht.put(map.get(s[4]).get(attriName).get(i), tempList);
                                }
                                //System.out.println("table is: " + s[4]);
                                Hashing.put(s[4], ht);
                                for (i = 0; i < map.get(s[4]).get(attriName).size(); i++) {
                                    System.out
                                            .println("hashing: " + ht.get(map.get(s[4]).get(attriName).get(i)));
                                }
                            } else {
                                System.out.println("Wrong attribute");
                            }
                        }
                        //System.out.println("Hashing: " + Hashing);
                    } else if (s[0].equalsIgnoreCase("SELECT") && Index) {
                        long start = System.currentTimeMillis();
                        //map:syntax (FROM, index in s[]) (Select From As Where)
                        String table[] = new String[2];
                        String target = null; //target attibute
                        String targetTable = null; //target's table
                        int targetNum = -1;
                        for (i = 0; s[i] != null; i++) {
                            if (s[i].equalsIgnoreCase("FROM")) {
                                from = i;
                                table[0] = s[i + 1];
                                table[1] = s[i + 2];
                                //syntax.put("FROM", from);
                            } else if (s[i].equalsIgnoreCase("WHERE")) {
                                where = i;
                                //syntax.put("WHERE", where);
                            }
                        }
                        if (s[1].contains("SUM") || s[1].contains("COUNT")) {
                            if (s[1].contains(".")) {
                                target = s[1].substring(s[1].indexOf(".") + 1, s[1].length() - 1);
                                targetTable = s[1].substring(s[1].indexOf("(") + 1, s[1].indexOf("."));
                                //System.out.println("targetTable:" + targetTable);
                            } else {
                                target = s[1].substring(s[1].indexOf("(") + 1, s[1].length() - 1);

                                for (j = from + 1; j < where; j++) {
                                    //System.out.println("s----:" + s[j]);
                                    //System.out.println(map.get(s[j]).get("attribute").size());
                                    for (k = 0; k < map.get(s[j]).get("attribute").size(); k++) {
                                        //System.out.println(map.get(s[j]).get("attribute").get(k));
                                        if (map.get(s[j]).get("attribute").get(k).contains(target)) {
                                            targetTable = s[j];
                                            //System.out.println("targetTable:" + targetTable);
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        for (i = 0; i < map.get(targetTable).get("attribute").size(); i++) {
                            if (map.get(targetTable).get("attribute").get(i).contains(target)) {
                                target = map.get(targetTable).get("attribute").get(i);
                                targetNum = i;
                                break;
                            }
                        }
                        //System.out.println("targetNum:" + targetNum);
                        //System.out.println("targetTable:" + targetTable);
                        //System.out.println("target:" + target);
                        String tempTable = null;
                        String tempAtrri = null;
                        List<String> pos = new ArrayList<>();
                        int numOfAttri = -1; //order of temp attribute
                        i = where + 1;
                        //System.out.println("i:" + i);

                        if (s[i].contains(".")) {
                            tempTable = s[i].substring(0, s[i].indexOf("."));
                            for (j = 0; j < map.get(tempTable).get("attribute").size(); j++) {
                                if (map.get(tempTable).get("attribute").get(j)
                                        .contains(s[i].substring(s[i].indexOf(".") + 1, s[i].length()))) {
                                    numOfAttri = map.get(tempTable).get("attribute")
                                            .indexOf(map.get(tempTable).get("attribute").get(j));
                                    tempAtrri = map.get(tempTable).get("attribute").get(j);
                                    //System.out.println("tempTable:" + tempTable);
                                    //System.out.println("tempAtrri:" + tempAtrri);
                                    //System.out.println("numOfAttri:" + numOfAttri);
                                    break;
                                }
                            }
                        } else {
                            for (j = from + 1; j < where; j++) { //table
                                for (k = 0; k < map.get(s[j]).get("attribute").size(); k++) { //atrribute
                                    if (map.get(s[j]).get("attribute").get(k).contains(s[i])) {
                                        numOfAttri = map.get(s[j]).get("attribute")
                                                .indexOf(map.get(s[j]).get("attribute").get(k));
                                        tempAtrri = map.get(s[j]).get("attribute").get(k);
                                        tempTable = s[j];
                                        //System.out.println("tempTable:" + tempTable);
                                        //System.out.println("tempAtrri:" + tempAtrri);
                                        //System.out.println("numOfAttri:" + numOfAttri);
                                        break;
                                    }
                                }
                            }
                        }
                        switch (s[i + 1]) {
                        case ">":
                            for (j = 0; j < map.get(tempTable).get(tempAtrri).size(); j++) {
                                if (Integer.parseInt(map.get(tempTable).get(tempAtrri).get(j)) > Integer
                                        .parseInt(s[i + 2])) {
                                    //System.out.println("record:" + map.get(tempTable).get(tempAtrri).get(j));
                                    pos.add(map.get(tempTable).get(index_attri.get(tempTable).get(0)).get(j));
                                    //index list
                                }
                            }
                            break;
                        case "<":
                            for (j = 0; j < map.get(tempTable).get(tempAtrri).size(); j++) {

                                if (Integer.parseInt(map.get(tempTable).get(tempAtrri).get(j)) < Integer
                                        .parseInt(s[i + 2])) {
                                    //System.out.println("record:" + map.get(tempTable).get(tempAtrri).get(j));
                                    pos.add(map.get(tempTable).get(index_attri.get(tempTable).get(0)).get(j));
                                }
                            }
                            break;
                        case "=":
                            for (j = 0; j < map.get(tempTable).get(tempAtrri).size(); j++) {
                                if (Integer.parseInt(map.get(tempTable).get(tempAtrri).get(j)) == Integer
                                        .parseInt(s[i + 2])) {
                                    //System.out.println("record:" + map.get(tempTable).get(tempAtrri).get(j));
                                    pos.add(map.get(tempTable).get(index_attri.get(tempTable).get(0)).get(j));
                                }
                            }
                            break;
                        case "!=":
                            for (j = 0; j < map.get(tempTable).get(tempAtrri).size(); j++) {
                                if (Integer.parseInt(map.get(tempTable).get(tempAtrri).get(j)) != Integer
                                        .parseInt(s[i + 2])) {
                                    //.out.println("record:" + map.get(tempTable).get(tempAtrri).get(j));
                                    pos.add(map.get(tempTable).get(index_attri.get(tempTable).get(0)).get(j));
                                }
                            }
                            break;
                        }

                        //System.out.println("pos:" + pos);
                        //todo
                        if (s[1].contains("SUM")) {
                            int sum = 0;
                            if (tempTable.equals(table[0])) {
                                for (i = 0; i < pos.size(); i++) {
                                    String temp1 = Hashing.get(tempTable).get(pos.get(i))
                                            .get(Hashing.get(tempTable).get(pos.get(i)).size() - 1);
                                    //System.out.println("foreign key:" + temp1);
                                    if (Hashing.get(targetTable).get(temp1) != null) {
                                        sum += Integer
                                                .parseInt(Hashing.get(targetTable).get(temp1).get(targetNum));
                                    }
                                }
                            } else if (tempTable.equals(table[1])) {
                                Set<String> keys = Hashing.get(table[0]).keySet();
                                Iterator<String> itr = keys.iterator();
                                while (itr.hasNext()) {
                                    str = itr.next();
                                    //System.out.println("str:" + str);
                                    //System.out.println("---" + Hashing.get(table[0]).get(str).get(Hashing.get(table[0]).get(str).size() - 1));
                                    if (pos.contains(Hashing.get(table[0]).get(str)
                                            .get(Hashing.get(table[0]).get(str).size() - 1))) {
                                        //System.out.println("num: " + Hashing.get(targetTable).get(str).get(targetNum));
                                        sum += Integer
                                                .parseInt(Hashing.get(targetTable).get(str).get(targetNum));
                                    }
                                }
                            }
                            System.out.println("------------------------------------------------------");
                            System.out.println("sum:" + sum);
                            System.out
                                    .println("Time cost with select: " + (System.currentTimeMillis() - start));
                        } else if (s[1].contains("COUNT")) {
                            int count = 0;
                            if (tempTable.equals(table[0])) {
                                for (i = 0; i < pos.size(); i++) {
                                    String temp1 = Hashing.get(tempTable).get(pos.get(i))
                                            .get(Hashing.get(tempTable).get(pos.get(i)).size() - 1);
                                    //System.out.println("foreign key:" + temp1);
                                    if (Hashing.get(targetTable).get(temp1) != null) {
                                        count++;
                                    }
                                }
                            } else if (tempTable.equals(table[1])) {
                                Set<String> keys = Hashing.get(table[0]).keySet();
                                Iterator<String> itr = keys.iterator();
                                while (itr.hasNext()) {
                                    str = itr.next();
                                    //System.out.println("str:" + str);
                                    //System.out.println("---" + Hashing.get(table[0]).get(str).get(Hashing.get(table[0]).get(str).size() - 1));
                                    if (pos.contains(Hashing.get(table[0]).get(str)
                                            .get(Hashing.get(table[0]).get(str).size() - 1))) {
                                        //System.out.println("num: " + Hashing.get(targetTable).get(str).get(targetNum));
                                        count++;
                                    }
                                }
                            }
                            System.out.println("------------------------------------------------------");
                            System.out.println("count:" + count);
                            System.out
                                    .println("Time cost with select: " + (System.currentTimeMillis() - start));
                        }
                    } else if (s[0].equalsIgnoreCase("SELECT") && !Index) {

                        //map:syntax (FROM, index in s[]) (Se Fr As Wh)
                        for (i = 0; s[i] != null; i++) {
                            if (s[i].equalsIgnoreCase("FROM")) {
                                from = i;
                                syntax.put("FROM", from);
                            } else if (s[i].equalsIgnoreCase("WHERE")) {
                                where = i;
                                syntax.put("WHERE", where);
                            } else if (s[i].equalsIgnoreCase("AS")) {
                                as[as_n] = i;
                                syntax.put("AS", as[as_n]);
                                as_n++;
                            }
                        }

                        for (i = 1; i < from; i++) { //select
                            if (!s[i].contains(".") && (where - from) > 1) {
                                System.out.println(map.get(s[from + 1]).get("attribute").size());
                                for (j = 0; j < map.get(s[from + 1]).get("attribute").size(); j++) {
                                    if (map.get(s[from + 1]).get("attribute").get(j).contains(s[i])) {
                                        for (k = 0; k < map.get(s[from + 2]).get("attribute").size(); k++) {
                                            if (map.get(s[from + 2]).get("attribute").get(k).contains(s[i])) {
                                                System.out.println("Ambuguous Input!!");
                                                ambuguous = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (ambuguous) {
                            break;
                        }

                        //map:tables (realname, alias) (Se Fr '*' As '*' Wh)
                        if (where != 0) {
                            for (i = from + 1; i < syntax.getValue(1); i++) {
                                if (s[i + 1].equalsIgnoreCase("AS")) {
                                    tables.put(s[i], s[i + 2]);
                                    i = i + 2;
                                } else if (!s[i - 1].equalsIgnoreCase("AS")
                                        && !s[i + 1].equalsIgnoreCase("AS")) {
                                    tables.put(s[i], null);
                                }
                            }
                        } else {
                            if (s[from + 2] != null) {
                                for (i = from + 1; s[i] != null; i++) {
                                    //System.out.println(i);
                                    if (s[i + 1].equalsIgnoreCase("AS")) {
                                        tables.put(s[i], s[i + 2]);
                                        i = i + 2;
                                    } else {
                                        tables.put(s[i], null);
                                    }
                                }
                            } else {
                                tables.put(s[from + 1], null);
                            }
                        }
                        System.out.println(tables);

                        //SELECT aggregation function ?table table-->ex. SELECT a.friendid, SUM(b.number)
                        //SELECT COUNT(*) FROM Book; HERE!!!  ??without"a."
                        //SELECT COUNT(*)FROM Author WHERE nationality = 'Taiwan';
                        //SELECT COUNT(editorial) FROM Book;
                        //SELECT SUM(pages) FROM Book WHERE authorId = 2;
                        //
                        //multimap:SelAtr (index, attribute, table-real-name) (Se '*' Fr * As * Wh) 
                        for (i = 1; i < from; i++) {//@check one attribute: [stuID] or [a.stuId] or [COUNT(stuID)] or [COUNT(a.stuID)]

                            String table1;
                            String attribute1;
                            //String[] atri = new String[2]; //store A.name as name and A

                            //aggregation bool
                            if (s[i].toUpperCase().contains("COUNT") || s[i].toUpperCase().contains("SUM")) {
                                c.aggre = s[i].substring(0, s[i].indexOf("(")).toUpperCase();
                                c.aggre_b = true;
                            }
                            System.out.println(c.aggre_b);
                            System.out.println("Im here1");

                            c.atri(s, i, tables, map);
                            System.out.println("Im here2");
                            table1 = c.table;
                            System.out.println("table1:" + table1);
                            attribute1 = c.attribute;
                            System.out.println("attribute1:" + attribute1);

                            if (attribute1.equals("*")) {

                                for (k = 0; k < map.get(c.table).get("attribute").size(); k++) {
                                    SelAtr.put(c.table, map.get(c.table).get("attribute").get(k));
                                    String coll;
                                    if (c.pt_attribute.contains(".")) {
                                        int len_todot = c.pt_attribute.indexOf(".");
                                        coll = c.pt_attribute.substring(0, len_todot)
                                                + map.get(c.table).get("attribute").get(k);
                                    } else {
                                        coll = map.get(c.table).get("attribute").get(k);
                                    }
                                    coltitle.add(coll);
                                }
                            } else {
                                for (j = 0; j < map.get(table1).get("attribute").size(); j++) {
                                    //System.out.println("000000000000" + map.get(table1).get("attribute").get(j));
                                    if (map.get(table1).get("attribute").get(j).contains(attribute1)) {

                                        SelAtr.put(table1, map.get(table1).get("attribute").get(j));
                                        coltitle.add(attribute1);
                                    }
                                }
                            }
                        } //end of [attributes --> SelAtr] for loop

                        System.out.println(SelAtr);
                        System.out.println(coltitle);
                        System.out.println("Im here1");

                        boolean compare = false;
                        // if there is no WHERE clause, set the c.correct
                        if (where == 0) {
                            System.out.println("im here in where");
                            String atriTemp;
                            String table_0 = tables.getKey(0);

                            atriTemp = map.get(table_0).get("attribute").get(0);
                            for (i = 0; i < map.get(table_0).get(atriTemp).size(); i++) {
                                c.correct.add(i);
                            }
                            if (tables.getKey(1) != null) {
                                String table_1 = tables.getKey(1);
                                atriTemp = map.get(table_1).get("attribute").get(0);
                                for (i = 0; i < map.get(table_1).get(atriTemp).size(); i++) {
                                    c.correct2.add(i);
                                }
                            }
                        } else if (where != 0) {//if where is written

                            boolean andor = false;
                            boolean and = false;
                            boolean or = false;

                            int mapcount;

                            for (i = where + 1; s[i] != null; i = i + 4) { //i=s[], start from where
                                System.out.println("--------------------" + i);
                                /*1*/
                                String table1, attribute1; //---> atri[0](attri)  atri[1](table-real name)
                                /*2*/
                                String opt;
                                /*3*/
                                String third;
                                /*4*/ //bool : AND
                                if (s[i + 3] != null) {
                                    if (s[i + 3].equalsIgnoreCase("AND")) {
                                        and = true;
                                        andor = true;
                                    } else if (s[i + 3].equalsIgnoreCase("OR")) {
                                        or = true;
                                        andor = true;
                                    }
                                }
                                System.out.println("Im here 2");

                                c.atri(s, i, tables, map);
                                table1 = c.table;
                                attribute1 = c.attribute;
                                System.out.println("table1:" + table1);
                                System.out.println("attribute1:" + attribute1);

                                /*2*/ //opt
                                opt = s[i + 1];
                                System.out.println("opt:" + opt);

                                /*3*/ //third
                                third = s[i + 2];
                                System.out.println("third:" + third);

                                for (mapcount = 0; mapcount < map.get(table1).get("attribute")
                                        .size(); mapcount++) {
                                    if (map.get(table1).get("attribute").get(mapcount).contains(attribute1)) {
                                        System.out.println(map.get(table1).get("attribute").get(mapcount));
                                        break;
                                    }
                                }
                                int at_size = map.get(table1)
                                        .get(map.get(table1).get("attribute").get(mapcount)).size(); // the size of the selected attribute (compared to the number)

                                //System.out.println("at_size:" + at_size);
                                /*case 1*/ //+num 
                                if (StringUtils.isNumeric(third)) {

                                    System.out.println(
                                            "im here 3" + map.get(table1).get("attribute").get(mapcount));

                                    int num = Integer.valueOf(third); // the number

                                    switch (opt) {
                                    case ">":
                                        //System.out.println(">>>>>>>");
                                        for (j = 0; j < at_size; j++) {
                                            if (Integer.valueOf(map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount))
                                                    .get(j)) > num) {
                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                        break;
                                    case "<":
                                        for (j = 0; j < at_size; j++) {
                                            if (Integer.valueOf(map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount))
                                                    .get(j)) < num) {
                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                        break;
                                    case "=":
                                        for (j = 0; j < at_size; j++) {
                                            //System.out.println(j);
                                            if (Integer.valueOf(map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount))
                                                    .get(j)) == num) {
                                                //System.out.println(map.get(table1).get(map.get(table1).get("attribute").get(mapcount)).get(j));
                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                        break;
                                    case "<>":
                                        for (j = 0; j < at_size; j++) {
                                            if (Integer.valueOf(map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount))
                                                    .get(j)) != num) {
                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                        break;
                                    default:
                                        break;
                                    }

                                } // end if third = integer

                                /*case 2*/ //+string 
                                else if (!third.contains(".") && !StringUtils.isNumeric(third)) {

                                    System.out.println("In case 2----------------");

                                    third = third.substring(1, third.length() - 1);
                                    System.out.println("third:" + third);
                                    if (opt.equals("<>")) {
                                        for (j = 0; j < at_size; j++) {
                                            if (!map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount)).get(j)
                                                    .equals(third)) {
                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                    } else if (opt.equals("=")) {

                                        for (j = 0; j < map.get(table1)
                                                .get(map.get(table1).get("attribute").get(mapcount))
                                                .size(); j++) {
                                            System.out.println(map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount))
                                                    .get(j));
                                            if (map.get(table1)
                                                    .get(map.get(table1).get("attribute").get(mapcount)).get(j)
                                                    .equals(third)) {

                                                c.COutput(map, table1, j, tables, compare);
                                            }
                                        }
                                    }
                                } else {
                                    /*case 3*/ //inner join a.studentID = b.studentID 
                                    //String table2, attribute2;
                                    //process third dot
                                    c.atri(s, i, tables, map);

                                    innerJoin = true;
                                    key = s[i].substring(s[i].indexOf(".") + 1, s[i].length());
                                    System.out.println("XXXXXXXXXXXXXXX:" + key);

                                }

                                System.out.println(c.correct);
                                System.out.println(c.correct2);

                                if (compare) {
                                    if (and && !innerJoin) {
                                        c.correct.retainAll(c.correct2);
                                        Set<Integer> hs = new HashSet<>();
                                        hs.addAll(c.correct);
                                        c.correct.clear();
                                        c.correct.addAll(hs);

                                    } else if (or && !innerJoin) {
                                        c.correct.addAll(c.correct2);
                                        Set<Integer> hs = new HashSet<>();
                                        hs.addAll(c.correct);
                                        c.correct.clear();
                                        c.correct.addAll(hs);
                                    }
                                }
                                System.out.println(c.correct);

                                if (andor) {
                                    compare = true;
                                } else {
                                    compare = false;
                                }
                                System.out.println("AND:" + and);
                                System.out.println("OR:" + or);
                                System.out.println("andor:" + andor);
                                System.out.println("compare:" + compare);

                            }

                            if (c.aggre_b == true) {
                                if (c.aggre.equalsIgnoreCase("COUNT")) {
                                    if (c.table.equals(tables.getKey(0))) {
                                        aggrenum = c.correct.size();
                                    } else {
                                        aggrenum = c.correct2.size();
                                    }
                                } else if (c.aggre.equalsIgnoreCase("SUM")) {
                                    int value;
                                    List<Integer> cor;
                                    if (c.table.equals(tables.getKey(0))) {
                                        cor = c.correct;
                                    } else {
                                        cor = c.correct2;
                                    }
                                    for (i = 0; i < cor.size(); i++) {
                                        value = Integer
                                                .valueOf(map.get(c.table).get(c.attribute).get(cor.get(i)));
                                        aggrenum = aggrenum + value;
                                    }
                                } else {
                                    System.out.println("Wrong aggregation function.");
                                }
                            }
                        }

                        //print!!!
                        System.out.println("coltitle" + coltitle);
                        System.out.println("tables" + tables);
                        System.out.println("correct" + c.correct);
                        System.out.println("SelAtr" + SelAtr);
                        //System.out.println("table" + c.table);
                        System.out.println("-----------------------------------------------------------");
                        String tab;

                        if (innerJoin) {
                            String biggerTable, smalTable, temp1;
                            String attiTemp1 = null, attiTemp2 = null;
                            if (tables.getKey(0).equals(c.table)) {
                                tab = tables.getKey(1);
                            } else {
                                tab = tables.getKey(0);
                            }

                            for (i = 0; i < map.get(c.table).get("attribute").size(); i++) {
                                //System.out.println("key:" + map.get(c.table).get("attribute").get(i));
                                if (map.get(c.table).get("attribute").get(i).contains(key)) {
                                    attiTemp1 = map.get(c.table).get("attribute").get(i);
                                    //System.out.println("key:" + attiTemp1);
                                    break;
                                }
                            }
                            for (j = 0; j < map.get(tab).get("attribute").size(); j++) {
                                //System.out.println("key:" + map.get(tab).get("attribute").get(l));
                                if (map.get(tab).get("attribute").get(j).contains(key)) {
                                    attiTemp2 = map.get(tab).get("attribute").get(j);
                                    //System.out.println("key:" + attiTemp2);
                                    break;
                                }
                            }
                            if (map.get(c.table).get(attiTemp1).size() > map.get(tab).get(attiTemp2).size()) {
                                biggerTable = c.table;
                                smalTable = tab;
                            } else {
                                temp1 = attiTemp2;
                                attiTemp2 = attiTemp1;
                                attiTemp1 = temp1;
                                biggerTable = tab;
                                smalTable = c.table;
                            }
                            /*
                            System.out.println(smalTable);
                            System.out.println("key:" + attiTemp2);
                            System.out.println(biggerTable);
                            System.out.println("key:" + attiTemp1);*/

                            /*for (j = 0; j < c.correct2.size(); j++) {
                            for (k = 0; k < map.get(tab).get(map.get(tab).get("attribute").get(l)).size(); k++) {
                                //System.out.println(tab+":"+map.get(tab).get(key).get(k));
                                //System.out.println(c.table+"r:"+map.get(c.table).get(map.get(c.table).get("attribute").get(i)).get(c.correct2.get(j)));
                                if (map.get(tab).get(map.get(tab).get("attribute").get(l)).get(k).equals(map.get(c.table).get(map.get(c.table).get("attribute").get(i)).get(c.correct2.get(j)))) {
                                    c.correct.add(k);
                                }
                            }
                                                           }*/
                            for (l = 0; l < map.get(biggerTable)
                                    .get(map.get(biggerTable).get("attribute").get(0)).size(); l++) {
                                c.correct.add(l);
                            }
                            //System.out.println("******************");
                            String[] stringArray = Arrays.copyOf(SelAtr.keySet().toArray(),
                                    SelAtr.keySet().toArray().length, String[].class);

                            //System.out.println("SelAtr.size()" + SelAtr.size());
                            if (stringArray.length == 1) {
                                if (!compare) {
                                    /*
                                            
                                    for (k = 0; k < c.correct.size(); k++) {
                                    System.out.println(k);
                                    for (String set : SelAtr.keySet()) {
                                        // System.out.println("Set:"+SelAtr.get(set).size());
                                        for (i = 0; i < SelAtr.get(set).size(); i++) {
                                            //System.out.println(set);
                                            System.out.format("%30s", map.get(set).get(SelAtr.get(set).get(i)).get(c.correct.get(k)));
                                        }
                                    }
                                    System.out.println();
                                    }*/
                                } else {

                                    c.correct.clear();
                                    List<Integer> tempList = new ArrayList<>();
                                    //System.out.println("c.correct2.size():"+c.correct2.size());
                                    for (i = 0; i < map.get(biggerTable).get(attiTemp1).size(); i++) {
                                        for (j = 0; j < c.correct2.size(); j++) {

                                            if (map.get(biggerTable).get(attiTemp1).get(i).equals(
                                                    map.get(smalTable).get(attiTemp2).get(c.correct2.get(j)))) {
                                                c.correct.add(i);
                                                tempList.add(c.correct2.get(j));
                                                break;
                                            }
                                        }
                                    }

                                    for (k = 0; k < c.correct.size(); k++) {
                                        for (j = 0; j < SelAtr.get(biggerTable).size(); j++) {
                                            System.out.format("%30s", map.get(biggerTable)
                                                    .get(SelAtr.get(biggerTable).get(j)).get(c.correct.get(k)));
                                        }
                                        for (i = 0; i < SelAtr.get(smalTable).size(); i++) {
                                            System.out.format("%30s", map.get(smalTable)
                                                    .get(SelAtr.get(smalTable).get(i)).get(tempList.get(k)));
                                        }
                                        System.out.println();
                                    }
                                }
                            } else {

                                if (!compare) {

                                    for (i = 0; i < c.correct.size(); i++) {
                                        for (j = 0; j < map.get(smalTable).get(attiTemp2).size(); j++) {
                                            if (map.get(biggerTable).get(attiTemp1).get(i).equals(
                                                    map.get(smalTable).get(attiTemp2).get(c.correct.get(j)))) {
                                                c.correct2.add(j);
                                                break;
                                            }
                                            if (j == map.get(smalTable).get(attiTemp2).size() - 1) {
                                                c.correct.remove(i);
                                            }
                                        }
                                    }
                                    System.out.println(c.correct);
                                    System.out.println(c.correct2);
                                    for (k = 0; k < c.correct.size(); k++) {
                                        for (j = 0; j < SelAtr.get(smalTable).size(); j++) {
                                            System.out.format("%30s", map.get(smalTable)
                                                    .get(SelAtr.get(smalTable).get(j)).get(c.correct2.get(k)));
                                        }
                                        for (i = 0; i < SelAtr.get(biggerTable).size(); i++) {
                                            System.out.format("%30s", map.get(biggerTable)
                                                    .get(SelAtr.get(biggerTable).get(i)).get(c.correct.get(k)));
                                        }
                                        System.out.println();
                                    }

                                } else {
                                    if (c.table.equals(biggerTable)) {
                                        for (i = 0; i < c.correct2.size(); i++) {
                                            for (j = 0; j < map.get(smalTable).get(attiTemp2).size(); j++) {
                                                if (map.get(smalTable).get(attiTemp2).get(j)
                                                        .equals(map.get(biggerTable).get(attiTemp1)
                                                                .get(c.correct2.get(i)))) {
                                                    c.correct.add(j);
                                                }
                                            }
                                        }
                                        for (k = 0; k < c.correct2.size(); k++) {
                                            for (j = 0; j < SelAtr.get(smalTable).size(); j++) {
                                                System.out.format("%30s",
                                                        map.get(smalTable).get(SelAtr.get(smalTable).get(j))
                                                                .get(c.correct.get(k)));
                                            }
                                            for (i = 0; i < SelAtr.get(biggerTable).size(); i++) {
                                                System.out.format("%30s",
                                                        map.get(biggerTable).get(SelAtr.get(biggerTable).get(i))
                                                                .get(c.correct2.get(k)));
                                            }
                                            System.out.println();
                                        }

                                    } else {

                                        c.correct.clear();
                                        List<Integer> tempList = new ArrayList<>();
                                        //System.out.println("c.correct2.size():"+c.correct2.size());
                                        for (i = 0; i < map.get(biggerTable).get(attiTemp1).size(); i++) {
                                            for (j = 0; j < c.correct2.size(); j++) {
                                                //System.out.println("1----"+map.get(biggerTable).get(attiTemp1).get(i));
                                                //System.out.println("2----"+map.get(smalTable).get(attiTemp2).get(c.correct2.get(j)));

                                                if (map.get(biggerTable).get(attiTemp1).get(i)
                                                        .equals(map.get(smalTable).get(attiTemp2)
                                                                .get(c.correct2.get(j)))) {
                                                    //System.out.println("**************************"+j);
                                                    //System.out.println("1----"+map.get(biggerTable).get(attiTemp1).get(i));
                                                    //System.out.println("2----"+map.get(smalTable).get(attiTemp2).get(c.correct2.get(j)));
                                                    c.correct.add(i);
                                                    tempList.add(c.correct2.get(j));
                                                    break;
                                                }
                                            }
                                        }
                                        System.out.println(c.correct);
                                        System.out.println(tempList);

                                        for (k = 0; k < c.correct.size(); k++) {
                                            for (j = 0; j < SelAtr.get(biggerTable).size(); j++) {
                                                System.out.format("%30s",
                                                        map.get(biggerTable).get(SelAtr.get(biggerTable).get(j))
                                                                .get(c.correct.get(k)));
                                            }
                                            for (i = 0; i < SelAtr.get(smalTable).size(); i++) {
                                                System.out.format("%30s",
                                                        map.get(smalTable).get(SelAtr.get(smalTable).get(i))
                                                                .get(tempList.get(k)));
                                            }
                                            System.out.println();
                                        }
                                    }

                                }
                                /*for (k = 0; k < c.correct.size(); k++) {
                                if (c.table.equals(stringArray[0])) {
                                    for (j = 0; j < SelAtr.get(stringArray[0]).size(); j++) {
                                        System.out.format("%30s", map.get(stringArray[0]).get(SelAtr.get(stringArray[0]).get(j)).get(c.correct2.get(k)));
                                    }
                                    for (i = 0; i < SelAtr.get(stringArray[1]).size(); i++) {
                                        System.out.format("%30s", map.get(stringArray[1]).get(SelAtr.get(stringArray[1]).get(i)).get(c.correct.get(k)));
                                    }
                                    System.out.println();
                                }
                                else if (c.table.equals(stringArray[1])) {
                                    for (j = 0; j < SelAtr.get(stringArray[0]).size(); j++) {
                                        System.out.format("%30s", map.get(stringArray[0]).get(SelAtr.get(stringArray[0]).get(j)).get(c.correct.get(k)));
                                    }
                                    for (i = 0; i < SelAtr.get(stringArray[1]).size(); i++) {
                                        System.out.format("%30s", map.get(stringArray[1]).get(SelAtr.get(stringArray[1]).get(i)).get(c.correct2.get(k)));
                                    }
                                    System.out.println();
                                }
                                }*/
                            }
                            //System.out.println(c.correct);
                        } else if (!c.aggre_b && !innerJoin) {
                            if (SelAtr.get(tables.getKey(0)) != null) {
                                //?table? --> correct
                                //String tab = tables.getKey(0);

                                for (k = 0; k < c.correct.size(); k++) {
                                    for (String set : SelAtr.keySet()) {
                                        for (i = 0; i < SelAtr.get(set).size(); i++) {
                                            System.out.format("%30s", map.get(set).get(SelAtr.get(set).get(i))
                                                    .get(c.correct.get(k)));
                                        }
                                    }
                                    System.out.println();
                                }
                            }
                        } else {
                            System.out.println(c.correct.size());
                        }

                        c.correct.clear();
                        c.correct2.clear();

                        //create table, insert values
                    } else if (s[0].equalsIgnoreCase("CREATE") && s[1].equalsIgnoreCase("TABLE")) {

                        if (!map.containsKey(s[2])) {
                            map.put(s[2], CT.Create(s));
                            System.out.println("Table [" + s[2] + "] has been created successfully\n");
                        } else {
                            System.out.println("Table [" + s[2] + "] has already existed\n");
                        }
                        break;
                    } else if (s[0].equalsIgnoreCase("INSERT") && s[1].equalsIgnoreCase("INTO")) {

                        if (map.containsKey(s[2])) {

                            for (i = 0; i < map.get(s[2]).get("attribute").size(); i++) {
                                if (map.get(s[2]).get("attribute").get(i).contains("*")) {
                                    InsertWithKey = true;
                                    //System.out.println("PR:"+InsertWithKey);
                                }
                            }
                            if (!InsertWithKey) {

                                if (s[3].equalsIgnoreCase("VALUES")) {
                                    int attri_count = map.get(s[2]).get("attribute").size();

                                    for (j = 4, k = 0; s[j] != null; j++, k++) {
                                        //System.out.println("attribute: " + (map.get(s[2]).get("attribute")).get(k));
                                        //System.out.println("data: " + s[j]);
                                        if ((map.get(s[2]).get("attribute")).get(k).contains(")")) {
                                            int num = Integer
                                                    .parseInt((map.get(s[2]).get("attribute")).get(k).substring(
                                                            (map.get(s[2]).get("attribute")).get(k).indexOf("(")
                                                                    + 1,
                                                            (map.get(s[2]).get("attribute")).get(k)
                                                                    .indexOf(")")));
                                            //System.out.println(num);
                                            if (s[j].length() > num) {
                                                System.out.println(s[j] + " exceed varchar limit of " + num);
                                                error = true;
                                                break;
                                            }
                                        } else {
                                            if (s[j].charAt(0) == '-') {
                                                if (!StringUtils.isNumeric(s[j].substring(1))) {
                                                    System.out.println(s[j] + " not in int type");
                                                    error = true;
                                                    break;
                                                }
                                            } else {
                                                if (!StringUtils.isNumeric(s[j])) {
                                                    System.out.println(s[j] + " not in int type");
                                                    error = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!error) {
                                        for (j = 4, k = 0; s[j] != null; j++, k++) {
                                            System.out.println(
                                                    "attribute: " + (map.get(s[2]).get("attribute")).get(k));
                                            System.out.println("data: " + s[j]);
                                            map.get(s[2]).put((map.get(s[2]).get("attribute")).get(k), s[j]);
                                        }

                                        for (k = 0; k < attri_count; k++) {
                                            System.out.println(
                                                    "attribute: " + (map.get(s[2]).get("attribute")).get(k));
                                            str = map.get(s[2]).get("attribute").get(k);
                                            System.out.println(map.get(s[2]).get(str));
                                        }
                                    }
                                } else {
                                    int attri_count = map.get(s[2]).get("attribute").size();
                                    for (i = 0; s[i] != null; i++) {
                                        if (s[i].equalsIgnoreCase("VALUES")) {
                                            break;
                                        }
                                    }

                                    for (j = 3, k = i + 1; !s[j].equalsIgnoreCase("VALUES"); j++, k++) {
                                        //System.out.println("attribute: " + s[j]);
                                        //System.out.println("data: " + s[k]);
                                        for (l = 0; l < attri_count; l++) {
                                            str = map.get(s[2]).get("attribute").get(l);
                                            //System.out.println("str: " + str);
                                            if (str.contains(s[j])) {
                                                break;
                                            }
                                        }
                                        if (str.contains(")")) {
                                            int num = Integer.parseInt(
                                                    str.substring(str.indexOf("(") + 1, str.indexOf(")")));
                                            //System.out.println(num);
                                            if (s[k].length() > num) {
                                                System.out.println(s[k] + " exceed varchar limit of " + num);
                                                error = true;
                                                break;
                                            }
                                        } else {
                                            if (s[k].charAt(0) == '-') {
                                                if (!StringUtils.isNumeric(s[k].substring(1))) {
                                                    System.out.println(s[k] + " not in int type");
                                                    error = true;
                                                    break;
                                                }
                                            }

                                            else {
                                                if (!StringUtils.isNumeric(s[k])) {
                                                    System.out.println(s[k] + " not in int type");
                                                    error = true;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    if (!error) {
                                        for (j = 3, k = i + 1; !s[j].equalsIgnoreCase("VALUES"); j++, k++) {
                                            System.out.println("attribute: " + s[j]);
                                            System.out.println("data: " + s[k]);
                                            for (l = 0; l < attri_count; l++) {
                                                str = map.get(s[2]).get("attribute").get(l);
                                                //System.out.println("str: " + str);
                                                if (str.contains(s[j])) {
                                                    break;
                                                }
                                            }
                                            map.get(s[2]).put(str, s[k]);
                                        }

                                        for (k = 0; k < attri_count; k++) {
                                            System.out.println(
                                                    "attribute: " + (map.get(s[2]).get("attribute")).get(k));
                                            str = map.get(s[2]).get("attribute").get(k);
                                            System.out.println(map.get(s[2]).get(str));
                                        }
                                    }
                                }
                            } // PR
                            else {
                                if (s[3].equalsIgnoreCase("VALUES")) {

                                    int attri_count = map.get(s[2]).get("attribute").size();

                                    //find primary key
                                    for (i = 0; i < attri_count; i++) {
                                        if (map.get(s[2]).get("attribute").get(i).contains("*")) {
                                            pr = map.get(s[2]).get("attribute").get(i); //primary key
                                            break;
                                        }
                                    }

                                    for (j = 0; j < map.get(s[2]).get(pr).size(); j++) {
                                        if (s[4 + i].equals(map.get(s[2]).get(pr).get(j))) {
                                            samekey = true;
                                            System.out.println("Error! Invalid key...");
                                            break;
                                        }
                                    }
                                    if (samekey == false) {
                                        for (j = 4, k = 0; s[j] != null; j++, k++) {
                                            //System.out.println("attribute: " + (map.get(s[2]).get("attribute")).get(k));
                                            //System.out.println("data: " + s[j]);
                                            if ((map.get(s[2]).get("attribute")).get(k).contains(")")) {
                                                int num = Integer.parseInt(
                                                        (map.get(s[2]).get("attribute")).get(k).substring(
                                                                (map.get(s[2]).get("attribute")).get(k)
                                                                        .indexOf("(") + 1,
                                                                (map.get(s[2]).get("attribute")).get(k)
                                                                        .indexOf(")")));
                                                //System.out.println(num);
                                                if (s[j].length() > num) {
                                                    System.out
                                                            .println(s[j] + " exceed varchar limit of " + num);
                                                    error = true;
                                                    break;
                                                }
                                            } else {
                                                if (s[j].charAt(0) == '-') {
                                                    if (!StringUtils.isNumeric(s[j])) {
                                                        System.out.println(s[j] + " not in int type");
                                                        error = true;
                                                        break;
                                                    }
                                                } else {
                                                    if (!StringUtils.isNumeric(s[j].substring(1))) {
                                                        System.out.println(s[j] + " not in int type");
                                                        error = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (!error) {
                                            for (j = 4, k = 0; s[j] != null; j++, k++) {
                                                System.out.println("attribute: "
                                                        + (map.get(s[2]).get("attribute")).get(k));
                                                System.out.println("data: " + s[j]);
                                                map.get(s[2]).put((map.get(s[2]).get("attribute")).get(k),
                                                        s[j]);
                                            }

                                            for (k = 0; k < attri_count; k++) {
                                                System.out.println("attribute: "
                                                        + (map.get(s[2]).get("attribute")).get(k));
                                                str = map.get(s[2]).get("attribute").get(k);
                                                System.out.println(map.get(s[2]).get(str));
                                            }

                                        }
                                    }

                                } else {
                                    int attri_count = map.get(s[2]).get("attribute").size();
                                    for (l = 0; s[l] != null; l++) {
                                        if (s[l].equalsIgnoreCase("VALUES")) {
                                            break;
                                        }
                                    }
                                    for (i = 0; i < attri_count; i++) {
                                        if (map.get(s[2]).get("attribute").get(i).contains("*")) {
                                            pr = map.get(s[2]).get("attribute").get(i); //primary key
                                            break;
                                        }
                                    }

                                    for (j = 3; j < l; j++) {
                                        System.out.println(pr.substring(0, pr.length() - 1));
                                        System.out.println(s[j]);
                                        if (pr.contains(s[j])) {
                                            break;
                                        }
                                    }

                                    for (k = 0; k < map.get(s[2]).get(pr).size(); k++) {
                                        if (s[j - 2 + l].equals(map.get(s[2]).get(pr).get(k))) {
                                            samekey = true;
                                            System.out.println("Error! Invalid key...");
                                            break;
                                        }
                                    }
                                    if (samekey == false) {

                                        for (j = 3, k = l + 1; !s[j].equalsIgnoreCase("VALUES"); j++, k++) {
                                            //System.out.println("attribute: " + s[j]);
                                            //System.out.println("data: " + s[k]);
                                            for (int n = 0; n < attri_count; n++) {
                                                str = map.get(s[2]).get("attribute").get(n);
                                                //System.out.println("str: " + str);
                                                if (str.contains(s[j])) {
                                                    break;
                                                }
                                            }
                                            if (str.contains(")")) {
                                                int num = Integer.parseInt(
                                                        str.substring(str.indexOf("(") + 1, str.indexOf(")")));
                                                //System.out.println(num);
                                                if (s[k].length() > num) {
                                                    System.out
                                                            .println(s[k] + " exceed varchar limit of " + num);
                                                    error = true;
                                                    break;
                                                }
                                            } else {
                                                if (s[k].charAt(0) == '-') {
                                                    if (!StringUtils.isNumeric(s[k].substring(1))) {
                                                        System.out.println(s[k] + " not in int type");
                                                        error = true;
                                                        break;
                                                    }
                                                } else {
                                                    if (!StringUtils.isNumeric(s[k])) {
                                                        System.out.println(s[k] + " not in int type");
                                                        error = true;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (!error) {
                                            for (j = 3, k = l + 1; !s[j].equalsIgnoreCase("VALUES"); j++, k++) {
                                                System.out.println("attribute: " + s[j]);
                                                System.out.println("data: " + s[k]);
                                                for (int n = 0; n < attri_count; n++) {
                                                    str = map.get(s[2]).get("attribute").get(n);
                                                    //System.out.println("str: " + str);
                                                    if (str.contains(s[j])) {
                                                        break;
                                                    }
                                                }
                                                map.get(s[2]).put(str, s[k]);
                                            }
                                            for (k = 0; k < attri_count; k++) {
                                                System.out.println("attribute: "
                                                        + (map.get(s[2]).get("attribute")).get(k));
                                                str = map.get(s[2]).get("attribute").get(k);
                                                System.out.println(map.get(s[2]).get(str));
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            System.out.println("No such table");
                        }
                    }

                    break;

                } catch (Exception e) {
                    System.out.println(e.getClass().getCanonicalName());
                    e.printStackTrace();
                    System.out.println("SQL");
                    break;
                }
            }
        }
    }
}

From source file:com.google.errorprone.bugpatterns.UnusedVariable.java

@Override
public Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state) {
    // Map of symbols to variable declarations. Initially this is a map of all of the local variable
    // and fields. As we go we remove those variables which are used.
    Map<Symbol, TreePath> unusedElements = new HashMap<>();

    // Map of symbols to their usage sites. In this map we also include the definition site in
    // addition to all the trees where symbol is used. This map is designed to keep the usage sites
    // of variables (parameters, fields, locals).
    ////  ww  w .jav a 2  s.  co m
    // We populate this map when analyzing the unused variables and then use it to generate
    // appropriate fixes for them.
    ListMultimap<Symbol, TreePath> usageSites = ArrayListMultimap.create();

    // We will skip reporting on the whole compilation if there are any native methods found.
    // Use a TreeScanner to find all local variables and fields.
    if (hasNativeMethods(tree)) {
        return Description.NO_MATCH;
    }

    // Use a TreeScanner to find all local variables and fields.
    class VariableFinder extends TreePathScanner<Void, Void> {

        private boolean exemptedBySuperType(Type type, VisitorState state) {
            return EXEMPTING_SUPER_TYPES.stream()
                    .anyMatch(t -> isSubtype(type, Suppliers.typeFromString(t).get(state), state));
        }

        @Override
        public Void visitVariable(VariableTree variableTree, Void unused) {
            if (exemptedByName(variableTree.getName())) {
                return null;
            }
            if (isSuppressed(variableTree)) {
                return null;
            }
            VarSymbol symbol = getSymbol(variableTree);
            if (symbol == null) {
                return null;
            }
            if (symbol.getKind() == ElementKind.FIELD
                    && exemptedFieldBySuperType(getType(variableTree), state)) {
                return null;
            }
            super.visitVariable(variableTree, null);
            // Return if the element is exempted by an annotation.
            if (exemptedByAnnotation(variableTree.getModifiers().getAnnotations(), state)) {
                return null;
            }
            switch (symbol.getKind()) {
            case FIELD:
                // We are only interested in private fields and those which are not special.
                if (isFieldEligibleForChecking(variableTree, symbol)) {
                    unusedElements.put(symbol, getCurrentPath());
                    usageSites.put(symbol, getCurrentPath());
                }
                break;
            case LOCAL_VARIABLE:
                unusedElements.put(symbol, getCurrentPath());
                usageSites.put(symbol, getCurrentPath());
                break;
            case PARAMETER:
                // ignore the receiver parameter
                if (variableTree.getName().contentEquals("this")) {
                    return null;
                }
                if (isParameterSubjectToAnalysis(symbol)) {
                    unusedElements.put(symbol, getCurrentPath());
                }
                break;
            default:
                break;
            }
            return null;
        }

        private boolean exemptedFieldBySuperType(Type type, VisitorState state) {
            return EXEMPTING_FIELD_SUPER_TYPES.stream()
                    .anyMatch(t -> isSubtype(type, state.getTypeFromString(t), state));
        }

        private boolean isFieldEligibleForChecking(VariableTree variableTree, VarSymbol symbol) {
            if (reportInjectedFields && variableTree.getModifiers().getFlags().isEmpty()
                    && ASTHelpers.hasDirectAnnotationWithSimpleName(variableTree, "Inject")) {
                return true;
            }
            return variableTree.getModifiers().getFlags().contains(Modifier.PRIVATE)
                    && !SPECIAL_FIELDS.contains(symbol.getSimpleName().toString())
                    && !isLoggerField(variableTree);
        }

        private boolean isLoggerField(VariableTree variableTree) {
            return variableTree.getModifiers().getFlags().containsAll(LOGGER_REQUIRED_MODIFIERS)
                    && LOGGER_TYPE_NAME.contains(variableTree.getType().toString())
                    && LOGGER_VAR_NAME.contains(variableTree.getName().toString());
        }

        /** Returns whether {@code sym} can be removed without updating call sites in other files. */
        private boolean isParameterSubjectToAnalysis(Symbol sym) {
            checkArgument(sym.getKind() == ElementKind.PARAMETER);
            Symbol enclosingMethod = sym.owner;

            for (String annotationName : methodAnnotationsExemptingParameters) {
                if (ASTHelpers.hasAnnotation(enclosingMethod, annotationName, state)) {
                    return false;
                }
            }

            return enclosingMethod.getModifiers().contains(Modifier.PRIVATE);
        }

        @Override
        public Void visitTry(TryTree node, Void unused) {
            // Skip resources, as while these may not be referenced, they are used.
            scan(node.getBlock(), null);
            scan(node.getCatches(), null);
            scan(node.getFinallyBlock(), null);
            return null;
        }

        @Override
        public Void visitClass(ClassTree tree, Void unused) {
            if (isSuppressed(tree) || exemptedBySuperType(getType(tree), state)) {
                return null;
            }
            return super.visitClass(tree, null);
        }

        @Override
        public Void visitLambdaExpression(LambdaExpressionTree node, Void unused) {
            // skip lambda parameters
            return scan(node.getBody(), null);
        }

        @Override
        public Void visitMethod(MethodTree tree, Void unused) {
            return isSuppressed(tree) ? null : super.visitMethod(tree, unused);
        }
    }
    new VariableFinder().scan(state.getPath(), null);

    class FilterUsedVariables extends TreePathScanner<Void, Void> {
        private boolean leftHandSideAssignment = false;
        // When this greater than zero, the usage of identifiers are real.
        private int inArrayAccess = 0;
        // This is true when we are processing a `return` statement. Elements used in return statement
        // must not be considered unused.
        private boolean inReturnStatement = false;
        // When this greater than zero, the usage of identifiers are real because they are in a method
        // call.
        private int inMethodCall = 0;

        private TreePath currentExpressionStatement = null;

        private boolean isInExpressionStatementTree() {
            Tree parent = getCurrentPath().getParentPath().getLeaf();
            return parent != null && parent.getKind() == Kind.EXPRESSION_STATEMENT;
        }

        private boolean isUsed(@Nullable Symbol symbol) {
            return symbol != null
                    && (!leftHandSideAssignment || inReturnStatement || inArrayAccess > 0 || inMethodCall > 0)
                    && unusedElements.containsKey(symbol);
        }

        @Override
        public Void visitExpressionStatement(ExpressionStatementTree tree, Void unused) {
            currentExpressionStatement = getCurrentPath();
            super.visitExpressionStatement(tree, null);
            currentExpressionStatement = null;
            return null;
        }

        @Override
        public Void visitIdentifier(IdentifierTree tree, Void unused) {
            Symbol symbol = getSymbol(tree);
            // Filtering out identifier symbol from vars map. These are real usages of identifiers.
            if (isUsed(symbol)) {
                unusedElements.remove(symbol);
            }
            if (currentExpressionStatement != null && unusedElements.containsKey(symbol)) {
                usageSites.put(symbol, currentExpressionStatement);
            }
            return null;
        }

        @Override
        public Void visitAssignment(AssignmentTree tree, Void unused) {
            // If a variable is used in the left hand side of an assignment that does not count as a
            // usage.
            if (isInExpressionStatementTree()) {
                leftHandSideAssignment = true;
                scan(tree.getVariable(), null);
                leftHandSideAssignment = false;
                scan(tree.getExpression(), null);
            } else {
                super.visitAssignment(tree, null);
            }
            return null;
        }

        @Override
        public Void visitMemberSelect(MemberSelectTree memberSelectTree, Void unused) {
            Symbol symbol = getSymbol(memberSelectTree);
            if (isUsed(symbol)) {
                unusedElements.remove(symbol);
            } else if (currentExpressionStatement != null && unusedElements.containsKey(symbol)) {
                usageSites.put(symbol, currentExpressionStatement);
            }
            // Clear leftHandSideAssignment and descend down the tree to catch any variables in the
            // receiver of this member select, which _are_ considered used.
            boolean wasLeftHandAssignment = leftHandSideAssignment;
            leftHandSideAssignment = false;
            super.visitMemberSelect(memberSelectTree, null);
            leftHandSideAssignment = wasLeftHandAssignment;
            return null;
        }

        @Override
        public Void visitMemberReference(MemberReferenceTree tree, Void unused) {
            super.visitMemberReference(tree, null);
            MethodSymbol symbol = getSymbol(tree);
            if (symbol != null) {
                symbol.getParameters().forEach(unusedElements::remove);
            }
            return null;
        }

        @Override
        public Void visitCompoundAssignment(CompoundAssignmentTree tree, Void unused) {
            if (isInExpressionStatementTree()) {
                leftHandSideAssignment = true;
                scan(tree.getVariable(), null);
                leftHandSideAssignment = false;
                scan(tree.getExpression(), null);
            } else {
                super.visitCompoundAssignment(tree, null);
            }
            return null;
        }

        @Override
        public Void visitArrayAccess(ArrayAccessTree node, Void unused) {
            inArrayAccess++;
            super.visitArrayAccess(node, null);
            inArrayAccess--;
            return null;
        }

        @Override
        public Void visitReturn(ReturnTree node, Void unused) {
            inReturnStatement = true;
            scan(node.getExpression(), null);
            inReturnStatement = false;
            return null;
        }

        @Override
        public Void visitUnary(UnaryTree tree, Void unused) {
            // If unary expression is inside another expression, then this is a real usage of unary
            // operand.
            // Example:
            //   array[i++] = 0; // 'i' has a real usage here. 'array' might not have.
            //   list.get(i++);
            // But if it is like this:
            //   i++;
            // Then it is possible that this is not a real usage of 'i'.
            if (isInExpressionStatementTree()
                    && (tree.getKind() == POSTFIX_DECREMENT || tree.getKind() == POSTFIX_INCREMENT
                            || tree.getKind() == PREFIX_DECREMENT || tree.getKind() == PREFIX_INCREMENT)) {
                leftHandSideAssignment = true;
                scan(tree.getExpression(), null);
                leftHandSideAssignment = false;
            } else {
                super.visitUnary(tree, null);
            }
            return null;
        }

        @Override
        public Void visitErroneous(ErroneousTree tree, Void unused) {
            return scan(tree.getErrorTrees(), null);
        }

        /**
         * Looks at method invocations and removes the invoked private methods from {@code
         * #unusedElements}.
         */
        @Override
        public Void visitMethodInvocation(MethodInvocationTree tree, Void unused) {
            inMethodCall++;
            super.visitMethodInvocation(tree, null);
            inMethodCall--;
            return null;
        }
    }

    new FilterUsedVariables().scan(state.getPath(), null);

    for (TreePath unusedPath : unusedElements.values()) {
        Tree unused = unusedPath.getLeaf();
        switch (unused.getKind()) {
        case VARIABLE:
            VariableTree unusedVar = (VariableTree) unused;
            String element;
            VarSymbol symbol = getSymbol(unusedVar);
            switch (symbol.getKind()) {
            case FIELD:
                element = "Field";
                break;
            case LOCAL_VARIABLE:
                element = "Local variable";
                break;
            case PARAMETER:
                element = "Parameter";
                break;
            default:
                element = "Variable";
                break;
            }
            ImmutableList<SuggestedFix> fixes;
            switch (symbol.getKind()) {
            case LOCAL_VARIABLE:
            case FIELD:
                fixes = buildUnusedVarFixes(symbol, usageSites.get(symbol), state);
                break;
            case PARAMETER:
                fixes = buildUnusedParameterFixes(symbol, usageSites.get(symbol), state);
                break;
            default:
                fixes = ImmutableList.of();
            }
            state.reportMatch(buildDescription(unused)
                    .setMessage(String.format("%s '%s' is never read.", element, unusedVar.getName()))
                    .addAllFixes(fixes).build());
            break;
        default:
            break;
        }
    }
    return Description.NO_MATCH;
}