Example usage for java.util Comparator Comparator

List of usage examples for java.util Comparator Comparator

Introduction

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

Prototype

Comparator

Source Link

Usage

From source file:nl.surfnet.coin.selfservice.provisioner.SAMLProvisioner.java

@Override
public UserDetails provisionUser(Assertion assertion) {

    CoinUser coinUser = new CoinUser();

    final String idpId = getAuthenticatingAuthority(assertion);

    List<InstitutionIdentityProvider> institutionIdentityProviders = csa.getInstitutionIdentityProviders(idpId);

    if (CollectionUtils.isEmpty(institutionIdentityProviders)) {
        //duhh, fail fast, big problems
        throw new IllegalArgumentException(
                "Csa#getInstitutionIdentityProviders('" + idpId + "') returned zero result");
    }//from   w w w .  j  av a2  s. co  m
    if (institutionIdentityProviders.size() == 1) {
        //most common case
        InstitutionIdentityProvider idp = institutionIdentityProviders.get(0);
        coinUser.setIdp(idp);
        coinUser.addInstitutionIdp(idp);
    } else {
        coinUser.setIdp(getCurrentIdp(idpId, institutionIdentityProviders));
        coinUser.getInstitutionIdps().addAll(institutionIdentityProviders);
        Collections.sort(coinUser.getInstitutionIdps(), new Comparator<InstitutionIdentityProvider>() {
            @Override
            public int compare(final InstitutionIdentityProvider lh, final InstitutionIdentityProvider rh) {
                return lh.getName().compareTo(rh.getName());
            }
        });
    }

    coinUser.setUid(getValueFromAttributeStatements(assertion, uuidAttribute));
    coinUser.setDisplayName(getValueFromAttributeStatements(assertion, DISPLAY_NAME));
    coinUser.setEmail(getValueFromAttributeStatements(assertion, EMAIL));
    coinUser.setSchacHomeOrganization(getValueFromAttributeStatements(assertion, SCHAC_HOME));

    coinUser.setAttributeMap(PersonAttributeUtil.getAttributesAsMap(assertion));

    return coinUser;
}

From source file:org.killbill.notificationq.MockNotificationQueue.java

public MockNotificationQueue(final Clock clock, final String svcName, final String queueName,
        final NotificationQueueHandler handler,
        final MockNotificationQueueService mockNotificationQueueService) {

    this.svcName = svcName;
    this.queueName = queueName;
    this.handler = handler;
    this.clock = clock;
    this.hostname = CreatorName.get();
    this.queueService = mockNotificationQueueService;

    this.recordIds = new AtomicLong();

    notifications = new TreeSet<NotificationEventModelDao>(new Comparator<NotificationEventModelDao>() {
        @Override//from  ww w  . j  av a2s. c  o  m
        public int compare(final NotificationEventModelDao o1, final NotificationEventModelDao o2) {
            if (o1.getEffectiveDate().equals(o2.getEffectiveDate())) {
                return o1.getRecordId().compareTo(o2.getRecordId());
            } else {
                return o1.getEffectiveDate().compareTo(o2.getEffectiveDate());
            }
        }
    });
}

From source file:com.netflix.explorers.ExplorersManagerImpl.java

public Collection<Explorer> getExplorers() {
    ArrayList<Explorer> modules = new ArrayList<Explorer>(this.explorers.values());
    Collections.sort(modules, new Comparator<Explorer>() {
        @Override/*  w  w  w  .j a va  2  s.c  o  m*/
        public int compare(Explorer arg0, Explorer arg1) {
            return String.valueOf(arg0.getTitle()).compareToIgnoreCase(String.valueOf(arg1.getTitle()));
        }
    });
    return modules;
}

From source file:azkaban.flow.GroupedExecutableFlow.java

public GroupedExecutableFlow(String id, ExecutableFlow... flows) {
    this.id = id;
    this.flows = flows;
    this.sortedFlows = Arrays.copyOf(this.flows, this.flows.length);
    Arrays.sort(this.sortedFlows, new Comparator<ExecutableFlow>() {
        @Override//w  ww  .j a va  2 s  .co  m
        public int compare(ExecutableFlow o1, ExecutableFlow o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    String[] names = new String[flows.length];
    for (int i = 0; i < flows.length; i++) {
        names[i] = flows[i].getName();
    }
    name = StringUtils.join(names, " + ");

    jobState = Status.READY;
    updateState();
    callbacksToCall = new ArrayList<FlowCallback>();

    theGroupCallback = new GroupedFlowCallback();

    switch (jobState) {
    case SUCCEEDED:
    case COMPLETED:
    case FAILED:
        DateTime theStartTime = new DateTime();
        DateTime theEndTime = new DateTime(0);
        for (ExecutableFlow flow : flows) {
            final DateTime subFlowStartTime = flow.getStartTime();
            if (theStartTime.isAfter(subFlowStartTime)) {
                theStartTime = subFlowStartTime;
            }

            final DateTime subFlowEndTime = flow.getEndTime();
            if (subFlowEndTime != null && subFlowEndTime.isAfter(theEndTime)) {
                theEndTime = subFlowEndTime;
            }
        }

        setAndVerifyParentProps();
        startTime = theStartTime;
        endTime = theEndTime;
        break;
    default:
        // Check for Flows that are "RUNNING"
        boolean allRunning = true;
        List<ExecutableFlow> runningFlows = new ArrayList<ExecutableFlow>();
        DateTime thisStartTime = null;

        for (ExecutableFlow flow : flows) {
            if (flow.getStatus() != Status.RUNNING) {
                allRunning = false;

                final DateTime subFlowStartTime = flow.getStartTime();
                if (subFlowStartTime != null && subFlowStartTime.isBefore(thisStartTime)) {
                    thisStartTime = subFlowStartTime;
                }
            } else {
                runningFlows.add(flow);
            }
        }

        if (allRunning) {
            jobState = Status.RUNNING;
        }

        for (ExecutableFlow runningFlow : runningFlows) {
            final DateTime subFlowStartTime = runningFlow.getStartTime();
            if (subFlowStartTime != null && subFlowStartTime.isBefore(thisStartTime)) {
                thisStartTime = subFlowStartTime;
            }
        }
        setAndVerifyParentProps();

        startTime = thisStartTime;
        endTime = null;

        // Make sure everything is initialized before leaking the pointer to "this".
        // This is just installing the callback in an already running flow.
        for (ExecutableFlow runningFlow : runningFlows) {
            runningFlow.execute(parentProps, theGroupCallback);
        }
    }
}

From source file:com.linkedin.pinot.core.indexsegment.utils.MmapMemoryManagerTest.java

@Test
public void testLargeBlocks() throws Exception {
    final String segmentName = "someSegment";
    PinotDataBufferMemoryManager memoryManager = new MmapMemoryManager(_tmpDir, segmentName);
    final long s1 = 2 * MmapMemoryManager.getDefaultFileLength();
    final long s2 = 1000;
    final String col1 = "col1";
    final String col2 = "col2";
    final byte value = 34;
    PinotDataBuffer buf1 = memoryManager.allocate(s1, col1);

    // Verify that we can write to and read from the buffer
    ByteBuffer b1 = buf1.toDirectByteBuffer(0, (int) s1);
    b1.putLong(0, s1);//ww  w. ja v a 2s . c om
    Assert.assertEquals(b1.getLong(0), s1);
    b1.put((int) s1 - 1, value);
    Assert.assertEquals(b1.get((int) s1 - 1), value);

    PinotDataBuffer buf2 = memoryManager.allocate(s2, col2);
    ByteBuffer b2 = buf2.toDirectByteBuffer(0, (int) s2);
    b2.putLong(0, s2);
    Assert.assertEquals(b2.getLong(0), s2);

    File dir = new File(_tmpDir);
    File[] files = dir.listFiles();
    Assert.assertEquals(files.length, 2);

    Arrays.sort(files, new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            return o1.getName().compareTo(o2.getName());
        }
    });

    String fileName = files[0].getName();
    Assert.assertTrue(fileName.contains(segmentName));

    fileName = files[1].getName();
    Assert.assertTrue(fileName.contains(segmentName));

    buf1.close();
    buf2.close();

    memoryManager.close();

    List<Pair<MmapUtils.AllocationContext, Integer>> allocationContexts = MmapUtils.getAllocationsAndSizes();
    Assert.assertEquals(allocationContexts.size(), 0);
    Assert.assertEquals(new File(_tmpDir).listFiles().length, 0);
}

From source file:it.andtorg.pdi.sdmx.SdmxStepMetaLoadSaveTest.java

@Before
public void setUp() throws Exception {

    List<String> attributes = Arrays.asList("provider", "dataflow", "sdmxQuery", "dimensionToCodes", "fields");

    Map<String, String> getters = new HashMap<>();
    getters.put("provider", "getProvider");
    getters.put("dataflow", "getDataflow");
    getters.put("sdmxQuery", "getSdmxQuery");
    getters.put("dimensionToCodes", "getDimensionToCodes");
    getters.put("fields", "getInputFields");

    Map<String, String> setters = new HashMap<>();
    setters.put("provider", "setProvider");
    setters.put("fields", "setInputFields");

    Map<String, FieldLoadSaveValidator<?>> attributeValidators = new HashMap<>();
    Map<String, FieldLoadSaveValidator<?>> typeValidators = new HashMap<>();

    @SuppressWarnings("Convert2Lambda")
    Comparator<Dimension> comparator = new Comparator<Dimension>() {
        @Override/*from  w w w.  j a v a2  s  . c om*/
        public int compare(Dimension o1, Dimension o2) {
            return o1.getPosition() - o2.getPosition();
        }
    };

    attributeValidators.put("dimensionToCodes", new CustomMapLoadSaveValidator<>(
            new DimensionLoadSaveValidator(), new StringLoadSaveValidator(), comparator, 10));

    typeValidators.put(Provider.class.getCanonicalName(), new ProviderValidator());
    typeValidators.put(Dataflow.class.getCanonicalName(), new DataflowValidator());
    typeValidators.put(SdmxInputField[].class.getCanonicalName(),
            new ArrayLoadSaveValidator<>(new SdmxInputFieldValidator(), 10));

    tester = new LoadSaveTester(SdmxStepMeta.class, attributes, getters, setters, attributeValidators,
            typeValidators);
}

From source file:edu.sabanciuniv.sentilab.sare.models.setcover.DocumentSetCover.java

private Pair<List<SetCoverDocument>, List<SetCoverDocument>> splitByCoverage(double weightCoverage) {
    List<SetCoverDocument> covered = Lists.newArrayList();
    List<SetCoverDocument> uncovered = Lists.newArrayList();
    List<SetCoverDocument> setCoverDocuments = Collections
            .synchronizedList(Lists.newArrayList(this.getAllDocuments()));

    double totalWeight = this.getTotalWeight();
    double accumulatedWeight = 0;

    // sort set cover.
    Iterator<SetCoverDocument> iterator = Ordering.from(new Comparator<SetCoverDocument>() {
        @Override/*  w w w . j ava 2s  . c  o  m*/
        public int compare(SetCoverDocument o1, SetCoverDocument o2) {
            return (int) ((o2.getWeight() - o1.getWeight()) * 100);
        }
    }).immutableSortedCopy(setCoverDocuments).iterator();

    // get all the useful ones.
    while (iterator.hasNext()) {
        if (accumulatedWeight >= weightCoverage * totalWeight) {
            break;
        }

        SetCoverDocument document = iterator.next();
        accumulatedWeight += document.getWeight();
        covered.add(document);
    }

    while (iterator.hasNext()) {
        uncovered.add(iterator.next());
    }

    return new ImmutablePair<List<SetCoverDocument>, List<SetCoverDocument>>(covered, uncovered);
}

From source file:com.knewton.mapreduce.util.RandomStudentEventGenerator.java

/**
 * Helper method for generating decorated increasing student ids. Used by
 * {@link WriteSampleSSTable} for writing a sorted SSTable.
 *
 * @return A list of byte buffers with student IDs
 *//*w ww . ja va  2s.c  o m*/
public static List<ByteBuffer> getStudentIds(int numberOfStudents) {
    long studentId = 1000000L;
    List<ByteBuffer> studentIds = Lists.newArrayListWithCapacity(numberOfStudents);

    for (int i = 0; i < numberOfStudents; i++) {
        ByteBuffer bb = ByteBuffer.wrap(new byte[8]);
        bb.putLong(studentId++);
        bb.rewind();
        studentIds.add(bb);
    }

    Collections.sort(studentIds, new Comparator<ByteBuffer>() {
        @Override
        public int compare(ByteBuffer o1, ByteBuffer o2) {
            DecoratedKey dk1 = StorageService.getPartitioner().decorateKey(o1);
            DecoratedKey dk2 = StorageService.getPartitioner().decorateKey(o2);
            return dk1.compareTo(dk2);
        }
    });

    return studentIds;
}

From source file:ca.ualberta.cs.expenseclaim.dao.ExpenseItemDao.java

private void save(Context context) {
    Collections.sort(itemList, new Comparator<ExpenseItem>() {

        @Override// w  w w. ja  v a 2  s .  c om
        public int compare(ExpenseItem lhs, ExpenseItem rhs) {
            return lhs.getDate().compareTo(rhs.getDate());
        }

    });
    File file = new File(context.getFilesDir(), FILENAME);
    PrintWriter writer = null;
    try {
        writer = new PrintWriter(file);
        for (ExpenseItem i : itemList) {
            JSONObject jo = new JSONObject();
            jo.put("id", i.getId());
            jo.put("claimId", i.getClaimId());
            jo.put("category", i.getCategory());
            jo.put("description", i.getDescription());
            jo.put("date", i.getDate().getTime());
            jo.put("amount", i.getAmount());
            jo.put("unit", i.getUnit());
            writer.println(jo.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (writer != null) {
            writer.close();
        }
    }

}

From source file:com.properned.application.ManageLocaleController.java

public void initializeList() {
    logger.info("Initialize locale list");
    list = FXCollections.observableArrayList(multiLanguageProperties.getMapPropertiesByLocale().keySet());

    SortedList<Locale> sortedList = new SortedList<>(list, new Comparator<Locale>() {
        @Override//from   www  .  j ava2 s.  c  o  m
        public int compare(Locale o1, Locale o2) {
            return o1.toString().compareTo(o2.toString());
        }
    });

    localeList.setItems(sortedList);

    localeList.setCellFactory(c -> new LocaleListCell(multiLanguageProperties, this));

    list.addListener(new ListChangeListener<Locale>() {
        @Override
        public void onChanged(Change<? extends Locale> c) {
            if (c.next()) {
                if (c.wasAdded()) {
                    List<? extends Locale> addedSubList = c.getAddedSubList();
                    for (Locale locale : addedSubList) {
                        try {
                            MultiLanguageProperties.getInstance().addLocale(locale);
                        } catch (IOException e) {
                            Properned.getInstance().showError(
                                    MessageReader.getInstance().getMessage("manageLocale.error.errorAddLocale"),
                                    e);
                        }
                    }

                }
            }
        }
    });
}