Example usage for javafx.util Pair Pair

List of usage examples for javafx.util Pair Pair

Introduction

In this page you can find the example usage for javafx.util Pair Pair.

Prototype

public Pair(@NamedArg("key") K key, @NamedArg("value") V value) 

Source Link

Document

Creates a new pair

Usage

From source file:Main.java

public static <A, B> List<Pair<A, B>> zip(final List<A> as, final List<B> bs) {
    return IntStream.range(0, Math.min(as.size(), bs.size())).mapToObj(i -> new Pair<>(as.get(i), bs.get(i)))
            .collect(Collectors.toList());
}

From source file:ijfx.ui.utils.NamingUtils.java

public Pair<String, String> separateExtension(String filename) {

    String extension = FilenameUtils.getExtension(filename);
    String basename = FilenameUtils.getBaseName(filename);
    return new Pair<>(basename, extension);
}

From source file:dev.archiecortez.jfacelog.dialogs.NewPassDialog.java

public NewPassDialog() throws IOException {
    super();/*from w w  w  . ja  v  a  2  s  . c  o m*/
    FXMLLoader loader = new FXMLLoader(getClass().getResource("newpassdialog.fxml"));
    loader.setController(this);

    Parent root = loader.load();
    this.getDialogPane().setContent(root);
    getDialogPane().getButtonTypes().add(ButtonType.APPLY);
    getDialogPane().getButtonTypes().add(ButtonType.CANCEL);
    getDialogPane().lookupButton(ButtonType.APPLY).disableProperty()
            .bind(newPassword.textProperty().isNotEqualTo(newPasswordCopy.textProperty())
                    .or(newPassword.textProperty().isEmpty()).or(oldPassword.textProperty().isEmpty()));

    setResultConverter(value -> {
        if (value == ButtonType.APPLY) {
            return new Pair<>(oldPassword.getText(), newPassword.getText());
        } else {
            return null;
        }
    });
}

From source file:cz.fi.muni.pa165.service.GameServiceImpl.java

@Override
public List<List<Pair>> generateSeasonMatches() {
    List<List<Pair>> result = new ArrayList<>();

    List<Team> teams = teamDao.findByAll();
    Collections.shuffle(teams);/*from   ww  w  . j a  va 2 s . c  o m*/

    //add ghost team if odd number of teams
    if (teams.size() % 2 != 0)
        teams.add(new Team(-1L));

    //round robin
    for (int i = 0; i < teams.size() - 1; i++) {
        List<Pair> row = new ArrayList<>();
        for (int j = 0; j < teams.size() / 2; j++) {
            if (teams.get(j).getId() != -1L && teams.get(teams.size() - j - 1).getId() != -1L)
                row.add(new Pair(teams.get(j), teams.get(teams.size() - j - 1)));
        }
        result.add(row);

        Team t = teams.remove(teams.size() - 1);
        teams.add(1, t);
    }

    Collections.shuffle(result);
    return result;
}

From source file:org.fineract.module.stellar.listener.StellarAdjustOfferEventListener.java

@Override
public void onApplicationEvent(final StellarAdjustOfferEvent event) {
    final AccountBridgePersistency accountBridge = accountBridgeRepository
            .findByMifosTenantId(event.getMifosAccountId());

    retrySynchronizer.sync(new Pair<>(event.getMifosAccountId(), event.getAssetCode()), () -> {
        final StellarAdjustOfferEventPersistency eventSource = this.stellarAdjustOfferEventRepository
                .findOne(event.getEventId());

        if (accountBridge == null) {
            eventSource.setOutstandingRetries(0);
            this.stellarAdjustOfferEventRepository.save(eventSource);
            return;
        }/*from   w w w  . ja  va 2 s. com*/

        final Integer outstandingRetries = eventSource.getOutstandingRetries();
        final Boolean processed = eventSource.getProcessed();
        if (processed || (outstandingRetries <= 0))
            return;

        eventSource.setOutstandingRetries(outstandingRetries - 1);
        this.stellarAdjustOfferEventRepository.save(eventSource);

        try {
            horizonServerUtilities.adjustOffer(accountBridge.getStellarAccountPrivateKey(),
                    StellarAccountId.mainAccount(accountBridge.getStellarVaultAccountId()),
                    event.getAssetCode());

            eventSource.setProcessed(Boolean.TRUE);
            eventSource.setErrorMessage("");
            eventSource.setOutstandingRetries(0);
        } catch (final InvalidConfigurationException | StellarOfferAdjustmentFailedException ex) {
            eventSource.setProcessed(Boolean.FALSE);
            eventSource.setErrorMessage(ex.getMessage());
            if (outstandingRetries == 1) {
                logger.error("Last offer adjustment attempt failed because: {}", ex.getMessage());
            }
        } finally {
            this.stellarAdjustOfferEventRepository.save(eventSource);
        }
    });
}

From source file:fi.vm.kapa.identification.proxy.background.SessionCleanup.java

public void runCleanup() {
    try {//w ww.java  2  s .c  om
        // Using time reference in minutes is good enough for a time frame for expiration
        long failedTTLThreshold = System.currentTimeMillis() - failedSessionsTTL * 60000;
        long activeTTLThreshold = System.currentTimeMillis() - activeSessionsTTL * 60000;

        Map<String, Map<AuthMethod, SessionDTO>> sessionsInCache = sessionHandlingUtils.getSessionsCache();
        List<Pair<String, AuthMethod>> toBeRemoved = new ArrayList<>();

        long originalSize = 0;
        for (Map<AuthMethod, SessionDTO> sessionDTOMap : sessionsInCache.values()) {
            originalSize += sessionDTOMap.size();
        }

        logger.info("Currently there are {} sessions in cache", originalSize);

        sessionsInCache.forEach((key, sessionDTOMap) -> sessionDTOMap.forEach((authMethod, sessionDTO) -> {
            if ((sessionDTO.isValidated() && sessionDTO.getTimestamp() < activeTTLThreshold)
                    || (!sessionDTO.isValidated() && sessionDTO.getTimestamp() < failedTTLThreshold)) {
                toBeRemoved.add(new Pair<>(key, authMethod));
            }
        }));

        toBeRemoved
                .forEach((pair) -> sessionHandlingUtils.removeFromSessionCache(pair.getKey(), pair.getValue()));

        long finalSize = 0;
        for (Map<AuthMethod, SessionDTO> sessionDTOMap : sessionsInCache.values()) {
            finalSize += sessionDTOMap.size();
        }
        logger.info("Removed {} expired sessions from cache", originalSize - finalSize);
    } catch (Exception e) {
        logger.error("Error running session cleanup", e);
    }
}

From source file:it.matjaz.jnumerus.RomanCharMapFactory.java

/**
 * Constructs an array of 13 {@link javafx.util.Pair Pairs}(roman character,
 * its Integer value)./*from  w  w  w .  j ava 2s  .  co m*/
 * <p>
 * Those pairs are used for conversions of whole Strings of roman numerals
 * and vice versa. The pairs are <b>hardcoded</b> since they are constants.
 *
 * <p>
 * The followind table offers a representation of the content of the
 * generated structure:
 *
 * <pre>
 *       Pair
 *      __||__
 *     /      \
 *  i |rom  int
 * ------------
 *  0 |  M 1000
 *  1 | CM  900
 *  2 |  D  500
 *  3 | CD  400
 *  4 |  C  100
 *  5 | XC   90
 *  6 |  L   50
 *  7 | XL   40
 *  8 |  X   10
 *  9 | IX    9
 * 10 |  V    5
 * 11 | IV    4
 * 12 |  I    1
 * </pre>
 *
 * @return Pair[] containing Pairs of roman characters and the respecitve
 * integer values.
 */
public static Pair[] generateCharPairsArray() {
    Pair[] pairsArray = new Pair[] { new Pair("M", 1000), new Pair("CM", 900), new Pair("D", 500),
            new Pair("CD", 400), new Pair("C", 100), new Pair("XC", 90), new Pair("L", 50), new Pair("XL", 40),
            new Pair("X", 10), new Pair("IX", 9), new Pair("V", 5), new Pair("IV", 4), new Pair("I", 1) };
    return pairsArray;
}

From source file:com.flipkart.flux.impl.task.LocalJvmTask.java

@Override
public Pair<Object, FluxError> execute(EventData[] events) {
    Object[] parameters = new Object[events.length];
    Class<?>[] parameterTypes = toInvoke.getParameterTypes();
    try {/*from w  w w  .java  2  s.c o  m*/
        /* TODO
        While this works for methods with all unique param types, it
        will fail for methods where we have mutliple params of the same type.
         */
        ClassLoader classLoader = ((TaskExecutableImpl) toInvoke).getDeploymentUnitClassLoader();
        Class objectMapper = classLoader.loadClass("com.fasterxml.jackson.databind.ObjectMapper");
        Object objectMapperInstance = objectMapper.newInstance();

        for (int i = 0; i < parameterTypes.length; i++) {
            for (EventData anEvent : events) {
                if (Class.forName(anEvent.getType(), true, classLoader).equals(parameterTypes[i])) {
                    parameters[i] = objectMapper.getMethod("readValue", String.class, Class.class).invoke(
                            objectMapperInstance, anEvent.getData(),
                            Class.forName(anEvent.getType(), true, classLoader));
                }
            }
            if (parameters[i] == null) {
                logger.warn("Could not find a paramter of type {} in event list {}", parameterTypes[i], events);
                throw new RuntimeException("Could not find a paramter of type " + parameterTypes[i]);
            }
        }

        Method writeValueAsString = objectMapper.getMethod("writeValueAsString", Object.class);

        final Object returnObject = toInvoke.execute(parameters);
        SerializedEvent serializedEvent = null;
        if (returnObject != null) {
            serializedEvent = new SerializedEvent(returnObject.getClass().getCanonicalName(),
                    (String) writeValueAsString.invoke(objectMapperInstance, returnObject));
        }
        return new Pair<>(serializedEvent, null);
    } catch (Exception e) {
        logger.warn("Bad things happened while trying to execute {}", toInvoke, e);
        return new Pair<>(null, new FluxError(FluxError.ErrorType.runtime, e.getMessage(), e));
    }
}

From source file:com.walmart.gatling.repository.ServerRepository.java

/**
 * Generates a unique tracking and submit the job to the master via the master proxy
 * if the job is properly submitted return the tracking identifier
 * @param jobModel/*  w  ww.ja  va2s . c  o m*/
 * @return
 * @throws Exception
 */
public Optional<String> submitJob(JobModel jobModel) throws Exception {
    String trackingId = UUID.randomUUID().toString();

    TaskEvent taskEvent = new TaskEvent();
    taskEvent.setJobName("gatling");
    taskEvent.setRoleName(jobModel.getRoleId());
    taskEvent.setParameters(Arrays.asList(new Pair<>("0", "-nr"), new Pair<>("1", "-m"), new Pair<>("2", "-s"),
            new Pair<>("3", jobModel.getSimulation())));
    //cmdLine.addArgument("-rf").addArgument(agentConfig.getJob().getResultPath(job.roleId,job.jobId));
    Timeout timeout = new Timeout(6, TimeUnit.SECONDS);
    int success = 0;
    for (int i = 0; i < jobModel.getCount(); i++) {
        Future<Object> future = ask(router,
                new Master.Job(jobModel.getRoleId(), taskEvent, trackingId, agentConfig.getAbortUrl()),
                timeout);
        Object result = Await.result(future, timeout.duration());
        if (result instanceof MasterClientActor.Ok) {
            success++;
            log.debug(
                    "Ok message from server just got here, this indicates the job was successfully posted to the master: {}",
                    result);
        }
    }

    if (success == jobModel.getCount()) {
        log.debug("Job Successfully submitted to master");
        return Optional.of(trackingId);
    }
    return Optional.empty();
}

From source file:ai.grakn.engine.backgroundtasks.InMemoryTaskManager.java

public String scheduleTask(BackgroundTask task, String createdBy, Date runAt, long period,
        JSONObject configuration) {// w  w w. ja v a 2 s  . c o  m
    Boolean recurring = (period != 0);
    String id = stateStorage.newState(task.getClass().getName(), createdBy, runAt, recurring, period,
            configuration);

    // Schedule task to run.
    Date now = new Date();
    long delay = now.getTime() - runAt.getTime();

    try {
        stateStorage.updateState(id, SCHEDULED, this.getClass().getName(), null, null, null, null);

        ScheduledFuture<?> future;
        if (recurring)
            future = schedulingService.scheduleAtFixedRate(runTask(id, task, true), delay, period,
                    MILLISECONDS);
        else
            future = schedulingService.schedule(runTask(id, task, false), delay, MILLISECONDS);

        instantiatedTasks.put(id, new Pair<>(future, task));

    } catch (Throwable t) {
        LOG.error(getFullStackTrace(t));
        stateStorage.updateState(id, FAILED, this.getClass().getName(), null, t, null, null);
        instantiatedTasks.remove(id);

        return null;
    }

    return id;
}