Example usage for java.util HashMap keySet

List of usage examples for java.util HashMap keySet

Introduction

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

Prototype

public Set<K> keySet() 

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.tacitknowledge.util.migration.DistributedAutoPatchRollbackTest.java

/**
 * Make sure we get notified of patch application
 * /*from  www .j a v  a 2s  . c  o  m*/
 * @exception Exception if anything goes wrong
 */
public void testDistributedRollbackEvents() throws Exception {
    IMocksControl mockControl = createControl();

    // There should be five listener on the main process
    // 1) the distributed launcher
    // 2) this test object
    // 3-5) the three sub-launchers
    assertEquals(5, getLauncher().getMigrationProcess().getListeners().size());

    // The sub-MigrationProcesses should have one listener each - the
    // sub-launcher
    HashMap controlledSystems = ((DistributedMigrationProcess) getLauncher().getMigrationProcess())
            .getControlledSystems();

    List<MigrationTask> migrationTasks = new ArrayList<MigrationTask>();

    for (Iterator controlledSystemIter = controlledSystems.keySet().iterator(); controlledSystemIter
            .hasNext();) {
        String controlledSystemName = (String) controlledSystemIter.next();
        JdbcMigrationLauncher subLauncher = (JdbcMigrationLauncher) controlledSystems.get(controlledSystemName);
        MigrationProcess subProcess = subLauncher.getMigrationProcess();
        List<MigrationTask> migrationTasksList = subProcess.getMigrationTasks();
        migrationTasks.addAll(migrationTasksList);
        assertEquals(1, subProcess.getListeners().size());

        MigrationProcess migrationProcessMock = mockControl.createMock(MigrationProcess.class);
        expect(migrationProcessMock.getMigrationTasks()).andReturn(migrationTasksList);
        subLauncher.setMigrationProcess(migrationProcessMock);

    }

    // Now do the migrations, and make sure we get the right number of
    // events
    DistributedMigrationProcess process = (DistributedMigrationProcess) getLauncher().getMigrationProcess();

    List<MigrationTask> rollbackCandidates = new ArrayList<MigrationTask>();

    for (MigrationTask migrationTask : migrationTasks) {
        if (migrationTask instanceof TestRollbackableTask2 || migrationTask instanceof TestRollbackableTask3
                || migrationTask instanceof TestRollbackableTask4
                || migrationTask instanceof TestRollbackableTask5) {

            rollbackCandidates.add(migrationTask);
        }
    }

    MigrationRunnerStrategy migrationRunnerStrategyMock = mockControl.createMock(MigrationRunnerStrategy.class);

    expect(migrationRunnerStrategyMock.getRollbackCandidates(EasyMock.<List<MigrationTask>>anyObject(),
            eq(ROLLBACK_LEVELS), eq(currentPatchInfoStore))).andReturn(rollbackCandidates);
    expect(migrationRunnerStrategyMock.getRollbackCandidates(rollbackCandidates, ROLLBACK_LEVELS,
            currentPatchInfoStore)).andReturn(Collections.EMPTY_LIST);

    expect(migrationRunnerStrategyMock.isSynchronized(eq(currentPatchInfoStore),
            EasyMock.<PatchInfoStore>anyObject())).andReturn(true).anyTimes();

    process.setMigrationRunnerStrategy(migrationRunnerStrategyMock);
    mockControl.replay();

    int currentPatchlevel = 12;

    setReportedPatchLevel(process.getControlledSystems().values(), currentPatchlevel);
    int patches = process.doRollbacks(currentPatchInfoStore, ROLLBACK_LEVELS, getContext(), false);
    assertEquals(4, patches);
    assertEquals(4, getRollbackStartedCount());
    assertEquals(4, getRollbackSuccessCount());
}

From source file:org.mahasen.util.PutUtil.java

/**
 * @param file/*w  w w.j a  v  a 2  s .co m*/
 * @throws InterruptedException
 * @throws RegistryException
 * @throws PastException
 * @throws IOException
 */
public void secureUpload(File file, Id resourceId) throws InterruptedException, RegistryException,
        PastException, IOException, MahasenConfigurationException, MahasenException {

    // get the IP addresses pool to upload files.
    Vector<String> nodeIpsToPut = getNodeIpsToPut();

    MahasenFileSplitter mahasenFileSplitter = new MahasenFileSplitter();
    mahasenFileSplitter.split(file);
    HashMap<String, String> fileParts = mahasenFileSplitter.getPartNames();

    mahasenResource.addPartNames(fileParts.keySet().toArray(new String[fileParts.size()]));
    Random random = new Random();

    for (String currentPartName : fileParts.keySet()) {
        File splittedFilePart = new File(fileParts.get(currentPartName));
        int randomNumber = random.nextInt(nodeIpsToPut.size());
        String nodeIp = nodeIpsToPut.get(randomNumber);

        try {
            setTrustStore();
            URI uri = null;

            ArrayList<NameValuePair> qparams = new ArrayList<NameValuePair>();
            qparams.add(new BasicNameValuePair("splittedfilename", splittedFilePart.getName()));
            uri = URIUtils.createURI("https", nodeIp + ":" + MahasenConstants.SERVER_PORT, -1,
                    "/mahasen/upload_request_ajaxprocessor.jsp", URLEncodedUtils.format(qparams, "UTF-8"),
                    null);

            MahasenUploadWorker uploadWorker = new MahasenUploadWorker(uri, currentPartName, splittedFilePart,
                    mahasenResource, nodeIp);
            uploadThread = new Thread(uploadWorker);
            uploadWorker.setJobId(jobId);

            //keep track of uploading parts
            AtomicInteger noOfParts = new AtomicInteger(0);
            storedNoOfParts.put(jobId, noOfParts);

            uploadThread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    final BlockFlag blockFlag = new BlockFlag(true, 6000);
    while (true) {

        AtomicInteger noOfParts = storedNoOfParts.get(jobId);
        if (noOfParts.get() == fileParts.size()) {
            storedNoOfParts.remove(uploadThread.getId());
            System.out.println("uploaded no of parts " + noOfParts + "out of " + fileParts.size() + "going out "
                    + "#####Thread id:" + uploadThread.getId());
            blockFlag.unblock();
            break;
        }

        if (blockFlag.isBlocked()) {
            mahasenManager.getNode().getEnvironment().getTimeSource().sleep(10);
        } else {
            throw new MahasenException("Time out in uploading " + file.getName());
        }
    }

    mahasenManager.insertIntoDHT(resourceId, mahasenResource, false);
    mahasenManager.insertTreeMapIntoDHT(resourceId, mahasenResource, false);

    ReplicateRequestStarter replicateStarter = new ReplicateRequestStarter(mahasenResource);
    Thread replicateThread = new Thread(replicateStarter);
    replicateThread.start();
}

From source file:com.concursive.connect.web.modules.calendar.portlets.main.SaveEventInviteesAction.java

private boolean scheduleDimdimMeeting(Connection db, MeetingInviteesBean meetingInviteesBean)
        throws SQLException {
    Meeting meeting = meetingInviteesBean.getMeeting();

    if (!StringUtils.hasText(meeting.getDimdimUrl()) || !StringUtils.hasText(meeting.getDimdimUsername())
            || !StringUtils.hasText(meeting.getDimdimPassword())) {
        meeting.addError("inviteesError", "Missing Dimdim credentials");
        return false;
    }//w  ww  . ja  va 2s.  co m

    HashMap<String, String> resultMap = DimDimUtils.processDimdimMeeting(meetingInviteesBean, null);
    if (resultMap.containsKey(DimDimUtils.DIMDIM_CODE_SUCCESS)) {
        String dimdimMeetingId = resultMap.get(DimDimUtils.DIMDIM_CODE_SUCCESS);
        meeting.setDimdimMeetingId(dimdimMeetingId);
        meeting.update(db);
        return true;
    }
    meeting.addError("inviteesError", resultMap.get(resultMap.keySet().toArray()[0]));
    return false;
}

From source file:com.odoo.core.service.OSyncAdapter.java

private void handleRelationRecords(OUser user,
        HashMap<String, OSyncDataUtils.SyncRelationRecords> relationRecords, SyncResult result) {
    for (String key : relationRecords.keySet()) {
        OSyncDataUtils.SyncRelationRecords record = relationRecords.get(key);
        OModel model = record.getBaseModel();
        OModel rel_model = model.createInstance(record.getRelationModel());
        model.close();/*from ww w .  j  a  va  2s. c  om*/
        ODomain domain = new ODomain();
        domain.add("id", "in", record.getUniqueIds());
        syncData(rel_model, user, domain, result, false, false);
        // Updating manyToOne record with their relation record row_id
        switch (record.getRelationType()) {
        case ManyToOne:
            // Nothing to do. Already added link with record relation
            break;
        case OneToMany:
            // Update related_column with base id's row_id for each of record ids
            String related_column = record.getRelatedColumn();
            for (Integer id : record.getUniqueIds()) {
                OValues values = new OValues();
                ODataRow rec = rel_model.browse(rel_model.selectRowId(id));
                values.put(related_column, rec.getInt(related_column));
                values.put("_is_dirty", "false");
                rel_model.update(rel_model.selectRowId(id), values);
            }
            break;
        case ManyToMany:
            // Nothing to do. Already added relation records links
            break;
        }
        rel_model.close();
    }
}

From source file:edu.ucsb.nceas.ezid.test.EZIDServiceTest.java

@Test
public void setAndGetMetadata() {
    String testId = null;/*from   w  ww .  j  a  v  a 2 s  . c om*/
    String TITLEKEY = DublinCoreProfile.TITLE.toString();
    String TITLEVAL = "A Dublin Core resource title";

    try {
        HashMap<String, String> metadata = generateMetadata("ToBeMinted");
        testId = ezid.mintIdentifier(DOISHOULDER, metadata);
        metadata.put(TITLEKEY, TITLEVAL);
        ezid.setMetadata(testId, metadata);
    } catch (EZIDException e) {
        fail("SetMetadata failed: " + e.getMessage());
    }

    try {
        HashMap<String, String> metadata = ezid.getMetadata(testId);
        for (String key : metadata.keySet()) {
            log.debug(key + ": " + metadata.get(key));
        }
        String title = metadata.get(TITLEKEY);
        log.debug("SetAndGet Title: " + title);
        if (title == null || !title.equals(TITLEVAL)) {
            fail("GetMetadata failed: Title does not match.");
        }
    } catch (EZIDException e) {
        fail("GetMetadata failed: " + e.getMessage());
    }
}

From source file:net.minecraftforge.common.crafting.CraftingHelper.java

public static ShapedPrimer parseShaped(Object... recipe) {
    ShapedPrimer ret = new ShapedPrimer();
    String shape = "";
    int idx = 0;/*from   w ww  .  ja  va 2 s .c  om*/

    if (recipe[idx] instanceof Boolean) {
        ret.mirrored = (Boolean) recipe[idx];
        if (recipe[idx + 1] instanceof Object[])
            recipe = (Object[]) recipe[idx + 1];
        else
            idx = 1;
    }

    if (recipe[idx] instanceof String[]) {
        String[] parts = ((String[]) recipe[idx++]);

        for (String s : parts) {
            ret.width = s.length();
            shape += s;
        }

        ret.height = parts.length;
    } else {
        while (recipe[idx] instanceof String) {
            String s = (String) recipe[idx++];
            shape += s;
            ret.width = s.length();
            ret.height++;
        }
    }

    if (ret.width * ret.height != shape.length() || shape.length() == 0) {
        String err = "Invalid shaped recipe: ";
        for (Object tmp : recipe) {
            err += tmp + ", ";
        }
        throw new RuntimeException(err);
    }

    HashMap<Character, Ingredient> itemMap = Maps.newHashMap();
    itemMap.put(' ', Ingredient.EMPTY);

    for (; idx < recipe.length; idx += 2) {
        Character chr = (Character) recipe[idx];
        Object in = recipe[idx + 1];
        Ingredient ing = CraftingHelper.getIngredient(in);

        if (' ' == chr.charValue())
            throw new JsonSyntaxException("Invalid key entry: ' ' is a reserved symbol.");

        if (ing != null) {
            itemMap.put(chr, ing);
        } else {
            String err = "Invalid shaped ore recipe: ";
            for (Object tmp : recipe) {
                err += tmp + ", ";
            }
            throw new RuntimeException(err);
        }
    }

    ret.input = NonNullList.withSize(ret.width * ret.height, Ingredient.EMPTY);

    Set<Character> keys = Sets.newHashSet(itemMap.keySet());
    keys.remove(' ');

    int x = 0;
    for (char chr : shape.toCharArray()) {
        Ingredient ing = itemMap.get(chr);
        if (ing == null)
            throw new IllegalArgumentException(
                    "Pattern references symbol '" + chr + "' but it's not defined in the key");
        ret.input.set(x++, ing);
        keys.remove(chr);
    }

    if (!keys.isEmpty())
        throw new IllegalArgumentException("Key defines symbols that aren't used in pattern: " + keys);

    return ret;
}

From source file:org.bitsofinfo.util.address.usps.ais.index.LuceneIndexService.java

@Override
public void index(List<USPSRecord> records) {

    // sort em all out
    HashMap<Class, List<USPSRecord>> clazzMap = new HashMap<Class, List<USPSRecord>>();
    for (USPSRecord record : records) {
        Class clazz = record.getClass();
        List<USPSRecord> tmp = clazzMap.get(clazz);
        if (tmp == null) {
            tmp = new ArrayList<USPSRecord>();
            clazzMap.put(clazz, tmp);/*ww w  .j a  va 2 s .c om*/
        }

        tmp.add(record);
    }

    for (Class clazz : clazzMap.keySet()) {

        List<USPSRecord> items = clazzMap.get(clazz);
        LuceneIndex index = indexMap.get(clazz);
        IndexWriter writer = null;
        try {
            writer = this.getIndexWriter(index.activeDir, true, false);

            for (USPSRecord r : items) {
                Document doc = this.uspsRecordToDocument(r);
                Term id = new Term("identifier", r.getIdentifier());
                writer.updateDocument(id, doc, this.uspsRecordAnalyzer);
            }

            if (indexCount == 10) {
                writer.optimize();
                indexCount = 0;
            }

        } catch (Exception e) {

        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ignoreForNow) {
                }
            }
        }
    }

    indexCount++;

}

From source file:com.atinternet.tracker.Configuration.java

/**
 * Override configuration/*w  w  w . j  a  v a 2 s.  c  o  m*/
 *
 * @param configuration HashMap
 */
Configuration(HashMap<String, Object> configuration) {
    clear();
    JSONObject jsonObject = getDefaultConfiguration(false);
    if (jsonObject != null) {
        Iterator<String> iterator = jsonObject.keys();
        while (iterator.hasNext()) {
            String key = iterator.next();
            try {
                put(key, jsonObject.get(key));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    for (String key : configuration.keySet()) {
        put(key, configuration.get(key));
    }
}

From source file:de.rbs90.fwdisp.settingsgui.gui.tabs.statistics.YearStatisticPanel.java

public YearStatisticPanel() {
    setName("Jahr");
    setLayout(new BorderLayout());

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();

    HashMap<Integer, Integer> alarmCount = new HashMap<>();

    try {//from   w  w  w  .  j av  a  2s.  c  o  m
        ResultSet resultSet = Starter.getDatabase().getStatement().executeQuery(
                "SELECT STARTDATE_YEAR, COUNT(*) AS COUNT FROM ALARMHISTORY GROUP BY STARTDATE_YEAR"
                        + " ORDER BY STARTDATE_YEAR ASC");

        while (resultSet.next()) {
            alarmCount.put(resultSet.getInt("STARTDATE_YEAR"), resultSet.getInt("COUNT"));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    }

    Set<Integer> years = alarmCount.keySet();

    for (Integer year : years) {
        Integer count = alarmCount.get(year);
        dataset.addValue(count, count, year);
    }

    JFreeChart chart = ChartFactory.createBarChart3D("Jahresbersicht", "Jahr", "Einstze", dataset,
            PlotOrientation.VERTICAL, false, false, false);

    chart.setBackgroundPaint(getBackground());
    ChartPanel panel = new ChartPanel(chart);
    panel.setPopupMenu(null);

    add(panel, BorderLayout.CENTER);
}