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.ibm.util.merge.CompareArchives.java

/**
 * @param tar1//www.  j a  va  2s  . c  o m
 * @param files1
 * @param tar2
 * @param files2
 * @throws IOException
 */
private static final void assertMembersEqual(String tar1, HashMap<String, TarArchiveEntry> files1, String tar2,
        HashMap<String, TarArchiveEntry> files2) throws IOException {
    if (files1.size() != files2.size()) {
        fail("Different Sizes, expected " + Integer.toString(files1.size()) + " found "
                + Integer.toString(files2.size()));
    }

    for (String key : files1.keySet()) {
        if (!files2.containsKey(key)) {
            fail("Expected file not in target " + key);
        }
    }

    for (String key : files1.keySet()) {
        if (!files2.containsKey(key)) {
            fail("Expected file not in target " + key);
        }
    }
    for (String key : files1.keySet()) {
        String file1 = getTarFile(tar1, key);
        String file2 = getTarFile(tar2, key);
        assertEquals(file1, file2);
    }
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

public static void addCommonHeaders(URLConnection connection) {
    HashMap<String, String> commonHeaders = getCommonHeaders();
    Set<String> keys = commonHeaders.keySet();
    for (String key : keys) {
        connection.setRequestProperty(key, commonHeaders.get(key));
    }/*w w w .  ja v  a  2 s  .co  m*/
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

/**
 * Adds our common headers/*from   w ww  .  ja v a2s  .  c  o m*/
 */
public static void addCommonHeaders(HttpPost httpPost) {
    HashMap<String, String> commonHeaders = getCommonHeaders();
    Set<String> keys = commonHeaders.keySet();
    for (String key : keys) {
        httpPost.addHeader(key, commonHeaders.get(key));
    }
}

From source file:com.symbian.driver.core.processors.EmulatorPreProcessor.java

/**
 * @param lEmulatorHashBackup//from  w  w w  .  j a  va2s  .  c om
 * 
 * @deprecated This needs to use the emulator ROM tool
 */
public static void restoreEmulator(HashMap<File, File> lEmulatorHashBackup) {
    if (lEmulatorHashBackup != null) {
        for (File lEmulatorOrginal : lEmulatorHashBackup.keySet()) {
            File lEmulatorBackup = lEmulatorHashBackup.get(lEmulatorOrginal);

            if (lEmulatorBackup != null && !lEmulatorBackup.renameTo(lEmulatorOrginal)) {
                LOGGER.fine("Could not restore Emulator backup of: " + lEmulatorBackup.toString() + " to "
                        + lEmulatorOrginal.toString());
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.ReportUtils.java

/**
 * Creates a confusion matrix by collecting the results from the overall CV run stored in
 * {@code tempM}// w  w w.  ja va2 s .c o  m
 * 
 * @param tempM
 * @param actualLabelsList
 *            the label powerset transformed list of actual/true labels
 * @param predictedLabelsList
 *            the label powerset transformed list of predicted labels
 * @return
 */
public static double[][] createConfusionMatrix(HashMap<String, Map<String, Integer>> tempM,
        List<String> actualLabelsList, List<String> predictedLabelsList) {
    double[][] matrix = new double[actualLabelsList.size()][predictedLabelsList.size()];

    Iterator<String> actualsIter = tempM.keySet().iterator();
    while (actualsIter.hasNext()) {
        String actual = actualsIter.next();
        Iterator<String> predsIter = tempM.get(actual).keySet().iterator();
        while (predsIter.hasNext()) {
            String pred = predsIter.next();
            int a = actualLabelsList.indexOf(actual);
            int p = predictedLabelsList.indexOf(pred);
            matrix[a][p] = tempM.get(actual).get(pred);
        }
    }
    return matrix;
}

From source file:com.savor.ads.core.ApiRequestFactory.java

private static JSONObject getJsonRequest(Object params, Session appSession) throws JSONException {
    if (params == null) {
        return new JSONObject();
    }//from w w w.  ja v  a 2s  .c o  m

    HashMap<String, Object> requestParams;
    if (params instanceof HashMap) {
        requestParams = (HashMap<String, Object>) params;
    } else {
        return new JSONObject();
    }

    // add parameter node
    final Iterator<String> keySet = requestParams.keySet().iterator();
    JSONObject jsonParams = new JSONObject();

    try {
        while (keySet.hasNext()) {
            final String key = keySet.next();
            Object val = requestParams.get(key);
            if (val == null) {
                val = "";
            }
            if (val instanceof String || val instanceof Number || val == null) {
                jsonParams.accumulate(key, val);
            } else if (val instanceof List<?>) {
                jsonParams.accumulate(key, getJSONArray((List<?>) val));
            } else {
                jsonParams.accumulate(key, getJSONObject(val).toString());
            }
        }
        LogUtils.i("??:" + jsonParams.toString());
        //            return new StringEntity(DesUtils.encrypt(jsonParams.toString()), HTTP.UTF_8);
        return jsonParams;

    } catch (Exception e) {
        e.printStackTrace();
        return new JSONObject();
    }
}

From source file:br.gov.jfrj.siga.base.ConexaoHTTP.java

public static String get(String URL, HashMap<String, String> header, Integer timeout, String payload)
        throws AplicacaoException {

    try {/*from   w w w  .j a  va  2  s  .c o  m*/

        HttpURLConnection conn = (HttpURLConnection) new URL(URL).openConnection();

        if (timeout != null) {
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
        }

        //conn.setInstanceFollowRedirects(true);

        if (header != null) {
            for (String s : header.keySet()) {
                conn.setRequestProperty(s, header.get(s));
            }
        }

        System.setProperty("http.keepAlive", "false");

        if (payload != null) {
            byte ab[] = payload.getBytes("UTF-8");
            conn.setRequestMethod("POST");
            // Send post request
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            os.write(ab);
            os.flush();
            os.close();
        }

        //StringWriter writer = new StringWriter();
        //IOUtils.copy(conn.getInputStream(), writer, "UTF-8");
        //return writer.toString();
        return IOUtils.toString(conn.getInputStream(), "UTF-8");

    } catch (IOException ioe) {
        throw new AplicacaoException("No foi possvel abrir conexo", 1, ioe);
    }

}

From source file:org.easyrec.utils.MyUtils.java

/**
 * This function sorts the Strings in the
 * given list by their first occurence in the given text.
 *
 * @param listToOrder e.g. FORMULA_1_DRIVERS = {"Lewis Hamilton","Heikki Kovalainen","Felipe Massa"}
 * @param textToParse e.g. "Felipe Masse is on fire. His is ahead of Lewis Hamilton"
 * @param fuzzy:      tokenize Strings and ordery by their occurence e.g. "Lewis Hamilton" --> {"Lewis","Hamilton"}
 * @return {"Felipe Massa","Lewis Hamilton"}
 *///from  w ww.j  a v  a2s .com
@SuppressWarnings({ "UnusedDeclaration" })
public static List<String> orderByFirstOccurenceInText(String listToOrder[], String textToParse,
        boolean fuzzy) {

    List<String> sortedList = new ArrayList<String>();
    HashMap<Integer, String> h = new HashMap<Integer, String>();

    if (listToOrder != null && !textToParse.equals("")) {
        for (String s : listToOrder) {
            if (textToParse.indexOf(s) > 0) {
                h.put(textToParse.indexOf(s), s);
            }
        }

        List<Integer> keys = new ArrayList<Integer>(h.keySet());
        Collections.sort(keys);

        for (Integer k : keys) {
            sortedList.add(h.get(k));
        }
    }

    if (fuzzy) {
        sortedList.addAll(orderByFuzzyFirstOccurenceInText(listToOrder, textToParse));
    }
    return sortedList;
}

From source file:com.liusoft.dlog4j.search.SearchProxy.java

/**
 * ?/*from   w w w  .  j  a  va  2s.  co m*/
 * @param params
 * @return
 * @throws Exception 
 */
public static List search(SearchParameter params) throws Exception {
    if (params == null)
        return null;

    SearchEnabled searching = (SearchEnabled) params.getSearchObject().newInstance();

    StringBuffer path = new StringBuffer(_baseIndexPath);
    path.append(searching.name());
    File f = new File(path.toString());
    if (!f.exists())
        return null;

    IndexSearcher searcher = new IndexSearcher(path.toString());

    //?
    BooleanQuery comboQuery = new BooleanQuery();
    int _query_count = 0;
    StringTokenizer st = new StringTokenizer(params.getSearchKey());
    while (st.hasMoreElements()) {
        String q = st.nextToken();
        String[] indexFields = searching.getIndexFields();
        for (int i = 0; i < indexFields.length; i++) {
            QueryParser qp = new QueryParser(indexFields[i], analyzer);
            try {
                Query subjectQuery = qp.parse(q);
                comboQuery.add(subjectQuery, BooleanClause.Occur.SHOULD);
                _query_count++;
            } catch (Exception e) {
                log.error("Add query parameter failed. key=" + q, e);
            }
        }
    }

    if (_query_count == 0)//?
        return null;

    //??
    MultiFilter multiFilter = null;
    HashMap conds = params.getConditions();
    if (conds != null) {
        Iterator keys = conds.keySet().iterator();
        while (keys.hasNext()) {
            if (multiFilter == null)
                multiFilter = new MultiFilter(0);
            String key = (String) keys.next();
            multiFilter.add(new FieldFilter(key, conds.get(key).toString()));
        }
    }

    /*
     * Creates a sort, possibly in reverse,
     * by terms in the given field with the type of term values explicitly given.
     */
    SortField[] s_fields = new SortField[2];
    s_fields[0] = SortField.FIELD_SCORE;
    s_fields[1] = new SortField(searching.getKeywordField(), SortField.INT, true);
    Sort sort = new Sort(s_fields);

    Hits hits = searcher.search(comboQuery, multiFilter, sort);
    int numResults = hits.length();
    //System.out.println(numResults + " found............................");
    int result_count = Math.min(numResults, MAX_RESULT_COUNT);
    List results = new ArrayList(result_count);
    for (int i = 0; i < result_count; i++) {
        Document doc = (Document) hits.doc(i);
        //Java
        Object result = params.getSearchObject().newInstance();
        Enumeration fields = doc.fields();
        while (fields.hasMoreElements()) {
            Field field = (Field) fields.nextElement();
            //System.out.println(field.name()+" -- "+field.stringValue());
            if (CLASSNAME_FIELD.equals(field.name()))
                continue;
            //?
            if (!field.isStored())
                continue;
            //System.out.println("=========== begin to mapping ============");
            //String --> anything
            Class fieldType = getNestedPropertyType(result, field.name());
            //System.out.println(field.name()+", class = " + fieldType.getName());
            Object fieldValue = null;
            if (fieldType.equals(Date.class))
                fieldValue = new Date(Long.parseLong(field.stringValue()));
            else
                fieldValue = ConvertUtils.convert(field.stringValue(), fieldType);
            //System.out.println(fieldValue+", class = " + fieldValue.getClass().getName());
            setNestedProperty(result, field.name(), fieldValue);
        }
        results.add(result);
    }

    return results;
}

From source file:com.concursive.connect.web.modules.calendar.utils.CalendarViewUtils.java

public static CalendarView generateCalendarView(Connection db, CalendarBean calendarInfo, Project project,
        User user, String filter) throws SQLException {

    // Generate a new calendar
    CalendarView calendarView = new CalendarView(calendarInfo, user.getLocale());

    if (calendarInfo.getShowHolidays()) {
        // Add some holidays based on the user locale
        calendarView.addHolidays();//  ww w.j  a  va 2s .com
    }

    // Set Start and End Dates for the view, use the user's timezone offset
    // (always use Locale.US which matches the URL format)
    String startValue = calendarView.getCalendarStartDate(calendarInfo.getSource());
    LOG.debug(startValue);
    String userStartValue = DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(),
            DateFormat.SHORT, DateFormat.LONG, startValue, Locale.US);
    LOG.debug(userStartValue);
    Timestamp startDate = DatabaseUtils.parseTimestamp(userStartValue);
    startDate.setNanos(0);
    LOG.debug(startDate);

    Timestamp endDate = DatabaseUtils.parseTimestamp(
            DateUtils.getUserToServerDateTimeString(calendarInfo.getTimeZone(), DateFormat.SHORT,
                    DateFormat.LONG, calendarView.getCalendarEndDate(calendarInfo.getSource()), Locale.US));
    endDate.setNanos(0);

    if (ProjectUtils.hasAccess(project.getId(), user, "project-tickets-view")) {
        // Show open and closed tickets
        TicketList ticketList = new TicketList();
        ticketList.setProjectId(project.getId());
        ticketList.setOnlyAssigned(true);
        ticketList.setAlertRangeStart(startDate);
        ticketList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            ticketList.setOnlyOpen(true);
        } else if ("completed".equals(filter)) {
            ticketList.setOnlyClosed(true);
        }

        // Retrieve the tickets that meet the criteria
        ticketList.buildList(db);
        for (Ticket thisTicket : ticketList) {
            if (thisTicket.getEstimatedResolutionDate() != null) {
                String alertDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisTicket.getEstimatedResolutionDate());
                calendarView.addEvent(alertDate, CalendarEventList.EVENT_TYPES[11], thisTicket);
            }
        }

        // Retrieve the dates in which a ticket has been resolved
        HashMap<String, Integer> dayEvents = ticketList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.TICKET],
                    dayEvents.get(thisDay));
        }
    }
    if (ProjectUtils.hasAccess(project.getId(), user, "project-plan-view")) {
        // List open and closed Requirements
        RequirementList requirementList = new RequirementList();
        requirementList.setProjectId(project.getId());
        requirementList.setBuildAssignments(false);
        requirementList.setAlertRangeStart(startDate);
        requirementList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            requirementList.setOpenOnly(true);
        } else if ("completed".equals(filter)) {
            requirementList.setClosedOnly(true);
        }

        // Retrieve the requirements that meet the criteria
        requirementList.buildList(db);
        // @todo fix timezone for query counts
        requirementList.buildPlanActivityCounts(db);
        for (Requirement thisRequirement : requirementList) {
            // Display Milestone startDate
            if (thisRequirement.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getStartDate());
                calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[16], thisRequirement);
            }
            // Display Milestone endDate
            if (thisRequirement.getDeadline() != null) {
                String end = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisRequirement.getDeadline());
                calendarView.addEvent(end, CalendarEventList.EVENT_TYPES[17], thisRequirement);
            }
        }

        // Retrieve the dates in which a requirement has a start or end date
        HashMap<String, HashMap<String, Integer>> dayGroups = requirementList.queryRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String type : dayGroups.keySet()) {
            if ("startdate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_START],
                            dayEvents.get(thisDay));
                }
            } else if ("enddate".equals(type)) {
                HashMap<String, Integer> dayEvents = dayGroups.get(type);
                for (String thisDay : dayEvents.keySet()) {
                    calendarView.addEventCount(thisDay,
                            CalendarEventList.EVENT_TYPES[CalendarEventList.MILESTONE_END],
                            dayEvents.get(thisDay));
                }
            }

        }

        // Retrieve assignments that meet the criteria
        AssignmentList assignmentList = new AssignmentList();
        assignmentList.setProjectId(project.getId());
        assignmentList.setOnlyIfRequirementOpen(true);
        assignmentList.setAlertRangeStart(startDate);
        assignmentList.setAlertRangeEnd(endDate);
        if ("pending".equals(filter)) {
            assignmentList.setIncompleteOnly(true);
        } else if ("completed".equals(filter)) {
            assignmentList.setClosedOnly(true);
        }

        // Display the user's assignments by due date
        assignmentList.buildList(db);
        for (Assignment thisAssignment : assignmentList) {
            if (thisAssignment.getDueDate() != null) {
                String dueDate = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisAssignment.getDueDate());
                calendarView.addEvent(dueDate, CalendarEventList.EVENT_TYPES[8], thisAssignment);
            }
        }

        // Retrieve the dates in which an assignment has a due date
        HashMap<String, Integer> dayEvents = assignmentList.queryAssignmentRecordCount(db,
                UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.ASSIGNMENT],
                    dayEvents.get(thisDay));
        }
    }

    if (ProjectUtils.hasAccess(project.getId(), user, "project-calendar-view")) {
        MeetingList meetingList = new MeetingList();
        meetingList.setProjectId(project.getId());
        meetingList.setEventSpanStart(startDate);
        if (!calendarInfo.isAgendaView()) {
            // limit the events to the date range chosen
            meetingList.setEventSpanEnd(endDate);
        }
        meetingList.setBuildAttendees(true);
        meetingList.buildList(db);
        LOG.debug("Meeting count = " + meetingList.size());
        // Display the meetings by date
        for (Meeting thisMeeting : meetingList) {
            if (thisMeeting.getStartDate() != null) {
                String start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                        DateFormat.SHORT, thisMeeting.getStartDate());
                if ("pending".equals(filter)) {
                    if (thisMeeting.getStartDate().getTime() > System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else if ("completed".equals(filter)) {
                    if (thisMeeting.getEndDate().getTime() < System.currentTimeMillis()) {
                        calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                                thisMeeting);
                    }
                } else {
                    if (calendarInfo.isAgendaView()) {
                        // Display meetings that started before today, but last greater than today, on the startDate of the calendar display
                        if (thisMeeting.getStartDate().before(startDate)) {
                            start = DateUtils.getServerToUserDateString(UserUtils.getUserTimeZone(user),
                                    DateFormat.SHORT, startDate);
                        }
                    }
                    calendarView.addEvent(start, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                            thisMeeting);
                }
                LOG.debug("Meeting added for date: " + start);
            }
        }

        // Retrieve the dates for meeting events
        HashMap<String, Integer> dayEvents = meetingList.queryRecordCount(db, UserUtils.getUserTimeZone(user));
        for (String thisDay : dayEvents.keySet()) {
            LOG.debug("addingCount: " + thisDay + " = " + dayEvents.get(thisDay));
            calendarView.addEventCount(thisDay, CalendarEventList.EVENT_TYPES[CalendarEventList.EVENT],
                    dayEvents.get(thisDay));
        }
    }
    return calendarView;
}