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:org.phenotips.data.internal.controller.SimpleNamedData.java

/**
 * Shortcut method for getting a value from this list, the first one where the key is equal to the requested name.
 * /*  ww  w. jav a  2 s . co m*/
 * @param name the name of the entry to retrieve
 * @return the value found in the pair with the key equal to the requested name; if more than one such pairs exists,
 *         the value from the first one is returned; if no such pair exists, {@code null} is returned
 */
public T get(String name) {
    for (Pair<String, T> entry : this) {
        if (StringUtils.equals(entry.getKey(), name)) {
            return entry.getValue();
        }
    }
    return null;
}

From source file:org.sakaiproject.assessment.integration.helper.integrated.TagSyncEventHandlerImplTest.java

@Test
public void testNotifyFailureExitsQuietly() {
    final Pair<ItemService, PublishedItemService> itemServices = mockItemServices();

    doThrow(new RuntimeException("oops")).when(itemServices.getKey())
            .deleteItemTagBindingsHavingTagCollectionId("foo");

    // choice of event types is completely random
    tagSyncEventHandler.notify(notification, newEvent("tags.delete.collection", "/tagcollections/foo"));
}

From source file:org.shaman.terrain.vegetation.ImpositorCreator.java

@Override
public void simpleInitApp() {
    File folder = new File(OUTPUT_FOLDER);
    if (folder.exists()) {
        assert (folder.isDirectory());
    } else {//from w  w  w  . ja  va 2  s .c o  m
        folder.mkdir();
    }

    List<TreeInfo> trees = new ArrayList<>();
    List<String> errors = new ArrayList<>();
    //collect input
    MultiMap<Biome, Pair<String, Float>> treeDef = new MultiValueMap<>();
    Map<String, Float> probabilities = new HashMap<>();
    try (BufferedReader in = new BufferedReader(new FileReader(TREE_DEF_FILE))) {
        in.readLine(); //skip head
        while (true) {
            String line = in.readLine();
            if (line == null)
                break;
            String[] parts = line.split(";");
            Biome biome = Biome.valueOf(parts[0]);
            String treeName = parts[1];
            float prob = Float.parseFloat(parts[2]) / 100f;
            treeDef.put(biome, new ImmutablePair<>(treeName, prob));
            Float p = probabilities.get(treeName);
            if (p == null) {
                p = prob;
            } else {
                p += prob;
            }
            probabilities.put(treeName, p);
        }
    } catch (IOException ex) {
        Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex);
    }
    LOG.info("TreeDef: " + treeDef);
    LOG.info("TreeProb: " + probabilities);
    //create trees
    treeCreation: for (Map.Entry<String, Float> entry : probabilities.entrySet()) {
        try {
            String treeName = entry.getKey();
            List<TreeInfo> treeInfos = new ArrayList<>();
            float prob = entry.getValue();
            if (prob <= MAX_PROP) {
                TreeInfo info = createTree(null, treeName, 0, 1);
                if (info != null) {
                    treeInfos.add(info);
                } else {
                    continue treeCreation;
                }
            } else {
                int n = (int) Math.ceil(prob / MAX_PROP);
                float p = prob / n;
                for (int i = 0; i < n; ++i) {
                    TreeInfo info = createTree(null, treeName, i, p);
                    if (info != null) {
                        treeInfos.add(info);
                    } else {
                        continue treeCreation;
                    }
                }
            }
            //create tree infos
            for (Map.Entry<Biome, Object> treeDefE : treeDef.entrySet()) {
                for (Pair<String, Float> v : (Collection<Pair<String, Float>>) treeDefE.getValue()) {
                    if (treeName.equals(v.getKey())) {
                        for (TreeInfo i : treeInfos) {
                            TreeInfo i2 = i.clone();
                            i2.biome = treeDefE.getKey();
                            i2.probability = v.getValue() / treeInfos.size();
                            trees.add(i2);
                        }
                    }
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    System.out.println("trees:");
    for (TreeInfo t : trees) {
        System.out.println(" " + t);
    }
    LOG.log(Level.INFO, "save tree infos, {0} trees in total", trees.size());
    try (ObjectOutputStream out = new ObjectOutputStream(
            new BufferedOutputStream(new FileOutputStream(TREE_DATA_FILE)))) {
        out.writeObject(trees);
    } catch (IOException ex) {
        Logger.getLogger(ImpositorCreator.class.getName()).log(Level.SEVERE, null, ex);
    }
    LOG.info("done");

    stop();
}

From source file:org.silverpeas.core.io.temp.LastModifiedDateFileTask.java

/**
 * Process all the requests. This method should be private but is already declared public in
 * the/*  w  w w  . j  av  a 2 s.com*/
 * base class Thread.
 */
@Override
public void run() {
    Pair<File, Long> pair = nextRequest();

    // The loop condition must be verified on a private attribute of run method (not on the static
    // running attribute) in order to avoid concurrent access.
    while (pair != null) {
        CacheServiceProvider.clearAllThreadCaches();

        /*
         * Each request is processed out of the synchronized block so the others threads (which put
         * the requests) will not be blocked.
         */
        try {
            File currentFile = pair.getKey();
            Long lastModifiedDate = pair.getValue();
            if (currentFile.isFile()) {
                setLastModifiedDate(currentFile, lastModifiedDate);
            } else if (currentFile.isDirectory()) {
                for (File file : FileUtils.listFilesAndDirs(currentFile, FileFilterUtils.trueFileFilter(),
                        FileFilterUtils.trueFileFilter())) {
                    setLastModifiedDate(file, lastModifiedDate);
                }
            }
        } catch (Exception e) {
            SilverLogger.getLogger(e);
        }

        // Getting the next request if any.
        pair = nextRequest();
    }
}

From source file:org.silverpeas.core.io.temp.TestLastModifiedDateFileTask.java

@SuppressWarnings("ConstantConditions")
@Test//from  w  w w .  ja  v a2s. c  o m
public void verifyLastModifiedDate() throws Exception {
    List<File> files = new ArrayList<File>();
    File fileTest = new File(tempPath, "file.txt");
    FileUtils.touch(fileTest);
    files.add(fileTest);

    fileTest = new File(tempPath, "folder");
    fileTest.mkdirs();
    files.add(fileTest);

    fileTest = new File(fileTest, "file1.txt");
    FileUtils.touch(fileTest);
    files.add(fileTest);

    fileTest = new File(fileTest.getParentFile(), "file2.txt");
    FileUtils.touch(fileTest);
    files.add(fileTest);

    fileTest = new File(fileTest.getParentFile(), "otherFolder");
    fileTest.mkdirs();
    files.add(fileTest);

    fileTest = new File(fileTest, "otherFile1.txt");
    FileUtils.touch(fileTest);
    files.add(fileTest);

    fileTest = new File(fileTest.getParentFile(), "otherFile2.txt");
    FileUtils.touch(fileTest);
    files.add(fileTest);

    Thread.sleep(200);
    long oneSecondAfterFileCreation = System.currentTimeMillis();

    List<Pair<File, Long>> fileLastModifiedDate = new ArrayList<Pair<File, Long>>();
    for (File file : files) {
        fileLastModifiedDate.add(Pair.of(file, file.lastModified()));
    }

    for (Pair<File, Long> fileOrFolder : fileLastModifiedDate) {
        assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(),
                is(fileOrFolder.getValue()));
        assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(),
                lessThan(oneSecondAfterFileCreation));
    }

    Thread.sleep(1001);
    File[] tempRootFiles = tempPath.listFiles();
    assertThat(tempRootFiles, arrayWithSize(2));
    for (File tempRootFile : tempRootFiles) {
        LastModifiedDateFileTask.addFile(tempRootFile);
    }

    long l = 0;
    while (LastModifiedDateFileTask.isRunning()) {
        l++;
    }
    assertThat("This assertion shows that the thread stops after all the files are performed", l,
            greaterThan(0l));

    Logger.getAnonymousLogger().info(MessageFormat
            .format("Calling LastModifiedDateFileThread.isRunning() {0} times", String.valueOf(l)));

    for (Pair<File, Long> fileOrFolder : fileLastModifiedDate) {
        assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(),
                greaterThan(fileOrFolder.getValue()));
        assertThat(fileOrFolder.getKey().getName(), fileOrFolder.getKey().lastModified(),
                greaterThan(oneSecondAfterFileCreation));
    }
}

From source file:org.spout.api.util.StringMap.java

public void handleUpdate(StringMapEvent message) {
    switch (message.getAction()) {
    case SET://from  w  w  w  .  j a v  a 2s  .  c o  m
        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;
    }
}

From source file:org.spout.api.util.SyncedStringMap.java

public void handleUpdate(SyncedMapEvent message) {
    switch (message.getAction()) {
    case SET://from www.j a  v  a2s  . 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:org.spout.engine.protocol.builtin.codec.StringMapCodec.java

@Override
public ChannelBuffer encode(StringMapMessage message) {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeInt(message.getMap());//from  www . j a  v a2  s .com
    buffer.writeByte(message.getAction().ordinal());
    buffer.writeInt(message.getElements().size());
    for (Pair<Integer, String> el : message.getElements()) {
        buffer.writeInt(el.getKey());
        ChannelBufferUtils.writeString(buffer, el.getValue());
    }
    return buffer;
}

From source file:org.spout.engine.protocol.builtin.codec.SyncedMapCodec.java

@Override
public ChannelBuffer encode(SyncedMapMessage message) {
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeInt(message.getMap());/*from  w w  w . j  av  a 2  s.c  om*/
    buffer.writeByte(message.getAction().ordinal());
    buffer.writeInt(message.getElements().size());
    for (Pair<Integer, String> el : message.getElements()) {
        buffer.writeInt(el.getKey());
        ChannelBufferUtils.writeString(buffer, el.getValue());
    }
    return buffer;
}

From source file:org.springframework.jdbc.repo.impl.jdbc.RawPropertiesRepoImpl.java

/**
 * @param id The entity ID//w  w w.  j  av a  2 s  .c  o m
 * @return A {@link Pair} whose left hand holds the internal identifier
 * and left hand the properties {@link Map} - <code>null</code> if cannot
 * locate internal identifier value
 */
Pair<Object, Map<String, Serializable>> resolveProperties(String id) {
    Object internalId = findInternalId(id);
    if (internalId == null) {
        return null;
    }

    List<Pair<String, Serializable>> propVals = jdbcAccessor.query(
            "SELECT * FROM " + ENTITY_PROPERTIES_TABLE + " WHERE " + PROP_OWNER_COL + " = :" + INTERNAL_ID_COL,
            Collections.singletonMap(INTERNAL_ID_COL, internalId), valueMapper);
    if (ExtendedCollectionUtils.isEmpty(propVals)) {
        return Pair.of(internalId, Collections.<String, Serializable>emptyMap());
    }

    Map<String, Serializable> propsMap = new TreeMap<String, Serializable>(String.CASE_INSENSITIVE_ORDER);
    for (Pair<String, Serializable> p : propVals) {
        String propName = p.getKey();
        Serializable propValue = p.getValue();
        if (propValue == null) {
            continue; // ignore null(s)
        }

        Serializable prevValue = propsMap.put(propName, propValue);
        if (prevValue != null) {
            throw new IllegalStateException("getProperties(" + getEntityClass().getSimpleName() + ")[" + id
                    + "]" + " multiple values for property=" + propName + ": " + propValue + ", " + prevValue);
        }
    }

    return Pair.of(internalId, propsMap);
}