Example usage for java.util List equals

List of usage examples for java.util List equals

Introduction

In this page you can find the example usage for java.util List equals.

Prototype

boolean equals(Object o);

Source Link

Document

Compares the specified object with this list for equality.

Usage

From source file:edu.umn.cs.spatialHadoop.core.RectangleNN.java

/**
 * @param R//from   w  ww. ja va2 s.c om
 * @param S
 * @param output
 * @return
 * @throws IOException
 */
public static <S1 extends Shape, S2 extends Shape> int SpatialJoin_planeSweep(List<S1> R, List<S2> S,
        ResultCollector2<S1, S2> output, Reporter reporter) throws IOException {
    int count = 0;

    Comparator<Shape> comparator = new Comparator<Shape>() {
        @Override
        public int compare(Shape o1, Shape o2) {
            if (o1.getMBR().x1 == o2.getMBR().x1)
                return 0;
            return o1.getMBR().x1 < o2.getMBR().x1 ? -1 : 1;
        }
    };

    long t1 = System.currentTimeMillis();
    LOG.info("Joining lists " + R.size() + " with " + S.size());
    Collections.sort(R, comparator);
    Collections.sort(S, comparator);

    int i = 0, j = 0;

    try {
        while (i < R.size() && j < S.size()) {
            S1 r;
            S2 s;
            if (comparator.compare(R.get(i), S.get(j)) < 0) {
                r = R.get(i);
                int jj = j;

                while ((jj < S.size()) && ((s = S.get(jj)).getMBR().x1 <= r.getMBR().x2)) {
                    // Check if r and s are overlapping but not the same object
                    // for self join
                    if (r.isIntersected(s) && !r.equals(s)) {
                        if (output != null)
                            output.collect(r, s);
                        count++;
                    }
                    jj++;
                    if (reporter != null)
                        reporter.progress();
                }
                i++;
            } else {
                s = S.get(j);
                int ii = i;

                while ((ii < R.size()) && ((r = R.get(ii)).getMBR().x1 <= s.getMBR().x2)) {
                    if (r.isIntersected(s) && !r.equals(s)) {
                        if (output != null)
                            output.collect(r, s);
                        count++;
                    }
                    ii++;
                    if (reporter != null)
                        reporter.progress();
                }
                j++;
            }
            if (reporter != null)
                reporter.progress();
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    long t2 = System.currentTimeMillis();
    LOG.info("Finished plane sweep in " + (t2 - t1) + " millis and found " + count + " pairs");
    return count;
}

From source file:me.ccrama.redditslide.DragSort.ReorderSubreddits.java

public void doShowSubs() {
    subs = new ArrayList<>(UserSubscriptions.getSubscriptions(this));
    recyclerView = (RecyclerView) findViewById(R.id.subslist);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.setItemAnimator(null);//from ww w.j a v a  2s .  c  o m

    DragSortRecycler dragSortRecycler = new DragSortRecycler();
    dragSortRecycler.setViewHandleId();
    dragSortRecycler.setFloatingAlpha();
    dragSortRecycler.setAutoScrollSpeed();
    dragSortRecycler.setAutoScrollWindow();

    dragSortRecycler.setOnItemMovedListener(new DragSortRecycler.OnItemMovedListener() {
        @Override
        public void onItemMoved(int from, int to) {
            String item = subs.remove(from);
            subs.add(to, item);
            adapter.notifyDataSetChanged();
        }
    });

    dragSortRecycler.setOnDragStateChangedListener(new DragSortRecycler.OnDragStateChangedListener() {
        @Override
        public void onDragStart() {
        }

        @Override
        public void onDragStop() {
        }
    });
    final FloatingActionsMenu fab = (FloatingActionsMenu) findViewById(R.id.add);

    {
        FloatingActionButton collection = (FloatingActionButton) findViewById(R.id.collection);
        Drawable icon = ResourcesCompat.getDrawable(getResources(), R.drawable.collection, null);
        collection.setIconDrawable(icon);
        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fab.collapse();
                if (UserSubscriptions.getMultireddits() != null
                        && !UserSubscriptions.getMultireddits().isEmpty()) {
                    new AlertDialogWrapper.Builder(ReorderSubreddits.this)
                            .setTitle(R.string.create_or_import_multi)
                            .setPositiveButton(R.string.btn_new, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    doCollection();
                                }
                            }).setNegativeButton(R.string.btn_import_multi,
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            final String[] multis = new String[UserSubscriptions
                                                    .getMultireddits().size()];
                                            int i = 0;
                                            for (MultiReddit m : UserSubscriptions.getMultireddits()) {
                                                multis[i] = m.getDisplayName();
                                                i++;
                                            }
                                            MaterialDialog.Builder builder = new MaterialDialog.Builder(
                                                    ReorderSubreddits.this);
                                            builder.title(R.string.reorder_subreddits_title).items(multis)
                                                    .itemsCallbackSingleChoice(-1,
                                                            new MaterialDialog.ListCallbackSingleChoice() {
                                                                @Override
                                                                public boolean onSelection(
                                                                        MaterialDialog dialog, View itemView,
                                                                        int which, CharSequence text) {

                                                                    String name = multis[which];
                                                                    MultiReddit r = UserSubscriptions
                                                                            .getMultiredditByDisplayName(name);
                                                                    StringBuilder b = new StringBuilder();

                                                                    for (MultiSubreddit s : r.getSubreddits()) {
                                                                        b.append(s.getDisplayName());
                                                                        b.append("+");
                                                                    }
                                                                    int pos = addSubAlphabetically(
                                                                            MULTI_REDDIT + r.getDisplayName());
                                                                    UserSubscriptions.setSubNameToProperties(
                                                                            MULTI_REDDIT + r.getDisplayName(),
                                                                            b.toString());
                                                                    adapter.notifyDataSetChanged();
                                                                    recyclerView.smoothScrollToPosition(pos);
                                                                    return false;
                                                                }
                                                            })
                                                    .show();
                                        }
                                    })
                            .show();
                } else {
                    doCollection();
                }
            }
        });
    }
    {
        FloatingActionButton collection = (FloatingActionButton) findViewById(R.id.sub);
        Drawable icon = ResourcesCompat.getDrawable(getResources(), R.drawable.sub, null);
        collection.setIconDrawable(icon);
        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fab.collapse();
                MaterialDialog.Builder b = new MaterialDialog.Builder(ReorderSubreddits.this)
                        .title(R.string.reorder_add_or_search_subreddit).alwaysCallInputCallback()
                        .input(getString(R.string.reorder_subreddit_name), null, false,
                                new MaterialDialog.InputCallback() {
                                    @Override
                                    public void onInput(MaterialDialog dialog, CharSequence raw) {
                                        input = raw.toString();
                                    }
                                })
                        .positiveText(R.string.btn_add).onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                new AsyncGetSubreddit().execute(input);
                            }
                        }).negativeText(R.string.btn_cancel)
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {

                            }
                        });
                b.show();
            }
        });
    }
    {
        FloatingActionButton collection = (FloatingActionButton) findViewById(R.id.domain);
        Drawable icon = ResourcesCompat.getDrawable(getResources(), R.drawable.link, null);
        collection.setIconDrawable(icon);
        collection.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fab.collapse();
                new MaterialDialog.Builder(ReorderSubreddits.this).title(R.string.reorder_add_domain)
                        .alwaysCallInputCallback()
                        .input("example.com" + getString(R.string.reorder_domain_placeholder), null, false,
                                new MaterialDialog.InputCallback() {
                                    @Override
                                    public void onInput(MaterialDialog dialog, CharSequence raw) {
                                        input = raw.toString().replaceAll("\\s", ""); //remove whitespace from input
                                        if (input.contains(".")) {
                                            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(true);
                                        } else {
                                            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
                                        }
                                    }
                                })
                        .positiveText(R.string.btn_add).inputRange(1, 35)
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                try {
                                    String url = (input);

                                    List<String> sortedSubs = UserSubscriptions.sortNoExtras(subs);

                                    if (sortedSubs.equals(subs)) {
                                        subs.add(url);
                                        subs = UserSubscriptions.sortNoExtras(subs);
                                        adapter = new CustomAdapter(subs);
                                        recyclerView.setAdapter(adapter);
                                    } else {
                                        int pos = addSubAlphabetically(url);
                                        adapter.notifyDataSetChanged();
                                        recyclerView.smoothScrollToPosition(pos);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    //todo make this better
                                    new AlertDialogWrapper.Builder(ReorderSubreddits.this)
                                            .setTitle(R.string.reorder_url_err)
                                            .setMessage(R.string.misc_please_try_again).show();

                                }
                            }

                        }).negativeText(R.string.btn_cancel)
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(MaterialDialog dialog, DialogAction which) {

                            }
                        }).show();
            }
        });
    }
    recyclerView.addItemDecoration(dragSortRecycler);
    recyclerView.addOnItemTouchListener(dragSortRecycler);
    recyclerView.addOnScrollListener(dragSortRecycler.getScrollListener());
    dragSortRecycler.setViewHandleId();

    if (subs != null && !subs.isEmpty()) {
        adapter = new CustomAdapter(subs);
        //  adapter.setHasStableIds(true);
        recyclerView.setAdapter(adapter);
    } else {
        subs = new ArrayList<>();
    }

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if (recyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) {
                diff += dy;
            } else {
                diff = 0;
            }
            if (dy <= 0 && fab.getId() != 0) {

            } else {
                fab.collapse();
            }

        }
    });
}

From source file:relationalFramework.RelationalRule.java

/**
 * Sets this rule's query parameters (replaceable variables). Generally
 * these are just goal args.// w w w .  ja  va 2 s  .  c o  m
 * 
 * @param queryParameters
 *            The parameters to set.
 * @param True
 *            if the query parameters changed as a result of this call.
 */
public boolean setQueryParams(List<RelationalArgument> queryParameters) {
    boolean changed = false;
    if (queryParameters != null) {
        if (!queryParameters.equals(queryParams_))
            changed = true;
        queryParams_ = new ArrayList<RelationalArgument>(queryParameters);
    } else {
        queryParams_ = null;
        changed = true;
    }

    if (changed)
        statesSeen_ = 0;

    return changed;
}

From source file:com.google.appinventor.components.runtime.GameClient.java

private void processInstanceLists(JSONObject instanceLists) {
    try {/*from w w w .  j  a v  a2s.c o m*/
        joinedInstances = JsonUtil.getStringListFromJsonArray(instanceLists.getJSONArray(JOINED_LIST_KEY));

        publicInstances = JsonUtil.getStringListFromJsonArray(instanceLists.getJSONArray(PUBLIC_LIST_KEY));

        List<String> receivedInstancesInvited = JsonUtil
                .getStringListFromJsonArray(instanceLists.getJSONArray(INVITED_LIST_KEY));

        if (!receivedInstancesInvited.equals(InvitedInstances())) {
            List<String> oldList = invitedInstances;
            invitedInstances = receivedInstancesInvited;
            List<String> newInvites = new ArrayList<String>(receivedInstancesInvited);
            newInvites.removeAll(oldList);

            for (final String instanceInvited : newInvites) {
                Invited(instanceInvited);
            }
        }

    } catch (JSONException e) {
        Log.w(LOG_TAG, e);
        Info("Instance lists failed to parse.");
    }
}

From source file:org.apache.hadoop.hive.ql.parse.CommonSubtreeDetect.java

private void removeCommonPart(HashSet<List<Object>> commonList) {
    HashSet<List<Object>> commonl = new HashSet<List<Object>>();
    Iterator<List<Object>> listIter = commonList.iterator();
    while (listIter.hasNext()) {
        List<Object> l = listIter.next();
        Iterator<List<Object>> tmpIter = commonList.iterator();
        while (tmpIter.hasNext()) {
            List<Object> tmpl = tmpIter.next();
            if (!l.equals(tmpl) && l.containsAll(tmpl)) {
                commonl.add(tmpl);/*from w w w  . jav  a2 s. c om*/
            }
        }
        //remove list that don't include operator
        boolean visitedOp = false;
        for (int i = 0; i < l.size(); i++) {
            if (l.get(i) instanceof Operator<?>) {
                visitedOp = true;
                break;
            }
        }
        if (visitedOp == false) {
            listIter.remove();
            continue;
        }
    }

    //merge common sub optree
    for (List<Object> list : commonl) {
        commonList.remove(list);
    }
}

From source file:com.alibaba.otter.node.etl.select.selector.MessageParser.java

/**
 * ?canal?Event<br>/*from  w w  w. j  av  a 2  s . c  o m*/
 * Oracle:?. <br>
 * <i>insert:afterColumns???<br>
 * <i>delete:beforeColumns???<br>
 * <i>update:before???after???,????<br>
 * Mysql:??????.<br>
 * <i>insert:afterColumns???<br>
 * <i>delete:beforeColumns???<br>
 * <i>update:beforeColumns???,afterColumns???<br>
 */
private EventData internParse(Pipeline pipeline, Entry entry, RowChange rowChange, RowData rowData) {
    EventData eventData = new EventData();
    eventData.setTableName(entry.getHeader().getTableName());
    eventData.setSchemaName(entry.getHeader().getSchemaName());
    eventData.setEventType(EventType.valueOf(rowChange.getEventType().name()));
    eventData.setExecuteTime(entry.getHeader().getExecuteTime());
    EventType eventType = eventData.getEventType();
    TableInfoHolder tableHolder = null;

    if (!StringUtils.equalsIgnoreCase(pipeline.getParameters().getSystemSchema(), eventData.getSchemaName())) {
        boolean useTableTransform = pipeline.getParameters().getUseTableTransform();
        Table table = null;
        DataMedia dataMedia = ConfigHelper.findSourceDataMedia(pipeline, eventData.getSchemaName(),
                eventData.getTableName());
        eventData.setTableId(dataMedia.getId());
        if (useTableTransform || dataMedia.getSource().getType().isOracle()) {// oracle???meta
            // ?table meta??table?
            // oracle erosa?????erosa?
            DbDialect dbDialect = dbDialectFactory.getDbDialect(pipeline.getId(),
                    (DbMediaSource) dataMedia.getSource());
            table = dbDialect.findTable(eventData.getSchemaName(), eventData.getTableName());// meta?
            if (table == null) {
                logger.warn("find table[{}.{}] is null , may be drop table.", eventData.getSchemaName(),
                        eventData.getTableName());
            }
            tableHolder = new TableInfoHolder(dbDialect, table, useTableTransform);
        }
    }

    List<Column> beforeColumns = rowData.getBeforeColumnsList();
    List<Column> afterColumns = rowData.getAfterColumnsList();
    String tableName = eventData.getSchemaName() + "." + eventData.getTableName();

    // ??all columns
    boolean isRowMode = pipeline.getParameters().getSyncMode().isRow(); // rowMode??updated
    boolean needAllColumns = isRowMode || checkNeedAllColumns(pipeline);

    // ??
    Map<String, EventColumn> keyColumns = new LinkedHashMap<String, EventColumn>();
    // ??
    Map<String, EventColumn> oldKeyColumns = new LinkedHashMap<String, EventColumn>();
    // ??
    Map<String, EventColumn> notKeyColumns = new LinkedHashMap<String, EventColumn>();

    if (eventType.isInsert()) {
        for (Column column : afterColumns) {
            if (isKey(tableHolder, tableName, column)) {
                keyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            } else {
                // mysql 
                notKeyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            }
        }
    } else if (eventType.isDelete()) {
        for (Column column : beforeColumns) {
            if (isKey(tableHolder, tableName, column)) {
                keyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            } else {
                // mysql 
                notKeyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            }
        }
    } else if (eventType.isUpdate()) {
        // ???.
        for (Column column : beforeColumns) {
            if (isKey(tableHolder, tableName, column)) {
                oldKeyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
                // ?new
                // key,mysql5.6?minimal?,after?,?before
                keyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            } else {
                if (needAllColumns && entry.getHeader().getSourceType() == CanalEntry.Type.ORACLE) {
                    // ?oracle?update?aftercolume
                    notKeyColumns.put(column.getName(), copyEventColumn(column, isRowMode, tableHolder));
                }
            }
        }
        for (Column column : afterColumns) {
            if (isKey(tableHolder, tableName, column)) {
                // ???
                keyColumns.put(column.getName(), copyEventColumn(column, true, tableHolder));
            } else if (needAllColumns || entry.getHeader().getSourceType() == CanalEntry.Type.ORACLE
                    || column.getUpdated()) {
                // update?oraclemysql?????,oracle??;
                // mysql??????????.
                // oracleafter?

                boolean isUpdate = true;
                if (entry.getHeader().getSourceType() == CanalEntry.Type.MYSQL) { // mysqlafter??,oracleafter?
                    isUpdate = column.getUpdated();
                }
                notKeyColumns.put(column.getName(),
                        copyEventColumn(column, isRowMode || isUpdate, tableHolder));// rowModeupdated
            }
        }

        if (entry.getHeader().getSourceType() == CanalEntry.Type.ORACLE) { // oracle?
            checkUpdateKeyColumns(oldKeyColumns, keyColumns);
        }
    }

    List<EventColumn> keys = new ArrayList<EventColumn>(keyColumns.values());
    List<EventColumn> oldKeys = new ArrayList<EventColumn>(oldKeyColumns.values());
    List<EventColumn> columns = new ArrayList<EventColumn>(notKeyColumns.values());

    Collections.sort(keys, new EventColumnIndexComparable());
    Collections.sort(oldKeys, new EventColumnIndexComparable());
    Collections.sort(columns, new EventColumnIndexComparable());
    if (!keyColumns.isEmpty()) {
        eventData.setKeys(keys);
        if (eventData.getEventType().isUpdate() && !oldKeys.equals(keys)) { // update??,old
                                                                            // keys??
            eventData.setOldKeys(oldKeys);
        }
        eventData.setColumns(columns);
        // } else if (CanalEntry.Type.MYSQL ==
        // entry.getHeader().getSourceType()) {
        // // ??mysql?
        // if (eventType.isUpdate()) {
        // List<EventColumn> oldColumns = new ArrayList<EventColumn>();
        // List<EventColumn> newColumns = new ArrayList<EventColumn>();
        // for (Column column : beforeColumns) {
        // oldColumns.add(copyEventColumn(column, true, tableHolder));
        // }
        //
        // for (Column column : afterColumns) {
        // newColumns.add(copyEventColumn(column, true, tableHolder));
        // }
        // Collections.sort(oldColumns, new EventColumnIndexComparable());
        // Collections.sort(newColumns, new EventColumnIndexComparable());
        // eventData.setOldKeys(oldColumns);// ??
        // eventData.setKeys(newColumns);// ??????
        // } else {
        // // ??
        // eventData.setKeys(columns);
        // }
    } else {
        throw new SelectException(
                "this rowdata has no pks , entry: " + entry.toString() + " and rowData: " + rowData);
    }

    return eventData;
}

From source file:org.apache.druid.segment.IndexMergerV9.java

private TimeAndDimsIterator makeMergedTimeAndDimsIterator(final List<IndexableAdapter> indexes,
        final List<String> mergedDimensions, final List<String> mergedMetrics,
        final Function<List<TransformableRowIterator>, TimeAndDimsIterator> rowMergerFn,
        final Map<String, DimensionHandler> handlers, final List<DimensionMergerV9> mergers) {
    List<TransformableRowIterator> perIndexRowIterators = Lists.newArrayListWithCapacity(indexes.size());
    for (int i = 0; i < indexes.size(); ++i) {
        final IndexableAdapter adapter = indexes.get(i);
        TransformableRowIterator target = adapter.getRows();
        if (!mergedDimensions.equals(adapter.getDimensionNames())
                || !mergedMetrics.equals(adapter.getMetricNames())) {
            target = makeRowIteratorWithReorderedColumns(mergedDimensions, mergedMetrics, handlers, adapter,
                    target);// www .j a  v a  2  s . co  m
        }
        perIndexRowIterators.add(IndexMerger.toMergedIndexRowIterator(target, i, mergers));
    }
    return rowMergerFn.apply(perIndexRowIterators);
}

From source file:au.org.ala.delta.editor.slotfile.model.SlotFileDataSet.java

private void changeControllingStates(VOControllingDesc controlling, List<Integer> stateIds) {
    int attrId = controlling.getUniId();

    if (stateIds.size() == 0) {
        deleteControlling(attrId);/*from   ww  w.  j a v a  2 s.c o  m*/
    }

    // Work around for ISSUE 243 - controlling character descriptors were not being assigned numbers in the
    // delta master - which leaves existing data sets vulnerable to ISSUE 243 despite the root caused being
    // addressed.
    //int attrNo = getVOP().getDeltaMaster().attrNoFromUniId(attrId);
    //if (attrNo > 0) {
    List<Integer> oldStateIds = controlling.readStateIds();
    Collections.sort(stateIds);

    if (!stateIds.equals(oldStateIds)) {
        controlling.writeStateIds(stateIds);
    }
    //}
}

From source file:com.pivotal.hawq.mapreduce.TPCHClusterTester.java

@Override
protected void testTPCHTable(HAWQTPCHSpec tpchSpec, String tableName) throws Exception {

    String caseName = tpchSpec.toString();
    System.out.println("Executing test case: " + caseName);

    final File caseFolder = new File(FT_TEST_FOLDER, caseName);
    final File answerFile = new File(caseFolder, tableName + ".ans");
    final File outputFile = new File(caseFolder, tableName + ".out");

    if (caseFolder.exists()) {
        FileUtils.deleteDirectory(caseFolder);
    }//from   ww w. java 2 s  . c o  m
    caseFolder.mkdir();

    Connection conn = null;
    List<String> answers;
    try {
        conn = MRFormatTestUtils.getTestDBConnection();

        // 1. load TPCH data
        Map<String, String> rs = HAWQJdbcUtils.executeSafeQueryForSingleRow(conn, "SHOW default_segment_num;");
        int segnum = Integer.parseInt(rs.get("default_segment_num"));
        MRFormatTestUtils.runShellCommand(tpchSpec.getLoadCmd(segnum));

        // 2. generate answer
        answers = MRFormatTestUtils.dumpTable(conn, tableName);
        Collections.sort(answers);
        Files.write(Joiner.on('\n').join(answers).getBytes(), answerFile);

    } finally {
        HAWQJdbcUtils.closeConnection(conn);
    }

    // 3. run input format driver
    final Path hdfsOutput = new Path("/temp/hawqinputformat/part-r-00000");
    int exitCode = MRFormatTestUtils.runMapReduceOnCluster(tableName, hdfsOutput.getParent(), null);
    Assert.assertEquals(0, exitCode);

    // 4. copy hdfs output to local
    MRFormatTestUtils.runShellCommand(
            String.format("hadoop fs -copyToLocal %s %s", hdfsOutput.toString(), outputFile.getPath()));

    // 5. compare result
    List<String> outputs = Files.readLines(outputFile, Charsets.UTF_8);

    if (!answers.equals(outputs))
        Assert.fail(String.format("HAWQInputFormat output for table %s differs with DB output:\n%s\n%s",
                tableName, answerFile, outputFile));

    System.out.println("Successfully finish test case: " + caseName);
}

From source file:io.hops.security.TestUsersGroups.java

public void testUsersGroupsCache(int cacheTime, int cacheSize) throws Exception {
    Configuration conf = new Configuration();
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SECS, Integer.toString(cacheTime));
    conf.set(CommonConfigurationKeys.HOPS_UG_CACHE_SIZE, Integer.toString(cacheSize));
    HdfsStorageFactory.resetDALInitialized();
    HdfsStorageFactory.setConfiguration(conf);
    HdfsStorageFactory.formatStorage();/*from  w  ww  .  ja  va  2 s  .co  m*/
    UsersGroups.createSyncRow();

    String currentUser = "user0";

    String[] groups = new String[3];
    for (int i = 0; i < 3; i++) {
        groups[i] = "group" + i;
    }

    try {
        UsersGroups.getUserID(currentUser);
    } catch (UserNotFoundException e) {
    }

    for (String group : groups) {
        try {
            UsersGroups.getGroupID(group);
        } catch (GroupNotFoundException e) {
        }
    }

    UsersGroups.addUser(currentUser);

    for (String group : groups) {
        UsersGroups.addGroup(group);
    }

    for (String group : groups) {
        try {
            UsersGroups.addGroup(group);
        } catch (GroupAlreadyExistsException e) {
        }
    }

    try {
        UsersGroups.addUser(currentUser);
    } catch (UserAlreadyExistsException e) {
    }

    //user0 -> {group0, group1}
    UsersGroups.addUserToGroups(currentUser, Arrays.copyOfRange(groups, 0, 2));

    try {
        UsersGroups.addUserToGroup(currentUser, groups[0]);
    } catch (UserAlreadyInGroupException e) {
    }

    int userId = UsersGroups.getUserID(currentUser);
    assertNotEquals(userId, 0);
    assertEquals(currentUser, UsersGroups.getUser(userId));
    List<String> cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[0], groups[1])));

    for (int i = 0; i < 2; i++) {
        int groupId = UsersGroups.getGroupID(groups[i]);
        assertNotEquals(groupId, 0);
        assertEquals(groups[i], UsersGroups.getGroup(groupId));
    }

    assertNotEquals(UsersGroups.getGroupID(groups[2]), 0);

    //remove group group0
    UsersGroups.removeGroup(groups[0]);

    try {
        UsersGroups.getGroupID(groups[0]);
    } catch (GroupNotFoundException e) {
    }

    cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[1])));

    //remover user from group1
    UsersGroups.removeUserFromGroup(currentUser, groups[1]);

    UsersGroups.getGroupID(groups[1]);
    UsersGroups.getUserID(currentUser);
    try {
        UsersGroups.getGroups(currentUser);
    } catch (GroupsNotFoundForUserException e) {
    }

    //remove group1
    UsersGroups.removeGroup(groups[1]);

    try {
        UsersGroups.getGroupID(groups[1]);
    } catch (GroupNotFoundException e) {
    }

    try {
        UsersGroups.getGroups(currentUser);
    } catch (GroupsNotFoundForUserException e) {
    }

    // append group to user: user0 -> {group2}
    UsersGroups.addUserToGroup(currentUser, groups[2]);

    cachedGroups = UsersGroups.getGroups(currentUser);
    assertNotNull(cachedGroups);
    assertTrue(cachedGroups.equals(Arrays.asList(groups[2])));

    // remove user and group
    UsersGroups.removeUser(currentUser);
    UsersGroups.removeGroup(groups[2]);
    try {
        UsersGroups.getUserID(currentUser);
    } catch (UserNotFoundException e) {
    }
    try {
        UsersGroups.getGroupID(groups[2]);
    } catch (GroupNotFoundException e) {
    }
    try {
        UsersGroups.getGroups(currentUser);
    } catch (UserNotFoundException e) {
    }
}