Example usage for java.util HashMap values

List of usage examples for java.util HashMap values

Introduction

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

Prototype

public Collection<V> values() 

Source Link

Document

Returns a Collection view of the values contained in this map.

Usage

From source file:gov.nih.nci.cabig.caaers.service.synchronizer.StudyOrganizationSynchronizer.java

/**
 * This method will synchronize the study site
 * @param dbStudy//from  w  ww.  j  av  a 2  s  .  co m
 * @param xmlStudy
 * @param outcome
 */
private void syncStudySite(Study dbStudy, Study xmlStudy, DomainObjectImportOutcome<Study> outcome) {

    //do nothing if study sites section is empty in xmlStudy
    if (CollectionUtils.isEmpty(xmlStudy.getStudySites())) {
        return;
    }

    //create an index consisting of sites, in dbStudy
    HashMap<String, StudySite> siteIndexMap = new HashMap<String, StudySite>();
    for (StudySite ss : dbStudy.getStudySites()) {
        siteIndexMap.put(generateIndexKey(ss), ss);
    }

    //loop through xmlStudy sites, and sync the personnel and investigators
    for (StudySite xmlStudySite : xmlStudy.getStudySites()) {
        StudySite ss = siteIndexMap.remove(generateIndexKey(xmlStudySite));
        if (ss == null) {
            //new so add it to dbStudy
            dbStudy.addStudySite(xmlStudySite);
            continue;
        }

        //sync the staff & investigators
        syncStudyInvestigators(ss, xmlStudySite, ss.getOrganization(), outcome);
        syncStudyPersonnels(ss, xmlStudySite, ss.getOrganization(), outcome);

    }

    //de-activate, all the other sites
    for (StudySite ss : siteIndexMap.values()) {
        ss.deactivate();
    }

}

From source file:net.line2soft.preambul.views.SlippyMapActivity.java

/**
 * Init map's overlays (compass, buttons, ...), attach listener.
 * You can launch map on normal or edit mode (to pick a position).
 * @param addFavorite If true, edit mode (to add favorite), if false normal mode
 *//*from  w w w  .j  a  v a 2s  .c  o  m*/
private void initMap(boolean addFavorite) {
    if (addFavorite == false) {
        //Launch map in normal mode
        findViewById(R.id.list_item).setVisibility(View.VISIBLE);
        findViewById(R.id.drawer).setVisibility(View.VISIBLE);

        //Add listener on excursions button
        ImageButton btExcursionsImg = (ImageButton) findViewById(R.id.imageButton1);
        btExcursionsImg.setOnClickListener(listener);
        btExcursionsImg.setVisibility(View.VISIBLE);
        findViewById(R.id.excursionButton).setVisibility(View.VISIBLE);
        ((ImageButton) findViewById(R.id.imageRight)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.imageLeft)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.favoritesButton)).setOnClickListener(listener);

        //Display POIs on map
        try {
            PointOfInterest[] pois = MapController.getInstance(this).getCurrentLocation().getPOIs(this);
            Drawable icon = null;
            OverlayItem item = null;
            boolean displayPoiType = true;
            for (PointOfInterest poi : pois) {
                displayPoiType = PreferenceManager.getDefaultSharedPreferences(this)
                        .getBoolean("type" + poi.getType().getId(), true);
                if (displayPoiType) {
                    icon = (poi.getType().getIcon() == null) ? poi.getType().getCategory().getIcon()
                            : poi.getType().getIcon();
                    item = new OverlayItem(poi.getPoint(), poi.getName(), poi.getComment(),
                            BalloonItemizedOverlay.boundLeftCenter(icon));
                    overlayPoiItemMarker.addItem(item, poi);
                }
            }
        } catch (Exception e) {
            displayInfo(getString(R.string.message_map_poi_load_error));
            e.printStackTrace();
        }

        //Display favorites on map
        try {
            HashMap<String, NamedPoint> favorites = MapController.getInstance(this).getCurrentLocation()
                    .getNamedFavorites(this);
            Drawable icon = getResources().getDrawable(R.drawable.marker_favorite);
            OverlayItem item = null;
            for (NamedPoint favPoint : favorites.values()) {
                item = new OverlayItem(favPoint.getPoint(), favPoint.getName(), favPoint.getComment(),
                        BalloonItemizedOverlay.boundLeftCenter(icon));
                overlayPoiItemMarker.addItem(item, favPoint);
            }
        } catch (IOException e) {
            displayInfo(getString(R.string.message_map_favorite_load_error));
            e.printStackTrace();
        }

        //Display excursions and instruction on map
        int pathToDisplay = MapController.getInstance(this).getPathToDisplay();
        displayExcursion(pathToDisplay);
        int instructionToDisplay = MapController.getInstance(this).getInstructionToDisplay() - 1;
        //Set instruction, only if > 0 because if instruction=0, was set when displaying excursion
        if (instructionToDisplay > 0) {
            setNavigationInstructionToDisplay(instructionToDisplay);
        }
        //Display of the bookmarksButton
        boolean displaybookmarksButton = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayBookmarksButton", true);
        ImageButton img = (ImageButton) findViewById(R.id.favoritesButton);
        if (displaybookmarksButton) {
            img.setVisibility(View.VISIBLE);
        } else {
            img.setVisibility(View.GONE);
        }
        //Display point
        GeoPoint pointToDisplay = MapController.getInstance(this).getPointToDisplay();
        if (pointToDisplay != null) {
            displayPosition(pointToDisplay.getLatitude(), pointToDisplay.getLongitude());
            MapController.getInstance(this).setPointToDisplay(null);
        }
        //Launch compass
        boolean displayCompass = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayCompass", true);
        CompassView cpv = (CompassView) findViewById(R.id.compass);
        CompassView cpvBig = (CompassView) findViewById(R.id.compassBig);
        if (displayCompass) {
            SensorManager mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor mAccelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            Sensor mField = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            if (mField != null && mAccelerometer != null) {
                mySensorManager.registerListener(listener, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
                mySensorManager.registerListener(listener, mField, SensorManager.SENSOR_DELAY_UI);
                cpv.setOnClickListener(listener);
                if (isCompassAccurate) {
                    cpv.setVisibility(View.VISIBLE);
                } else {
                    displayInfo(getString(R.string.message_compass_not_accurate));
                    cpv.setVisibility(View.GONE);
                }
                cpvBig.setVisibility(View.GONE);
                cpvBig.setOnClickListener(listener);
            } else {
                cpv.setVisibility(View.GONE);
                cpvBig.setVisibility(View.GONE);
            }
        } else {
            cpv.setVisibility(View.GONE);
            cpvBig.setVisibility(View.GONE);
        }

        //Hide validate button
        findViewById(R.id.validatePositionButton).setVisibility(View.GONE);
        findViewById(R.id.imageViewValidate).setVisibility(View.GONE);
        findViewById(R.id.mapPointer).setVisibility(View.GONE);
    } else {
        //Launch map in edit mode, to set coordinates of a favorite
        findViewById(R.id.list_item).setVisibility(View.GONE);
        findViewById(R.id.compass).setVisibility(View.GONE);
        findViewById(R.id.drawer).setVisibility(View.GONE);
        findViewById(R.id.favoritesButton).setVisibility(View.GONE);

        findViewById(R.id.mapPointer).setVisibility(View.VISIBLE);

        //Display validate button and add listener
        findViewById(R.id.validatePositionButton).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setOnClickListener(listener);

        this.addFavorite = false;
    }
}

From source file:net.freifunk.android.discover.Main.java

void updateMaps() {
    final String URL = "https://raw.githubusercontent.com/NiJen/AndroidFreifunkNord/master/MapUrls.json";

    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    final ConnectivityManager connManager = (ConnectivityManager) getSystemService(
            this.getBaseContext().CONNECTIVITY_SERVICE);
    final NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    MapMaster mapMaster = MapMaster.getInstance();
    final DatabaseHelper databaseHelper = DatabaseHelper.getInstance(this.getApplicationContext());
    final RequestQueueHelper requestHelper = RequestQueueHelper.getInstance(this.getApplicationContext());

    final HashMap<String, NodeMap> mapList = databaseHelper.getAllNodeMaps();

    final boolean sync_wifi = sharedPrefs.getBoolean("sync_wifi", true);
    final int sync_frequency = Integer.parseInt(sharedPrefs.getString("sync_frequency", "0"));

    if (sync_wifi == true) {
        Log.d(TAG, "Performing online update ONLY via wifi, every " + sync_frequency + " minutes");
    } else {/*  www. j  a v a2  s  . com*/
        Log.d(TAG, "Performing online update ALWAYS, every " + sync_frequency + " minutes");
    }

    updateTask = new TimerTask() {
        @Override
        public void run() {
            /* load from database */
            for (NodeMap map : mapList.values()) {
                map.loadNodes();
            }

            /* load from web */
            if (connManager.getActiveNetworkInfo() != null
                    && (sync_wifi == false || mWifi.isConnected() == true)) {
                Log.d(TAG, "Performing online update. Next update at " + scheduledExecutionTime());
                requestHelper.add(new JsonObjectRequest(URL, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            MapMaster mapMaster = MapMaster.getInstance();

                            Iterator mapkeys = jsonObject.keys();
                            while (mapkeys.hasNext()) {
                                String mapName = mapkeys.next().toString();
                                String mapUrl = jsonObject.getString(mapName);

                                NodeMap m = new NodeMap(mapName, mapUrl);
                                databaseHelper.addNodeMap(m);

                                // only update, if not already found in database
                                if (!mapList.containsKey(m.getMapName())) {
                                    m.loadNodes();
                                }
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, e.toString());
                        } finally {
                            requestHelper.RequestDone();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.e(TAG, volleyError.toString());
                        requestHelper.RequestDone();
                    }
                }));
            } else {
                Log.d(TAG, "Online update is skipped. Next try at " + scheduledExecutionTime());
            }
        }
    };

    Timer timer = new Timer();

    if (sync_frequency > 0) {
        timer.schedule(updateTask, 0, (sync_frequency * 60 * 1000));
    } else {
        timer.schedule(updateTask, 0);
    }

}

From source file:ddf.catalog.impl.operations.UpdateOperations.java

private UpdateRequest populateMetacards(UpdateRequest updateRequest) throws IngestException {
    QueryRequestImpl queryRequest = createQueryRequest(updateRequest);
    QueryResponse queryResponse;/*from  w w  w.j a va2 s .  c  om*/
    try {
        queryResponse = queryOperations.doQuery(queryRequest, frameworkProperties.getFederationStrategy());
    } catch (FederationException e) {
        LOGGER.debug("Unable to complete query for updated metacards.", e);
        throw new IngestException("Exception during runtime while performing update");
    }

    if (!foundAllUpdateRequestMetacards(updateRequest, queryResponse)) {
        logFailedQueryInfo(updateRequest, queryResponse);
        throw new IngestException("Could not find all metacards specified in request");
    }

    updateRequest = rewriteRequestToAvoidHistoryConflicts(updateRequest, queryResponse);

    // Construct the metacardMap using the metacard's ID in order to match the UpdateRequest
    HashMap<String, Metacard> metacardMap = new HashMap<>(
            queryResponse.getResults().stream().map(Result::getMetacard).collect(Collectors
                    .toMap(metacard -> getAttributeStringValue(metacard, Core.ID), Function.identity())));
    updateRequest.getProperties().put(Constants.ATTRIBUTE_UPDATE_MAP_KEY, metacardMap);
    updateRequest.getProperties().put(Constants.OPERATION_TRANSACTION_KEY,
            new OperationTransactionImpl(OperationTransaction.OperationType.UPDATE, metacardMap.values()));
    return updateRequest;
}

From source file:org.sickbeard.SickBeard.java

public ArrayList<Show> shows() throws Exception {
    HashMap<String, ShowJson> result = this.commandData("shows",
            new TypeToken<JsonResponse<HashMap<String, ShowJson>>>() {
            }.getType());//  w w w.j  a  va2  s. com
    for (Map.Entry<String, ShowJson> entry : result.entrySet()) {
        entry.getValue().id = entry.getKey();
    }
    ArrayList<Show> ret = new ArrayList<Show>();
    for (ShowJson j : result.values()) {
        ret.add(new Show(j));
    }
    Collections.sort(ret, new Comparator<Show>() {
        public int compare(Show a, Show b) {
            return a.showName.compareTo(a.showName);
        }
    });
    return ret;
}

From source file:de.tuebingen.uni.sfs.germanet.api.GermaNet.java

/**
 * Trims all <code>Lists</code> (takes ~0.3 seconds and frees up 2mb).
 */// w w w  .  ja  v  a 2 s  .co m
protected void trimAll() {
    // trim Synsets, which trim LexUnits
    for (Synset sset : synsets) {
        sset.trimAll();
    }

    // trim lists in wordCategoryMap
    HashMap<String, ArrayList<LexUnit>> map;
    for (WordCategory wc : WordCategory.values()) {
        map = wordCategoryMap.get(wc);
        for (ArrayList<LexUnit> luList : map.values()) {
            luList.trimToSize();
        }
    }
}

From source file:info.semanticsoftware.lodexporter.tdb.TDBTripleStoreImpl.java

private void prepareTDBPropertyModel(final HashMap<String, LinkedList<PropertyMapping>> propMapList) {
    // TODO define relations in the RDF rather than hard-coding it here
    hasAnnotation = model.createProperty(modelBaseURI, "hasAnnotation");
    hasDocument = model.createProperty(modelBaseURI, "hasDocument");

    // properties for relation annotations
    hasCompetencyRecord = model.createProperty("http://intelleo.eu/ontologies/user-model/ns/",
            "hasCompetencyRecord");
    competenceFor = model.createProperty("http://www.intelleo.eu/ontologies/competences/ns/", "competenceFor");

    propertyModelHash = new HashMap<>();
    for (final LinkedList<PropertyMapping> propMapElement : propMapList.values()) {
        for (final PropertyMapping map : propMapElement) {
            final String propKey = (map.getGATEattribute() == null) ? map.getGATEfeature()
                    : map.getGATEattribute();
            /*/*from w  ww .  j  av a2 s  .  com*/
             * if(map.getGATEattribute() == null){ propKey =
             * map.getGATEfeature(); }else{ propKey =
             * map.getGATEattribute(); }
             */
            propertyModelHash.put(propKey, model.createProperty(map.getType()));

        }
    }

}

From source file:fi.vrk.xroad.catalog.collector.actors.ListClientsActor.java

@Override
protected boolean handleMessage(Object message) {

    if (START_COLLECTING.equals(message)) {

        String listClientsUrl = host + "/listClients";

        log.info("Getting client list from {}", listClientsUrl);
        ClientList clientList = restOperations.getForObject(listClientsUrl, ClientList.class);

        int counter = 1;
        HashMap<MemberId, Member> m = new HashMap();

        for (ClientType clientType : clientList.getMember()) {
            log.info("{} - ClientType {}  ", counter++, ClientTypeUtil.toString(clientType));
            Member newMember = new Member(clientType.getId().getXRoadInstance(),
                    clientType.getId().getMemberClass(), clientType.getId().getMemberCode(),
                    clientType.getName());
            newMember.setSubsystems(new HashSet<>());
            if (m.get(newMember.createKey()) == null) {
                m.put(newMember.createKey(), newMember);
            }/*from   ww  w. ja va 2  s .  co m*/

            if (XRoadObjectType.SUBSYSTEM.equals(clientType.getId().getObjectType())) {
                Subsystem newSubsystem = new Subsystem(newMember, clientType.getId().getSubsystemCode());
                m.get(newMember.createKey()).getAllSubsystems().add(newSubsystem);
            }
        }

        // Save members
        catalogService.saveAllMembersAndSubsystems(m.values());
        for (ClientType clientType : clientList.getMember()) {
            if (XRoadObjectType.SUBSYSTEM.equals(clientType.getId().getObjectType())) {
                listMethodsPoolRef.tell(clientType, getSelf());
            }
        }
        log.info("all clients (" + (counter - 1) + ") sent to actor");
        return true;
    } else {
        return false;
    }
}

From source file:com.fluidops.iwb.provider.XMLProvider.java

@Override
public void gatherOntology(final List<Statement> ontology) throws Exception {
    HashMap<String, MappingRule> mappingRules = initializeGather();

    // iterate over the rules and extract ontology one by one
    for (MappingRule mr : mappingRules.values()) {
        Map<String, URI> types = new HashMap<String, URI>();

        // Step 1: extract type information, type it as owl:Class with label
        for (String owlType : mr.owlTypes) {
            URI type = null;/* w w w . j  a v a 2s. c om*/
            if (owlType.contains("=")) {
                String keyVal[] = owlType.split("=");
                type = EndpointImpl.api().getNamespaceService().guessURIOrCreateInDefaultNS(keyVal[1]);
                types.put(keyVal[0], type);
            } else {
                type = EndpointImpl.api().getNamespaceService().guessURIOrCreateInDefaultNS(owlType);
                types.put("*", type);
            }
            ontology.add(vf.createStatement(type, RDF.TYPE, OWL.CLASS));
            ontology.add(vf.createStatement(type, RDFS.LABEL, vf.createLiteral(type.getLocalName())));
        }

        // Step 2: extract datatype properties
        for (DatatypePropertyMapping dpMapping : mr.datatypePropMappings) {
            for (URI type : types.values()) {
                // type predicate and assign label
                URI predicate = uriResolver.resolveProperty(dpMapping.owlProperty, type, OWL.DATATYPEPROPERTY);

                // store in ontology
                if (predicate != null)
                    ontology.add(vf.createStatement(predicate, RDF.TYPE, OWL.DATATYPEPROPERTY));
            }
        }

        // handle object properties
        for (ObjectPropertyMapping opMapping : mr.objectPropertyMappings) {
            for (URI type : types.values()) {
                // type predicate and assign label
                URI predicate = uriResolver.resolveProperty(opMapping.owlProperty, type, OWL.OBJECTPROPERTY);

                // store in ontology
                if (predicate != null)
                    ontology.add(vf.createStatement(predicate, RDF.TYPE, OWL.OBJECTPROPERTY));
            }
        }
    }

    // write ontology for predicates
    for (Pair<URI, URI> resolvedProp : uriResolver.resolvedProperties()) {
        URI prop = resolvedProp.fst;
        URI type = resolvedProp.snd;

        if (prop != null && type != null) {
            ontology.add(vf.createStatement(prop, RDF.TYPE, type));

            Statement stmt = vf.createStatement(prop, RDFS.LABEL, vf.createLiteral(prop.getLocalName()));
            ontology.add(stmt);
        }
    }
}

From source file:de.unirostock.sems.cbarchive.web.VcImporter.java

private static File cloneHg(String link, ArchiveFromHg archive) throws IOException, TransformerException,
        JDOMException, ParseException, CombineArchiveException, CombineArchiveWebException {
    // create new temp dir
    File tempDir = Files//from w w  w .  j av  a2 s  . c  o m
            .createTempDirectory(Fields.TEMP_FILE_PREFIX,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
            .toFile();
    if (!tempDir.isDirectory() && !tempDir.mkdirs())
        throw new CombineArchiveWebException(
                "The temporary directories could not be created: " + tempDir.getAbsolutePath());

    // temp file for CombineArchive
    File archiveFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, "ca-imported");
    archiveFile.delete(); // delete the tmp file, so the CombineArchive Lib will create a new file
    // create the archive
    CombineArchive ca = new CombineArchive(archiveFile);

    Repository repo = Repository.clone(tempDir, link);
    if (repo == null) {
        ca.close();
        LOGGER.error("Cannot clone Mercurial Repository ", link, " into ", tempDir);
        throw new CombineArchiveWebException("Cannot clone Mercurial Repository " + link + " into " + tempDir);
    }

    List<File> relevantFiles = scanRepository(tempDir, repo);
    System.out.println("before LogCommand");
    LogCommand logCmd = new LogCommand(repo);
    System.out.println("after LogCommand");
    for (File cur : relevantFiles) {
        List<Changeset> relevantVersions = logCmd.execute(cur.getAbsolutePath());

        ArchiveEntry caFile = ca.addEntry(tempDir, cur, Formatizer.guessFormat(cur));

        // lets create meta!
        List<Date> modified = new ArrayList<Date>();
        List<VCard> creators = new ArrayList<VCard>();

        HashMap<String, VCard> users = new HashMap<String, VCard>();
        for (Changeset cs : relevantVersions) {
            LOGGER.debug("cs: " + cs.getTimestamp().getDate() + " -- " + cs.getUser());
            modified.add(cs.getTimestamp().getDate());

            String vcuser = cs.getUser();
            String firstName = "";
            String lastName = "";
            String mail = "";

            String[] tokens = vcuser.split(" ");
            int lastNameToken = tokens.length - 1;
            // is there a mail address?
            if (tokens[lastNameToken].contains("@")) {
                mail = tokens[lastNameToken];
                if (mail.startsWith("<") && mail.endsWith(">"))
                    mail = mail.substring(1, mail.length() - 1);
                lastNameToken--;
            }

            // search for a non-empty last name
            while (lastNameToken >= 0) {
                if (tokens[lastNameToken].length() > 0) {
                    lastName = tokens[lastNameToken];
                    break;
                }
                lastNameToken--;
            }

            // and first name of course...
            for (int i = 0; i < lastNameToken; i++) {
                if (tokens[i].length() > 0)
                    firstName += tokens[i] + " ";
            }
            firstName = firstName.trim();

            String userid = "[" + firstName + "] -- [" + lastName + "] -- [" + mail + "]";
            LOGGER.debug("this is user: " + userid);
            if (users.get(userid) == null) {
                users.put(userid, new VCard(lastName, firstName, mail, null));
            }
        }

        for (VCard vc : users.values())
            creators.add(vc);

        caFile.addDescription(new OmexMetaDataObject(
                new OmexDescription(creators, modified, modified.get(modified.size() - 1))));

    }

    ca.pack();
    ca.close();
    repo.close();

    // clean up the directory
    FileUtils.deleteDirectory(tempDir);

    // add the combine archive to the dataholder
    if (archive != null) {
        //TODO ugly workaround with the lock. 
        archive.setArchiveFile(archiveFile, null);
        archive.getArchive().close();
    }

    return archiveFile;
}