Example usage for org.apache.commons.lang3.tuple Pair getKey

List of usage examples for org.apache.commons.lang3.tuple Pair getKey

Introduction

In this page you can find the example usage for org.apache.commons.lang3.tuple Pair getKey.

Prototype

@Override
public final L getKey() 

Source Link

Document

Gets the key from this pair.

This method implements the Map.Entry interface returning the left element as the key.

Usage

From source file:com.helion3.prism.api.query.QueryBuilder.java

/**
 * Parses a parameter argument./*from  w  ww. j av  a  2 s . c  o  m*/
 *
 * @param session QuerySession current session.
 * @param query Query query being built.
 * @param parameter String argument which should be a parameter
 * @return Optional<ListenableFuture<?>>
 * @throws ParameterException
 */
private static Optional<ListenableFuture<?>> parseParameterFromArgument(QuerySession session, Query query,
        Pair<String, String> parameter) throws ParameterException {
    // Simple validation
    if (parameter.getKey().length() <= 0 || parameter.getValue().length() <= 0) {
        throw new ParameterException("Invalid empty value for parameter \"" + parameter.getKey() + "\".");
    }

    // Find a handler
    Optional<ParameterHandler> optionalHandler = Prism.getParameterHandler(parameter.getKey());
    if (!optionalHandler.isPresent()) {
        throw new ParameterException(
                "\"" + parameter.getKey() + "\" is not a valid parameter. No handler found.");
    }

    ParameterHandler handler = optionalHandler.get();

    // Allows this command source?
    if (!handler.acceptsSource(session.getCommandSource().get())) {
        throw new ParameterException(
                "This command source may not use the \"" + parameter.getKey() + "\" parameter.");
    }

    // Validate value
    if (!handler.acceptsValue(parameter.getValue())) {
        throw new ParameterException(
                "Invalid value \"" + parameter.getValue() + "\" for parameter \"" + parameter.getKey() + "\".");
    }

    return handler.process(session, parameter.getKey(), parameter.getValue(), query);
}

From source file:alfio.util.TemplateManager.java

public static String translate(String template, Locale locale, MessageSource messageSource) {
    StringBuilder sb = new StringBuilder(template.length());

    AST ast = new AST();

    ParserState state = ParserState.START;
    int idx = 0;/*from   w  ww  .  ja  v a 2 s  .c  o m*/
    while (true) {
        Pair<ParserState, Integer> stateAndIdx = state.next(template, idx, ast);
        state = stateAndIdx.getKey();
        idx = stateAndIdx.getValue();
        if (state == ParserState.END) {
            break;
        }
    }

    ast.visit(sb, locale, messageSource);

    return sb.toString();
}

From source file:net.minecraftforge.items.VanillaInventoryCodeHooks.java

/**
 * Copied from TileEntityHopper#captureDroppedItems and added capability support
 * @return Null if we did nothing {no IItemHandler}, True if we moved an item, False if we moved no items
 *//* w ww .j  a v a 2  s. com*/
@Nullable
public static Boolean extractHook(IHopper dest) {
    Pair<IItemHandler, Object> itemHandlerResult = getItemHandler(dest, EnumFacing.UP);
    if (itemHandlerResult == null)
        return null;

    IItemHandler handler = itemHandlerResult.getKey();

    for (int i = 0; i < handler.getSlots(); i++) {
        ItemStack extractItem = handler.extractItem(i, 1, true);
        if (!extractItem.isEmpty()) {
            for (int j = 0; j < dest.getSizeInventory(); j++) {
                ItemStack destStack = dest.getStackInSlot(j);
                if (dest.isItemValidForSlot(j, extractItem)
                        && (destStack.isEmpty() || destStack.getCount() < destStack.getMaxStackSize()
                                && destStack.getCount() < dest.getInventoryStackLimit()
                                && ItemHandlerHelper.canItemStacksStack(extractItem, destStack))) {
                    extractItem = handler.extractItem(i, 1, false);
                    if (destStack.isEmpty())
                        dest.setInventorySlotContents(j, extractItem);
                    else {
                        destStack.grow(1);
                        dest.setInventorySlotContents(j, destStack);
                    }
                    dest.markDirty();
                    return true;
                }
            }
        }
    }

    return false;
}

From source file:net.minecraftforge.items.VanillaInventoryCodeHooks.java

/**
 * Copied from TileEntityHopper#transferItemsOut and added capability support
 *///from w ww. j  ava  2s.  c  o  m
public static boolean insertHook(TileEntityHopper hopper) {
    EnumFacing hopperFacing = BlockHopper.getFacing(hopper.getBlockMetadata());
    Pair<IItemHandler, Object> destinationResult = getItemHandler(hopper, hopperFacing);
    if (destinationResult == null) {
        return false;
    } else {
        IItemHandler itemHandler = destinationResult.getKey();
        Object destination = destinationResult.getValue();
        if (isFull(itemHandler)) {
            return false;
        } else {
            for (int i = 0; i < hopper.getSizeInventory(); ++i) {
                if (!hopper.getStackInSlot(i).isEmpty()) {
                    ItemStack originalSlotContents = hopper.getStackInSlot(i).copy();
                    ItemStack insertStack = hopper.decrStackSize(i, 1);
                    ItemStack remainder = putStackInInventoryAllSlots(hopper, destination, itemHandler,
                            insertStack);

                    if (remainder.isEmpty()) {
                        return true;
                    }

                    hopper.setInventorySlotContents(i, originalSlotContents);
                }
            }

            return false;
        }
    }
}

From source file:alfio.manager.CheckInManager.java

public static String encrypt(String key, String payload) {
    try {//from   ww w  . j av  a 2 s  .  co  m
        Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key);
        Cipher cipher = cipherAndSecret.getKey();
        cipher.init(Cipher.ENCRYPT_MODE, cipherAndSecret.getRight());
        byte[] data = cipher.doFinal(payload.getBytes(StandardCharsets.UTF_8));
        byte[] iv = cipher.getIV();
        return Base64.encodeBase64URLSafeString(iv) + "|" + Base64.encodeBase64URLSafeString(data);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

From source file:fr.landel.utils.commons.MapUtils2.java

/**
 * Create a map from {@code objects}.// ww  w .  j  av  a  2 s  .  c  o m
 * 
 * <pre>
 * Map&lt;String, String&gt; map = MapUtils2.newMap(TreeMap::new, Pair.of("key1", "value1"), Pair.of("key2", "value2"));
 * 
 * // equivalent
 * Map&lt;String, String&gt; map = new TreeMap&lt;&gt;();
 * map.put("key1", "value1");
 * map.put("key2", "value2");
 * </pre>
 * 
 * @param mapProvider
 *            map constructor supplier
 * @param objects
 *            objects pair to put in the new {@link Map}
 * @param <K>
 *            the type of map key
 * @param <V>
 *            the type of map value
 * @param <M>
 *            the type of map
 * @return the new {@link Map}
 * @throws NullPointerException
 *             if {@code mapProvider} is {@code null}
 * @throws IllegalArgumentException
 *             if {@code objects} is {@code null} or empty
 */
@SafeVarargs
public static <K, V, M extends Map<K, V>> M newMap(final Supplier<M> mapProvider, Pair<K, V>... objects) {
    Objects.requireNonNull(mapProvider);
    ObjectUtils.requireNonNull(objects, ERROR_OBJECTS_SUPPLIER);

    final M map = mapProvider.get();

    for (Pair<K, V> pair : objects) {
        map.put(pair.getKey(), pair.getValue());
    }

    return map;
}

From source file:alfio.manager.CheckInManager.java

public static String decrypt(String key, String payload) {
    try {//  w  w  w.j a  va 2 s  .com
        Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key);
        Cipher cipher = cipherAndSecret.getKey();
        String[] splitted = payload.split(Pattern.quote("|"));
        byte[] iv = Base64.decodeBase64(splitted[0]);
        byte[] body = Base64.decodeBase64(splitted[1]);
        cipher.init(Cipher.DECRYPT_MODE, cipherAndSecret.getRight(), new IvParameterSpec(iv));
        byte[] decrypted = cipher.doFinal(body);
        return new String(decrypted, StandardCharsets.UTF_8);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.acmutv.ontoqa.core.parser.SimpleSltagParser.java

private static void processSubstitutions(ParserState dashboard) throws LTAGException {
    Integer idxPrev = dashboard.getIdxPrev();
    Sltag curr = dashboard.getCurr();/*from  w ww . j  av a 2 s.c o m*/

    Iterator<LtagNode> localSubstitutions = curr.getNodesDFS(LtagNodeMarker.SUB).iterator();
    while (localSubstitutions.hasNext()) {
        LtagNode localTarget = localSubstitutions.next();
        Iterator<Pair<Sltag, Integer>> waitingSubstitutions = dashboard.getSubstitutions().iterator();
        while (waitingSubstitutions.hasNext()) {
            Pair<Sltag, Integer> entry = waitingSubstitutions.next();
            Sltag waitingSubstitution = entry.getKey();
            if (localTarget.getCategory()
                    .equals(waitingSubstitution.getRoot().getCategory())) { /* CAN MAKE SUBSTITUTION */
                if (curr.getSemantics().getMainVariable() == null && waitingSubstitution.getSemantics()
                        .getMainVariable() != null) { /* RECORD A MAIN VARIABLE MISS */
                    int pos = (idxPrev != null) ? idxPrev + 1 : 0;
                    Variable mainVar = waitingSubstitution.getSemantics().getMainVariable();
                    Set<Statement> statements = waitingSubstitution.getSemantics().getStatements(mainVar);
                    curr.substitution(waitingSubstitution, localTarget);
                    Variable renamedVar = curr.getSemantics().findRenaming(mainVar, statements);
                    if (renamedVar != null) {
                        Triple<Variable, Variable, Set<Statement>> missedRecord = new MutableTriple<>(mainVar,
                                renamedVar, statements);
                        dashboard.getMissedMainVariables().put(pos, missedRecord);
                        LOGGER.info(
                                "Recorded main variable: pos: {} | mainVar: {} renamed to {} | statements: {} ",
                                pos, mainVar, renamedVar, statements);
                    }
                } else {
                    curr.substitution(waitingSubstitution, localTarget);
                }
                LOGGER.debug("Substituted {} with:\n{}", localTarget, waitingSubstitution.toPrettyString());
                waitingSubstitutions.remove();
                localSubstitutions = curr.getNodesDFS(LtagNodeMarker.SUB).iterator();
                break;
            }
        }
    }
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Map<UpnpIgdDevice, byte[]> getRootXmlForEachDevice(Set<UpnpIgdDevice> devices)
        throws InterruptedException {
    Map<UpnpIgdDevice, byte[]> serviceRoots = new HashMap();

    ExecutorService executorService = null;
    try {//from   w  w  w  . jav a2  s .  c o m
        int maximumPoolSize = (int) ((double) Runtime.getRuntime().availableProcessors() / (1.0 - 0.95));
        executorService = new ThreadPoolExecutor(0, maximumPoolSize, 1, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());

        List<HttpRequestCallable<UpnpIgdDevice>> tasks = new LinkedList<>();
        for (UpnpIgdDevice device : devices) {
            tasks.add(new HttpRequestCallable<>(device.getUrl(), device));
        }

        List<Future<Pair<UpnpIgdDevice, byte[]>>> results = executorService.invokeAll(tasks);

        for (Future<Pair<UpnpIgdDevice, byte[]>> result : results) {
            try {
                Pair<UpnpIgdDevice, byte[]> data = result.get();
                serviceRoots.put(data.getKey(), data.getValue());
            } catch (InterruptedException | ExecutionException | CancellationException e) { // NOPMD
                // do nothing, skip
            }
        }
    } finally {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }

    return serviceRoots;
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdDiscovery.java

private static Map<UpnpIgdServiceReference, byte[]> getServiceDescriptions(
        Set<UpnpIgdServiceReference> services) throws InterruptedException {
    Map<UpnpIgdServiceReference, byte[]> serviceXmls = new HashMap();

    ExecutorService executorService = null;
    try {//  w  w  w  .  j a v a  2  s  . c  o  m
        int maximumPoolSize = (int) ((double) Runtime.getRuntime().availableProcessors() / (1.0 - 0.95));
        executorService = new ThreadPoolExecutor(0, maximumPoolSize, 1, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());

        List<HttpRequestCallable<UpnpIgdServiceReference>> tasks = new LinkedList<>();
        for (UpnpIgdServiceReference service : services) {
            tasks.add(new HttpRequestCallable<>(service.getScpdUrl(), service));
        }

        List<Future<Pair<UpnpIgdServiceReference, byte[]>>> results = executorService.invokeAll(tasks);

        for (Future<Pair<UpnpIgdServiceReference, byte[]>> result : results) {
            try {
                Pair<UpnpIgdServiceReference, byte[]> data = result.get();
                serviceXmls.put(data.getKey(), data.getValue());
            } catch (InterruptedException | ExecutionException | CancellationException e) { // NOPMD
                // do nothing, skip
            }
        }
    } finally {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }

    return serviceXmls;
}