Example usage for java.util EnumMap EnumMap

List of usage examples for java.util EnumMap EnumMap

Introduction

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

Prototype

public EnumMap(Map<K, ? extends V> m) 

Source Link

Document

Creates an enum map initialized from the specified map.

Usage

From source file:org.apache.hadoop.corona.Scheduler.java

/**
 * Used by unit test to fake the ConfigManager
 *
 * @param nodeManager Manages the nodes and their resources
 * @param sessionManager Manages a collection of sessions
 * @param sessionNotifier Delivers notifications to sessions asynchronously
 * @param types Types of resources//from w  w w .  java2  s .  com
 * @param metrics Cluster Manager metrics.
 * @param configManager Manages the reloadable configuration
 * @param conf Static configuration
 */
public Scheduler(NodeManager nodeManager, SessionManager sessionManager, SessionNotifier sessionNotifier,
        Collection<ResourceType> types, ClusterManagerMetrics metrics, CoronaConf conf,
        ConfigManager configManager) {
    this.configManager = configManager;
    this.schedulersForTypes = new EnumMap<ResourceType, SchedulerForType>(ResourceType.class);
    this.types = types;
    for (ResourceType type : types) {
        SchedulerForType schedulerForType = new SchedulerForType(type, sessionManager, sessionNotifier,
                nodeManager, configManager, metrics, conf);
        schedulerForType.setDaemon(true);
        schedulerForType.setName("Scheduler-" + type);
        schedulersForTypes.put(type, schedulerForType);
    }
    this.conf = conf;
}

From source file:fr.free.movierenamer.scrapper.impl.image.TMDbImagesScrapper.java

@Override
protected List<ImageInfo> fetchImagesInfo(Movie movie) throws Exception {
    String id = movie.getId().toString();
    switch (movie.getId().getIdType()) {
    case IMDB://w w w.  j a v a2 s.  co  m
        id = imdbIDLookUp(id);
        break;
    case TMDB:
        break;
    default:
        throw new UnsupportedOperationException(
                movie.getId().getIdType() + " is not supported by " + getName() + " image scrapper");
    }

    URL searchUrl = new URL("http", host, "/" + version + "/movie/" + id + "/images?api_key=" + apikey);
    JSONObject json = URIRequest.getJsonDocument(searchUrl.toURI());

    List<ImageInfo> images = new ArrayList<ImageInfo>();
    for (String section : new String[] { "backdrops", "posters" }) {
        List<JSONObject> jsonObjs = JSONUtils.selectList(section, json);
        TmdbImageSize imageSize = section.equals("backdrops") ? TmdbImageSize.backdrop : TmdbImageSize.poster;
        int count = 0;
        for (JSONObject jsonObj : jsonObjs) {
            Map<ImageInfo.ImageProperty, String> imageFields = new EnumMap<ImageInfo.ImageProperty, String>(
                    ImageInfo.ImageProperty.class);
            String file_path = JSONUtils.selectString("file_path", jsonObj);

            imageFields.put(ImageInfo.ImageProperty.url,
                    TMDbScrapper.imageUrl + imageSize.getBig() + file_path);
            imageFields.put(ImageInfo.ImageProperty.urlMid,
                    TMDbScrapper.imageUrl + imageSize.getMedium() + file_path);
            imageFields.put(ImageInfo.ImageProperty.urlTumb,
                    TMDbScrapper.imageUrl + imageSize.getSmall() + file_path);

            String lang = JSONUtils.selectString("iso_639_1", jsonObj);
            if (lang != null && !lang.equals("null")) {
                imageFields.put(ImageInfo.ImageProperty.language, lang);
            }
            imageFields.put(ImageInfo.ImageProperty.width, JSONUtils.selectString("width", jsonObj));
            imageFields.put(ImageInfo.ImageProperty.height, JSONUtils.selectString("height", jsonObj));

            images.add(new ImageInfo(count++, imageFields,
                    section.equals("posters") ? ImageInfo.ImageCategoryProperty.thumb
                            : ImageInfo.ImageCategoryProperty.fanart));
        }
    }

    return images;
}

From source file:de.matzefratze123.heavyspleef.core.FlagManager.java

public void addFlag(AbstractFlag<?> flag) {
    Class<?> clazz = flag.getClass();

    Validate.isTrue(clazz.isAnnotationPresent(Flag.class),
            "Flag class " + clazz.getCanonicalName() + " must annotate " + Flag.class.getCanonicalName());
    Flag flagAnnotation = clazz.getAnnotation(Flag.class);

    //Generate the full path
    StringBuilder pathBuilder = new StringBuilder();

    Flag lastParentFlagData = flagAnnotation;
    while (lastParentFlagData != null) {
        pathBuilder.insert(0, lastParentFlagData.name());

        Class<? extends AbstractFlag<?>> parentClass = lastParentFlagData.parent();
        lastParentFlagData = parentClass.getAnnotation(Flag.class);

        if (lastParentFlagData != null) {
            pathBuilder.insert(0, ":");
        }//  w  w  w .  j  a  v  a 2 s  . c  o m
    }

    String path = pathBuilder.toString();

    if (flags.containsKey(path)) {
        return;
    }

    flags.put(path, flag);

    if (clazz.isAnnotationPresent(BukkitListener.class)) {
        Bukkit.getPluginManager().registerEvents(flag, plugin);
    }

    if (flagAnnotation.hasGameProperties()) {
        Map<GameProperty, Object> flagGamePropertiesMap = new EnumMap<GameProperty, Object>(GameProperty.class);
        flag.defineGameProperties(flagGamePropertiesMap);

        if (!flagGamePropertiesMap.isEmpty()) {
            GamePropertyBundle properties = new GamePropertyBundle(flag, flagGamePropertiesMap);
            propertyBundles.add(properties);
        }
    }
}

From source file:com.google.i18n.addressinput.common.ClientData.java

/**
 * Returns the contents of the JSON-format string as a map.
 *//*from   w  ww.j  ava2  s .  c  o m*/
protected AddressVerificationNodeData createNodeData(JsoMap jso) {
    Map<AddressDataKey, String> map = new EnumMap<AddressDataKey, String>(AddressDataKey.class);

    JSONArray arr = jso.getKeys();
    for (int i = 0; i < arr.length(); i++) {
        try {
            AddressDataKey key = AddressDataKey.get(arr.getString(i));

            if (key == null) {
                // Not all keys are supported by Android, so we continue if we encounter one
                // that is not used.
                continue;
            }

            String value = jso.get(Util.toLowerCaseLocaleIndependent(key.toString()));
            map.put(key, value);
        } catch (JSONException e) {
            // This should not happen - we should not be fetching a key from outside the bounds
            // of the array.
        }
    }

    return new AddressVerificationNodeData(map);
}

From source file:org.lilyproject.runtime.configuration.ConfRegistryImpl.java

/**
 * Checks for configuration changes on disk and reloads as necessary.
 *
 * <p>If there are listeners to be notified of changes, this will not happen immediately,
 * but a Runnable will be returned, executing this Runnable will notify the listeners.
 * The purpose of this is that the notification of listeners would not block the
 * refreshing performed by the ConfManager (ConfListener's should return quickly,
 * but you never know). The ConfManager might decide to either run the Runnable
 * after refreshing all ConfRegistry's, possibly executing them on a background thread.
 *//*from   www.ja  va  2 s.c o m*/
public Runnable refresh() {
    // Refresh the lower-level conf registries
    for (ConfSource source : sources) {
        source.refresh();
    }

    // Determine list of all available configuration paths
    Set<String> paths = new HashSet<String>();
    for (ConfSource source : sources) {
        paths.addAll(source.getPaths());
    }

    Map<ChangeType, Set<String>> changesByType = new EnumMap<ChangeType, Set<String>>(ChangeType.class);
    for (ChangeType changeType : ChangeType.values()) {
        changesByType.put(changeType, new HashSet<String>());
    }

    // Delete confs which no longer exist
    root.removeUnexistingChildren(paths, "", changesByType);

    // Update/add the existing/new confs
    for (String path : paths) {
        String[] parsedPath = path.split("/"); // we assume our sources only deliver clean paths without empty path segments
        ConfPath confPath = root.getConfPath(parsedPath, 0);
        boolean changes;

        if (confPath != null && confPath.conf != null) {
            changes = confPath.conf.refresh();
        } else {
            MergedConfig config = new MergedConfig(path);
            config.refresh();
            root.addConf(parsedPath, 0, config, changesByType);
            changes = true; // a new config is always a change
        }

        if (changes) {
            changesByType.get(ChangeType.CONF_CHANGE).add(path);
        }
    }

    return getListenerNotificationRunnable(changesByType);
}

From source file:com.android.i18n.addressinput.ClientData.java

/**
 * Returns the contents of the JSON-format string as a map.
 *///from ww  w. j a va  2 s  .co  m
protected AddressVerificationNodeData createNodeData(JsoMap jso) {
    Map<AddressDataKey, String> map = new EnumMap<AddressDataKey, String>(AddressDataKey.class);

    JSONArray arr = jso.getKeys();
    for (int i = 0; i < arr.length(); i++) {
        try {
            AddressDataKey key = AddressDataKey.get(arr.getString(i));

            if (key == null) {
                // Not all keys are supported by Android, so we continue if we encounter one
                // that is not used.
                continue;
            }

            String value = jso.get(key.toString().toLowerCase());
            map.put(key, value);
        } catch (JSONException e) {
            // This should not happen - we should not be fetching a key from outside the bounds
            // of the array.
        }
    }

    return new AddressVerificationNodeData(map);
}

From source file:fr.romainf.QRCode.java

/**
 * Writes data as a QRCode in an image./*from  ww w  . ja v  a 2  s  . c  o m*/
 *
 * @param data        String The data to encode in a QRCode
 * @param output      String The output filename
 * @param pixelColour Color The colour of pixels representing bits
 * @throws WriterException
 * @throws IOException
 */
private static void writeQRCode(String data, String output, Color pixelColour)
        throws WriterException, IOException {
    Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    hints.put(EncodeHintType.MARGIN, DEFAULT_MARGIN);

    BitMatrix bitMatrix = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, DEFAULT_WIDTH, DEFAULT_HEIGHT,
            hints);

    File file = new File(output);
    if (file.isDirectory()) {
        file = new File(output + File.separator + DEFAULT_OUTPUT_FILE);
    }
    if (!file.createNewFile() && !file.canWrite()) {
        throw new IOException("Cannot write file " + file);
    }

    SVGGraphics2D graphics2D = renderSVG(bitMatrix, pixelColour);
    graphics2D.stream(new FileWriter(file), true);
}

From source file:org.zanata.client.commands.FileMappingRuleHandler.java

@VisibleForTesting
protected static EnumMap<Placeholders, String> parseToMap(@Nonnull String sourceFile,
        @Nonnull LocaleMapping localeMapping, Optional<String> translationFileExtension) {
    EnumMap<Placeholders, String> parts = new EnumMap<Placeholders, String>(Placeholders.class);
    File file = new File(sourceFile);

    String extension = translationFileExtension.isPresent() ? translationFileExtension.get()
            : FilenameUtils.getExtension(sourceFile);
    String filename = FilenameUtils.removeExtension(file.getName());
    parts.put(Placeholders.extension, extension);
    parts.put(Placeholders.filename, filename);
    parts.put(Placeholders.locale, localeMapping.getLocalLocale());
    parts.put(Placeholders.localeWithUnderscore, localeMapping.getLocalLocale().replaceAll("\\-", "_"));
    String pathname = Strings.nullToEmpty(file.getParent());
    parts.put(Placeholders.path, FileUtil.simplifyPath(pathname));
    log.debug("parsed parts: {}", parts);
    return parts;
}

From source file:com.autentia.common.statemachine.StateMachine.java

@SuppressWarnings("unchecked")
protected StateMachine(T initialState, T... finalStates) {
    Assert.notNull(initialState, "initialState cannot be null");
    Assert.notEmpty(finalStates, "finalState cannot be null");

    this.enumClass = (Class<T>) initialState.getClass();
    this.initialState = initialState;
    this.finalStates = EnumSet.copyOf(Arrays.asList(finalStates));

    states = new EnumMap<T, Pair<State<T>, List<Transition<T>>>>(enumClass);
    createStateMachine();/*from  w  w  w .  j  a v a 2s. co  m*/
    checkConsistency();
}

From source file:io.lavagna.web.security.SecurityFilterTest.java

@Test
public void testSetupNotComplete() throws IOException, ServletException {

    SecurityFilter sf = new SecurityFilter();

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");

    Map<Key, String> conf = new EnumMap<>(Key.class);
    conf.put(Key.SETUP_COMPLETE, "false");
    when(configurationRepository.findConfigurationFor(Mockito.<Set<Key>>any())).thenReturn(conf);

    MockHttpServletResponse response = new MockHttpServletResponse();
    MockFilterChain chain = new MockFilterChain();

    sf.init(filterConfig);//from   w w w. ja  va  2 s . c om
    sf.doFilter(request, response, chain);
}