Example usage for java.util.concurrent ConcurrentMap get

List of usage examples for java.util.concurrent ConcurrentMap get

Introduction

In this page you can find the example usage for java.util.concurrent ConcurrentMap get.

Prototype

V get(Object key);

Source Link

Document

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Usage

From source file:com.alibaba.jstorm.daemon.nimbus.metric.ClusterMetricsContext.java

public Map<String, Long> registerMetrics(String topologyId, Set<String> metricNames) {
    TimeTicker ticker = new TimeTicker(TimeUnit.MILLISECONDS, true);

    TopologyMetricContext topologyMetricContext = topologyMetricContexts.get(topologyId);
    if (topologyMetricContext == null) {
        LOG.warn("topology metrics context does not exist for topology:{}!!!", topologyId);
        return new HashMap<>();
    }//ww w .  j  av  a  2 s .  co m

    //        if (!topologyMetricContext.finishSyncRemote()) {
    //            LOG.warn("waiting for topology {} to finish sync with remote.", topologyId);
    //            return new HashMap<>();
    //        }

    ConcurrentMap<String, Long> memMeta = topologyMetricContexts.get(topologyId).getMemMeta();
    Map<String, Long> ret = new HashMap<>();
    for (String metricName : metricNames) {
        Long id = memMeta.get(metricName);
        if (id != null && MetricUtils.isValidId(id)) {
            ret.put(metricName, id);
        } else {
            id = metricIDGenerator.genMetricId(metricName);
            Long old = memMeta.putIfAbsent(metricName, id);
            if (old == null) {
                ret.put(metricName, id);
            } else {
                ret.put(metricName, old);
            }
        }
    }
    long cost = ticker.stop();
    LOG.info("register metrics, topology:{}, size:{}, cost:{}", topologyId, metricNames.size(), cost);

    return ret;
}

From source file:io.druid.query.extraction.namespace.TestKafkaExtractionCluster.java

@Test
public void testSimpleRename() throws InterruptedException {
    final Properties kafkaProducerProperties = makeProducerProperties();
    final Producer<byte[], byte[]> producer = new Producer<byte[], byte[]>(
            new ProducerConfig(kafkaProducerProperties));
    try {/* ww w  .ja  v a 2s . c  o m*/
        checkServer();
        final ConcurrentMap<String, Function<String, String>> fnFn = injector
                .getInstance(Key.get(new TypeLiteral<ConcurrentMap<String, Function<String, String>>>() {
                }, Names.named("namespaceExtractionFunctionCache")));
        KafkaExtractionNamespace extractionNamespace = new KafkaExtractionNamespace(topicName, namespace);

        Assert.assertEquals(null, fnFn.get(extractionNamespace.getNamespace()).apply("foo"));

        long events = renameManager.getNumEvents(namespace);

        log.info("-------------------------     Sending foo bar     -------------------------------");
        producer.send(new KeyedMessage<byte[], byte[]>(topicName, StringUtils.toUtf8("foo"),
                StringUtils.toUtf8("bar")));

        long start = System.currentTimeMillis();
        while (events == renameManager.getNumEvents(namespace)) {
            Thread.sleep(10);
            if (System.currentTimeMillis() > start + 60_000) {
                throw new ISE("Took too long to update event");
            }
        }

        log.info("-------------------------     Checking foo bar     -------------------------------");
        Assert.assertEquals("bar", fnFn.get(extractionNamespace.getNamespace()).apply("foo"));
        Assert.assertEquals(null, fnFn.get(extractionNamespace.getNamespace()).apply("baz"));

        checkServer();
        events = renameManager.getNumEvents(namespace);

        log.info("-------------------------     Sending baz bat     -------------------------------");
        producer.send(new KeyedMessage<byte[], byte[]>(topicName, StringUtils.toUtf8("baz"),
                StringUtils.toUtf8("bat")));
        while (events == renameManager.getNumEvents(namespace)) {
            Thread.sleep(10);
            if (System.currentTimeMillis() > start + 60_000) {
                throw new ISE("Took too long to update event");
            }
        }

        log.info("-------------------------     Checking baz bat     -------------------------------");
        Assert.assertEquals("bat", fnFn.get(extractionNamespace.getNamespace()).apply("baz"));
    } finally {
        producer.close();
    }
}

From source file:com.networknt.light.rule.transform.AbstractTransformRule.java

public List<Map<String, Object>> getTransformRequest(String ruleClass) {
    String sql = "SELECT FROM TransformRequest WHERE ruleClass = '" + ruleClass + "' ORDER BY sequence";
    List<Map<String, Object>> transforms = null;

    Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) ruleMap.get("cache");
    if (cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        ruleMap.put("cache", cache);
    } else {//  w  w w .  j a  va  2s .  c  o  m
        Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
        if (rule != null) {
            transforms = (List<Map<String, Object>>) rule.get("transformRequest");
        }
    }
    if (transforms == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(sql);
            List<ODocument> docs = graph.getRawGraph().command(query).execute();
            transforms = new ArrayList<Map<String, Object>>();
            if (docs != null) {
                for (ODocument doc : docs) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("sequence", doc.field("sequence"));
                    map.put("transformRule", doc.field("transformRule"));
                    map.put("transformData", doc.field("transformData"));
                    map.put("createUserId", doc.field("createUserId"));
                    transforms.add(map);
                }
            }
            // put an empty list into the cache if no transform rules available. This can avoid access db every time the cache is hit.
            Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
            if (rule != null) {
                rule.put("transformRequest", transforms);
            } else {
                rule = new HashMap<String, Object>();
                rule.put("transformRequest", transforms);
                cache.put(ruleClass, rule);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return transforms;
}

From source file:com.networknt.light.rule.transform.AbstractTransformRule.java

public List<Map<String, Object>> getTransformResponse(String ruleClass) {
    String sql = "SELECT FROM TransformResponse WHERE ruleClass = '" + ruleClass + "' ORDER BY sequence";
    List<Map<String, Object>> transforms = null;

    Map<String, Object> ruleMap = ServiceLocator.getInstance().getMemoryImage("ruleMap");
    ConcurrentMap<Object, Object> cache = (ConcurrentMap<Object, Object>) ruleMap.get("cache");
    if (cache == null) {
        cache = new ConcurrentLinkedHashMap.Builder<Object, Object>().maximumWeightedCapacity(1000).build();
        ruleMap.put("cache", cache);
    } else {//  w w w  .jav a 2s  .c o  m
        Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
        if (rule != null) {
            transforms = (List<Map<String, Object>>) rule.get("transformResponse");
        }
    }
    if (transforms == null) {
        OrientGraph graph = ServiceLocator.getInstance().getGraph();
        try {
            OSQLSynchQuery<ODocument> query = new OSQLSynchQuery<>(sql);
            List<ODocument> docs = graph.getRawGraph().command(query).execute();
            transforms = new ArrayList<Map<String, Object>>();
            if (docs != null) {
                for (ODocument doc : docs) {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("sequence", doc.field("sequence"));
                    map.put("transformRule", doc.field("transformRule"));
                    map.put("transformData", doc.field("transformData"));
                    map.put("createUserId", doc.field("createUserId"));
                    transforms.add(map);
                }
            }
            // put an empty list into the cache if no transform rules available. This can avoid access db every time the cache is hit.
            Map<String, Object> rule = (Map<String, Object>) cache.get(ruleClass);
            if (rule != null) {
                rule.put("transformResponse", transforms);
            } else {
                rule = new HashMap<String, Object>();
                rule.put("transformResponse", transforms);
                cache.put(ruleClass, rule);
            }
        } catch (Exception e) {
            logger.error("Exception:", e);
            throw e;
        } finally {
            graph.shutdown();
        }
    }
    return transforms;
}

From source file:org.onosproject.store.trivial.impl.SimpleDeviceStore.java

@Override
public DeviceEvent updatePortStatus(ProviderId providerId, DeviceId deviceId, PortDescription portDescription) {
    Device device = devices.get(deviceId);
    checkArgument(device != null, DEVICE_NOT_FOUND, deviceId);

    Map<ProviderId, DeviceDescriptions> descsMap = deviceDescs.get(deviceId);
    checkArgument(descsMap != null, DEVICE_NOT_FOUND, deviceId);

    synchronized (descsMap) {
        DeviceDescriptions descs = descsMap.get(providerId);
        // assuming all providers must give DeviceDescription first
        checkArgument(descs != null, "Device description for Device ID %s from Provider %s was not found",
                deviceId, providerId);/*w  w  w.  j  a  va  2s  .  c o m*/

        ConcurrentMap<PortNumber, Port> ports = getPortMap(deviceId);
        final PortNumber number = portDescription.portNumber();
        final Port oldPort = ports.get(number);
        final Port newPort;

        // update description
        descs.putPortDesc(portDescription);
        newPort = composePort(device, number, descsMap);

        if (oldPort == null) {
            return createPort(device, newPort, ports);
        } else {
            return updatePort(device, oldPort, newPort, ports);
        }
    }
}

From source file:com.censoredsoftware.infractions.bukkit.legacy.CommandHandler.java

@Override
public boolean onCommand(CommandSender sender, Command c, String label, String[] args) {
    Player p = null;//from   w  w  w.  j  a  v a 2s .  c  o  m
    if (sender instanceof Player)
        p = (Player) sender;
    if (c.getName().equalsIgnoreCase("infractions")) {
        MiscUtil.sendMessage(p, "---------------");
        MiscUtil.sendMessage(p, "INFRACTIONS HELP");
        MiscUtil.sendMessage(p, "---------------");
        if (MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /cite <player> <infraction> [proof-url]");
            MiscUtil.sendMessage(p, ChatColor.GRAY + "  /uncite <player> <key>" + ChatColor.WHITE
                    + " - Find the key with " + ChatColor.YELLOW + "/history" + ChatColor.WHITE + ".");
        }
        MiscUtil.sendMessage(p, ChatColor.GRAY + "  /history [player]");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /reasons " + ChatColor.WHITE + "- Shows all valid infraction reasons.");
        MiscUtil.sendMessage(p,
                ChatColor.GRAY + "  /virtues " + ChatColor.WHITE + "- Shows all valid virtue types.");
        return true;
    } else if (c.getName().equalsIgnoreCase("reasons")) {
        MiscUtil.sendMessage(p, "------------------");
        MiscUtil.sendMessage(p, "INFRACTION REASONS");
        MiscUtil.sendMessage(p, "------------------");

        for (int i = 1; i < 6; i++) {
            MiscUtil.sendMessage(p,
                    (i < 3 ? ChatColor.GREEN : i < 5 ? ChatColor.YELLOW : ChatColor.RED) + "Level " + i + ":");
            for (int j = 0; j < SettingUtil.getLevel(i).size(); j++)
                MiscUtil.sendMessage(p, "  " + SettingUtil.getLevel(i).get(j));
        }
        return true;
    } else if (c.getName().equalsIgnoreCase("cite")) {
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }
        if (SettingUtil.getSettingBoolean("require_proof")) {
            if ((args.length != 3)) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
            if (!URLUtil.isValidURL(args[2])) {
                MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                return false;
            }
        }
        if (args.length == 0 || args.length == 1) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }

        if (Infractions.getCompleteDossier(args[0]) == null) {
            MiscUtil.sendMessage(p, "This player hasn't joined yet.");
            return true;
        }
        // Levels
        Integer level = SettingUtil.getLevel(args[1]);
        if (level != null) {
            if (args.length == 3) {
                if (!URLUtil.isValidURL(args[2])) {
                    MiscUtil.sendMessage(p, "You must provide a valid URL as proof.");
                    return false;
                }
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        URLUtil.convertURL(args[2]));
            } else {
                MiscUtil.addInfraction(MiscUtil.getInfractionsPlayer(args[0]), sender, level, args[1],
                        "No proof.");
            }
            MiscUtil.sendMessage(p, ChatColor.GOLD + "Success! " + ChatColor.WHITE + "The level " + level
                    + " infraction has been received.");
            MiscUtil.kickNotify(MiscUtil.getInfractionsPlayer(args[0]), args[1]);
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("uncite")) {
        if (!(args.length == 2)) {
            MiscUtil.sendMessage(p, "Not enough arguments.");
            return false;
        }
        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod")) {
            MiscUtil.sendMessage(p, "You do not have enough permissions.");
            return true;
        }

        if (MiscUtil.removeInfraction(MiscUtil.getInfractionsPlayer(args[0]), args[1])) {
            MiscUtil.sendMessage(p, "Infraction removed!");
            try {
                MiscUtil.checkScore(MiscUtil.getInfractionsPlayer(args[0]));
            } catch (NullPointerException e) {
                // player is offline
            }
            return true;
        }
        MiscUtil.sendMessage(p, "No such infraction.");
        return true;
    } else if (c.getName().equalsIgnoreCase("history")) {
        if (!(args.length == 1) && !(p == null)) {
            if (MiscUtil.ignore(p)) {
                sender.sendMessage(ChatColor.YELLOW + "Infractions does not track your history.");
                return true;
            }

            p.performCommand("history " + p.getName());
            return true;
        }
        if ((p == null) && !(args.length == 1)) {
            log.info("You must provide a username in the console.");
            return false;
        }

        if (!MiscUtil.hasPermissionOrOP(p, "infractions.mod") && !p.getName().toLowerCase().equals(args[0])) {
            p.sendMessage(ChatColor.RED + "You don't have permission to do that.");
            return true;
        }

        /**
         * DISPLAY ALL CURRENT INFRACTIONS
         */

        String player = MiscUtil.getInfractionsPlayer(args[0]);
        if (player != null) {
            sender.sendMessage("   ");

            CompleteDossier dossier = Infractions.getCompleteDossier(player);

            Integer maxScore = MiscUtil.getMaxScore(Infractions.getCompleteDossier(player).getId());
            String chatLevel = InfractionsPlugin.getLevelForChat(player);
            MiscUtil.sendMessage(p,
                    ChatColor.WHITE + (chatLevel.equals("") ? "" : chatLevel + " ") + ChatColor.YELLOW + player
                            + ChatColor.WHITE + " - " + MiscUtil.getScore(player)
                            + (maxScore == null ? " points towards a ban."
                                    : " points out of " + maxScore + " until a ban."));

            try {
                boolean staff = MiscUtil.hasPermissionOrOP(p, "infractions.mod");
                Set<Infraction> infractions = dossier.getInfractions();
                if (!infractions.isEmpty()) {
                    for (Infraction infraction : infractions) {
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_RED + " " + ChatColor.DARK_PURPLE
                                        + StringUtils.capitalize(infraction.getReason()) + ChatColor.DARK_GRAY
                                        + " - " + ChatColor.BLUE + FORMAT.format(infraction.getDateCreated()));
                        MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Penalty: " + ChatColor.GRAY
                                + infraction.getScore());
                        MiscUtil.sendMessage(p,
                                ChatColor.DARK_GRAY + "     Proof: " + ChatColor.GRAY
                                        + Iterables.getFirst(Collections2.transform(infraction.getEvidence(),
                                                new Function<Evidence, Object>() {
                                                    @Override
                                                    public String apply(Evidence evidence) {
                                                        return evidence.getRawData();
                                                    }
                                                }), "No Proof."));
                        if (staff) {
                            String id = MiscUtil.getInfractionId(infraction);
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "     Key: " + ChatColor.GRAY + id);
                            String issuerId = infraction.getIssuer().getId();
                            if (IssuerType.STAFF.equals(infraction.getIssuer().getType())) {
                                UUID issuerUUID = UUID.fromString(issuerId);
                                ConcurrentMap<UUID, LegacyDossier> map = DataManager.getManager()
                                        .getMapFor(LegacyDossier.class);
                                if (map.containsKey(issuerUUID)
                                        && map.get(issuerUUID) instanceof CompleteDossier) {
                                    CompleteDossier issuerDossier = (LegacyCompleteDossier) map.get(issuerUUID);
                                    issuerId = issuerDossier.getLastKnownName();
                                } else {
                                    issuerId = "INVALID UUID: " + issuerId;
                                }
                            }
                            MiscUtil.sendMessage(p,
                                    ChatColor.DARK_GRAY + "     Issuer: " + ChatColor.GRAY + issuerId);
                        }
                    }
                } else
                    MiscUtil.sendMessage(p, ChatColor.DARK_GREEN + " " + ChatColor.WHITE
                            + "No infractions found for this player.");
                if (!staff)
                    return true;
                Set<InetAddress> addresses = dossier.getAssociatedIPAddresses();
                MiscUtil.sendMessage(p,
                        ChatColor.BLUE + " " + ChatColor.DARK_AQUA + "Associated IP Addresses:");
                if (addresses.isEmpty())
                    MiscUtil.sendMessage(p, ChatColor.GRAY + "     No currently known addresses.");
                else
                    for (InetAddress address : addresses) {
                        MiscUtil.sendMessage(p, ChatColor.GRAY + "     " + address.getHostAddress());
                        Collection<String> others = AsyncIPMatcherTask.getRelatives(dossier.getId());
                        if (others.size() > 1) {
                            MiscUtil.sendMessage(p, ChatColor.DARK_GRAY + "       - also associated with:");
                            for (String other : others) {
                                if (other.equals(player))
                                    continue;
                                MiscUtil.sendMessage(p,
                                        ChatColor.GRAY + "         " + ChatColor.YELLOW + other);
                            }
                        }
                    }

                sender.sendMessage("   ");
                return true;
            } catch (NullPointerException e) {
                return true;
            }
        } else {
            MiscUtil.sendMessage(p, "A player with the name \"" + args[0] + "\" cannot be found.");
            return true;
        }
    } else if (c.getName().equalsIgnoreCase("clearhistory") && p != null
            && p.hasPermission("infractions.clearhistory") && args.length > 0) {
        try {
            Player remove = Bukkit.getServer().matchPlayer(args[0]).get(0);
            Infractions.removeDossier(remove.getUniqueId());
            remove.kickPlayer(ChatColor.GREEN + "Your Infractions history has been reset--please join again.");
            return true;
        } catch (Exception error) {
            sender.sendMessage(ChatColor.RED + "Could not find that player...");
            return false;
        }
    }
    MiscUtil.sendMessage(p, "Something went wrong, please try again.");
    return false;
}

From source file:rocks.stalin.android.app.model.MusicProvider.java

private synchronized void buildListsByGenre() {
    ConcurrentMap<String, List<MediaMetadataCompat>> newMusicListByGenre = new ConcurrentHashMap<>();

    for (MutableMediaMetadata m : mMusicListById.values()) {
        String genre = "";
        if (m.metadata.containsKey(MediaMetadataCompat.METADATA_KEY_GENRE)) {
            genre = m.metadata.getString(MediaMetadataCompat.METADATA_KEY_GENRE);
        }/* ww w  .  ja v a 2  s. com*/
        List<MediaMetadataCompat> list = newMusicListByGenre.get(genre);
        if (list == null) {
            list = new ArrayList<>();
            newMusicListByGenre.put(genre, list);
        }
        list.add(m.metadata);
    }
    mMusicListByGenre = newMusicListByGenre;
}

From source file:org.amplafi.hivemind.factory.servicessetter.ServicesSetterImpl.java

/**
 * @see com.sworddance.core.ServicesSetter#wire(java.lang.Object, java.lang.Iterable)
 *///from   ww w  .j a v a 2 s . c o m
@Override
@SuppressWarnings("unchecked")
public void wire(Object obj, Iterable<String> excludedProperties) {
    if (obj == null) {
        return;
    }
    List<String> props = getWriteableProperties(obj);
    Set<String> alwaysExcludedCollection = this.cachedAlwaysExcludedMap.get(obj.getClass());

    if (alwaysExcludedCollection != null) {
        props.removeAll(alwaysExcludedCollection);
        if (getLog().isDebugEnabled()) {
            getLog().debug(obj.getClass() + ": autowiring. Class has already been filtered down to "
                    + props.size() + "properties. props={" + join(props, ",") + "}");
        }
    } else {
        if (getLog().isDebugEnabled()) {
            getLog().debug(obj.getClass() + ": autowiring for the first time. Class has at most " + props.size()
                    + "properties. props={" + join(props, ",") + "}");
        }
        alwaysExcludedCollection = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());
        this.cachedAlwaysExcludedMap.putIfAbsent(obj.getClass(), alwaysExcludedCollection);
        alwaysExcludedCollection = this.cachedAlwaysExcludedMap.get(obj.getClass());
    }
    for (String exclude : excludedProperties) {
        props.remove(exclude);
    }
    int wiredCount = 0;

    for (String prop : props) {
        PropertyAdaptor type = getPropertyAdaptor(obj, prop);
        Class propertyType = type.getPropertyType();
        if (!isWireableClass(propertyType)) {
            // if it is a standard java class then lets exclude it.
            alwaysExcludedCollection.add(prop);
            continue;
        }
        // if it is not readable then, then we can't verify that
        // we are not overwriting non-null property.
        if (!type.isReadable() || !type.isWritable()) {
            alwaysExcludedCollection.add(prop);
            continue;
        }
        // check to see if we have a service to offer before bothering
        // to checking if the property can be set. This avoids triggering
        // actions caused by calling the get/setters.
        Object srv = null;
        if (type.getPropertyType() == Log.class) {
            // log is special.
            srv = LogFactory.getLog(obj.getClass());
        } else {
            ConcurrentMap<String, String> classServiceMap = this.serviceMap.get(obj.getClass());
            if (classServiceMap == null) {
                this.serviceMap.putIfAbsent(obj.getClass(), new ConcurrentHashMap<String, String>());
                classServiceMap = this.serviceMap.get(obj.getClass());
            }
            String serviceName = classServiceMap.get(prop);
            if (serviceName == null) {
                InjectService service;
                try {
                    service = findInjectService(obj, type);
                } catch (DontInjectException e) {
                    // do nothing
                    alwaysExcludedCollection.add(prop);
                    continue;
                }

                if (service != null) {
                    serviceName = service.value();
                    if (isNotBlank(serviceName)) {
                        for (String attempt : new String[] { serviceName,
                                serviceName + '.' + type.getPropertyName(),
                                serviceName + '.' + StringUtils.capitalize(type.getPropertyName()) }) {
                            srv = getService(attempt, propertyType);
                            if (srv != null) {
                                serviceName = attempt;
                                break;
                            }
                        }
                    }
                }
                if (srv != null) {
                    classServiceMap.putIfAbsent(prop, serviceName);
                } else {
                    // we looked but did not find... no need to look again.
                    classServiceMap.putIfAbsent(prop, "");
                }
            } else if (!serviceName.isEmpty()) {
                // we already found the service.
                srv = getService(serviceName, propertyType);
            }
            if (srv == null && !noServiceForType.containsKey(propertyType)) {
                try {
                    srv = this.module.getService(propertyType);
                } catch (Exception e) {
                    noServiceForType.put(propertyType, e);
                    getLog().debug("Look up of class " + propertyType
                            + " failed. The failure is caused if there is not exactly 1 service implementing the class. Further searches by this property class will be ignored.");
                }
            }
        }
        if (srv == null) {
            alwaysExcludedCollection.add(prop);
        } else if (type.read(obj) == null) {
            // Doing the read check last avoids
            // triggering problems caused by lazy initialization and read-only properties.
            if (type.getPropertyType().isAssignableFrom(srv.getClass())) {
                type.write(obj, srv);
                wiredCount++;
            } else {
                // this is probably an error so we do not just add to the exclude list.
                throw new ApplicationRuntimeException("Trying to set property " + obj.getClass() + "." + prop
                        + " however, the property type=" + type.getPropertyType()
                        + " is not a superclass or same class as " + srv.getClass() + ". srv=" + srv);
            }
        }
    }
    if (getLog().isDebugEnabled()) {
        getLog().debug(obj.getClass() + ": done autowiring. actual number of properties wired=" + wiredCount
                + " excluded properties=" + alwaysExcludedCollection);
    }
}

From source file:robert843.o2.pl.player.model.MusicProvider.java

private synchronized void retrieveMedia() {
    PlaylistDB pdb = new PlaylistDB(this.mContext);
    ConcurrentMap<String, List<MediaMetadata>> newMusicListByGenre = new ConcurrentHashMap<>();
    try {/*w  ww .j  a  v a 2s . c  o m*/
        if (mCurrentState == State.NON_INITIALIZED) {
            mCurrentState = State.INITIALIZING;
            for (String playlist : pdb.getListPlaylist()) {
                for (String id : pdb.getTracks(playlist)) {
                    List<MediaMetadata> list = newMusicListByGenre.get(playlist);
                    if (list == null) {
                        list = new ArrayList<>();
                        newMusicListByGenre.put(playlist, list);
                    }
                    MediaMetadata item = buildFromJSON(id);
                    String musicId = item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
                    mMusicListById.put(musicId, new MutableMediaMetadata(musicId, item));
                    list.add(item);
                }
            }
            mMusicListByGenre = newMusicListByGenre;
            /*int slashPos = CATALOG_URL.lastIndexOf('/');
            String path = CATALOG_URL.substring(0, slashPos + 1);
            JSONObject jsonObj = fetchJSONFromUrl(CATALOG_URL);
            if (jsonObj == null) {
            return;
            }
            JSONArray tracks = jsonObj.getJSONArray(JSON_MUSIC);
            if (tracks != null) {
            for (int j = 0; j < tracks.length(); j++) {
                MediaMetadata item = buildFromJSON(tracks.getJSONObject(j), path);
                String musicId = item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
                mMusicListById.put(musicId, new MutableMediaMetadata(musicId, item));
            }
            buildListsByGenre();
            }*/

            mCurrentState = State.INITIALIZED;
        }
    } catch (JSONException e) {
        LogHelper.e(TAG, e, "Could not retrieve music list");
    } catch (ParserConfigurationException e) {
        LogHelper.e(TAG, e, "Could not retrieve music list");
    } catch (IOException e) {
        //  e.printStackTrace();
    } finally {
        if (mCurrentState != State.INITIALIZED) {
            // Something bad happened, so we reset state to NON_INITIALIZED to allow
            // retries (eg if the network connection is temporary unavailable)
            mCurrentState = State.NON_INITIALIZED;
        }
    }
}