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.flowpowered.api.util.SyncedStringMap.java

@SuppressWarnings("fallthrough")
public void handleUpdate(SyncedMapEvent message) {
    switch (message.getAction()) {
    case SET://ww  w . ja  v  a  2  s. c o  m
        super.clear();
    case ADD:
        for (Pair<Integer, String> pair : message.getModifiedElements()) {
            store.set(pair.getValue(), pair.getKey());
        }
        break;
    case REMOVE:
        for (Pair<Integer, String> pair : message.getModifiedElements()) {
            store.remove(pair.getValue());
        }
        break;
    }
    callEvent(new SyncedMapEvent(this, message.getAction(), message.getModifiedElements()));
}

From source file:com.nesscomputing.jackson.datatype.CommonsLang3SerializerTest.java

@Test
public void testTrumpetPairCompatibility() throws IOException {
    Pair<String, Boolean> pair = mapper.readValue("{\"car\":\"foo\",\"cdr\":true}",
            new TypeReference<Pair<String, Boolean>>() {
            });//from   ww w.j  a v a  2s .c  o  m
    assertEquals("foo", pair.getKey());
    assertEquals(true, pair.getValue());
}

From source file:com.garethahealy.quotalimitsgenerator.cli.parsers.YamlTemplateProcessor.java

public void process(QuotaLimitModel quotaLimitModel) throws IOException, TemplateException {
    Map<String, QuotaLimitModel> root = new HashMap<String, QuotaLimitModel>();
    root.put("model", quotaLimitModel);

    if (!new File(quotaLimitModel.getOutputPath().toString()).mkdirs()) {
        throw new IOException("Failed to create directory for; " + quotaLimitModel.getOutputPath().toString());
    }//from w ww  .j a  va 2s. com

    for (Pair<String, Template> current : templates) {
        LOG.info("{}/{}.yaml", quotaLimitModel.getOutputPath().toString(), current.getKey());

        File yamlFile = new File(quotaLimitModel.getOutputPath().toString() + "/" + current.getKey() + ".yaml");
        if (!yamlFile.createNewFile()) {
            throw new IOException("Failed to create file for; " + current.getKey());
        }

        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(yamlFile), Charset.forName("UTF-8"));
            current.getValue().process(root, writer);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}

From source file:com.vmware.photon.controller.common.xenon.ServiceHostUtils.java

public static void waitForNodeGroupConvergence(ServiceHost localHost,
        Collection<Pair<String, Integer>> remoteHostIpAndPortPairs, String nodeGroupPath, int maxRetries,
        int retryInterval) throws Throwable {
    checkArgument(localHost != null, "localHost cannot be null");
    checkArgument(remoteHostIpAndPortPairs != null, "remoteHostIpAndPortPairs cannot be null");
    checkArgument(!Strings.isNullOrEmpty(nodeGroupPath), "nodeGroupPath cannot be null or empty");
    checkArgument(maxRetries > 0, "maxRetries must be > 0");

    for (Pair<String, Integer> remoteHostIpAndPortPair : remoteHostIpAndPortPairs) {

        int checkRetries = maxRetries;
        int checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
        while (checkRetries > 0 && checksToConvergence > 0) {
            // update retry count and sleep
            checkRetries--;/*  www  .  ja  v a2 s.  c o  m*/
            Thread.sleep(retryInterval * checksToConvergence);

            // check the host response
            NodeGroupService.NodeGroupState response = getNodeGroupState(localHost,
                    remoteHostIpAndPortPair.getKey(), remoteHostIpAndPortPair.getValue(), nodeGroupPath);
            if (response.nodes.size() < remoteHostIpAndPortPairs.size()) {
                continue;
            }

            // check host status
            checksToConvergence--;
            for (NodeState nodeState : response.nodes.values()) {
                if (nodeState.status != NodeState.NodeStatus.AVAILABLE) {
                    checksToConvergence = REQUIRED_STABLE_STATE_COUNT;
                    break;
                    // Note that we are not breaking from the above while loop where checksToConvergence is done
                    // This is because the nodes might switch between AVAILABLE and SYNCHRONIZING as the other nodes join
                }
            }
        }

        if (checkRetries == 0) {
            throw new TimeoutException("nodes did not converge");
        }
    }
}

From source file:name.martingeisse.phunky.runtime.code.expression.array.ArrayConstructionExpression.java

@Override
public void toJson(JsonValueBuilder<?> builder) {
    JsonObjectBuilder<?> sub = builder.object().property("type").string("arrayConstruction");
    JsonListBuilder<?> subsub = sub.property("elements").list();
    for (Pair<Expression, Expression> element : elements) {
        JsonObjectBuilder<?> subsubsub = subsub.element().object();
        if (element.getKey() != null) {
            element.getKey().toJson(subsubsub.property("key"));
        }/*w ww  . j  a va  2  s . c om*/
        element.getValue().toJson(subsubsub.property("value"));
        subsubsub.end();
    }
    subsub.end();
    sub.end();
}

From source file:com.microsoft.tooling.msservices.serviceexplorer.azure.storage.StorageModule.java

@Override
protected void refreshItems() throws AzureCmdException {
    List<Pair<String, String>> failedSubscriptions = new ArrayList<>();

    try {/*from   w  w w.  j  a  v a  2  s  . c o  m*/
        AzureManager azureManager = AuthMethodManager.getInstance().getAzureManager();
        // not signed in
        if (azureManager == null) {
            return;
        }

        SubscriptionManager subscriptionManager = azureManager.getSubscriptionManager();
        Set<String> sidList = subscriptionManager.getAccountSidList();
        for (String sid : sidList) {
            try {
                Azure azure = azureManager.getAzure(sid);
                List<com.microsoft.azure.management.storage.StorageAccount> storageAccounts = azure
                        .storageAccounts().list();
                for (StorageAccount sm : storageAccounts) {
                    addChildNode(new StorageNode(this, sid, sm));
                }

            } catch (Exception ex) {
                failedSubscriptions.add(new ImmutablePair<>(sid, ex.getMessage()));
                continue;
            }
        }
    } catch (Exception ex) {
        DefaultLoader.getUIHelper()
                .logError("An error occurred when trying to load Storage Accounts\n\n" + ex.getMessage(), ex);
    }

    //            public List<ArmStorageAccount> execute(@NotNull Azure azure) throws Throwable {
    //                List<ArmStorageAccount> storageAccounts = new ArrayList<>();
    //                for (StorageAccount storageAccount : azure.storageAccounts().list()){
    //                    ArmStorageAccount sa = new ArmStorageAccount(storageAccount.name(), subscriptionId, storageAccount);
    //
    //                    sa.setProtocol("https");
    //                    sa.setType(storageAccount.sku().name().toString());
    //                    sa.setLocation(Strings.nullToEmpty(storageAccount.regionName()));
    //                    List<StorageAccountKey> keys = storageAccount.keys();
    //                    if (!(keys == null || keys.isEmpty())) {
    //                        sa.setPrimaryKey(keys.get(0).value());
    //                        if (keys.size() > 1) {
    //                            sa.setSecondaryKey(keys.get(1).value());
    //                        }
    //                    }
    //                    sa.setResourceGroupName(storageAccount.resourceGroupName());
    //                    storageAccounts.add(sa);
    //                }
    //                return storageAccounts;
    //            }
    //TODO
    // load External Accounts
    for (ClientStorageAccount clientStorageAccount : ExternalStorageHelper.getList(getProject())) {
        ClientStorageAccount storageAccount = StorageClientSDKManager.getManager()
                .getStorageAccount(clientStorageAccount.getConnectionString());

        //            addChildNode(new ExternalStorageNode(this, storageAccount));
    }
    if (!failedSubscriptions.isEmpty()) {
        StringBuilder errorMessage = new StringBuilder(
                "An error occurred when trying to load Storage Accounts for the subscriptions:\n\n");
        for (Pair error : failedSubscriptions) {
            errorMessage.append(error.getKey()).append(": ").append(error.getValue()).append("\n");
        }
        DefaultLoader.getUIHelper().logError(
                "An error occurred when trying to load Storage Accounts\n\n" + errorMessage.toString(), null);
    }
}

From source file:com.streamsets.pipeline.hbase.api.common.processor.HBaseStore.java

public List<Optional<String>> get(List<Pair<String, HBaseColumn>> keys) throws Exception {
    ArrayList<Optional<String>> values = new ArrayList<>();
    List<Get> gets = new ArrayList<>();
    for (Pair<String, HBaseColumn> key : keys) {
        Get g = new Get(Bytes.toBytes(key.getKey()));

        HBaseColumn hBaseColumn = key.getValue();
        if (hBaseColumn.getCf() != null && hBaseColumn.getQualifier() != null) {
            g.addColumn(hBaseColumn.getCf(), hBaseColumn.getQualifier());
        }//from   w  w w.  j  a v  a 2s. c  o m
        if (hBaseColumn.getTimestamp() > 0) {
            g.setTimeStamp(hBaseColumn.getTimestamp());
        }
        gets.add(g);
    }

    Result[] results = hBaseProcessor.get(gets);

    int index = 0;
    for (Pair<String, HBaseColumn> key : keys) {
        Result result = results[index];
        HBaseColumn hBaseColumn = key.getValue();

        String value = getValue(hBaseColumn, result);
        values.add(Optional.fromNullable(value));
        index++;
    }
    return values;
}

From source file:emily.games.game2048.Grid.java

public void addRandomTwo() {
    Pair<Integer, Integer> pos = getRandomFreePosition();
    board[pos.getKey()][pos.getValue()] = 2;
}

From source file:com.linkedin.pinot.server.api.restlet.MmapDebugResource.java

@Override
@HttpVerb("get")//www  . ja  v a2 s.c om
@Description("Lists all off-heap allocations and their associated sizes")
@Summary("View current off-heap allocations")
@Paths({ "/debug/memory/offheap", "/debug/memory/offheap/" })
protected Representation get() throws ResourceException {
    try {
        JSONObject returnValue = new JSONObject();

        JSONArray allocationsArray = new JSONArray();
        List<Pair<MmapUtils.AllocationContext, Integer>> allocations = MmapUtils.getAllocationsAndSizes();

        for (Pair<MmapUtils.AllocationContext, Integer> allocation : allocations) {
            JSONObject jsonAllocation = new JSONObject();
            jsonAllocation.put("context", allocation.getKey().getContext());
            jsonAllocation.put("type", allocation.getKey().getAllocationType().toString());
            jsonAllocation.put("size", allocation.getValue());
            allocationsArray.put(jsonAllocation);
        }

        returnValue.put("allocations", allocationsArray);

        return new StringRepresentation(returnValue.toString(2));
    } catch (JSONException e) {
        return new StringRepresentation(e.toString());
    }
}

From source file:code.elix_x.excore.utils.net.packets.SmartNetworkWrapper.java

public <REQ extends IMessage, REPLY extends IMessage> void registerMessage2(
        final Function<REQ, Pair<Runnable, REPLY>> onReceive, Class<REQ> requestMessageType, Side side) {
    registerMessage(new Function<Pair<REQ, MessageContext>, Pair<Runnable, REPLY>>() {

        @Override/*from   w  ww. j av  a 2 s  . c o  m*/
        public Pair<Runnable, REPLY> apply(Pair<REQ, MessageContext> t) {
            return onReceive.apply(t.getKey());
        }

    }, requestMessageType, side);
}