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.ambari.server.controller.AmbariManagementControllerImpl.java

private void addClientSchForReinstall(Cluster cluster, Map<State, List<Service>> changedServices,
        Map<String, Map<State, List<ServiceComponentHost>>> changedScHosts) throws AmbariException {

    Set<String> services = new HashSet<String>();

    // This is done to account for services with client only components.
    if (changedServices != null) {
        for (Entry<State, List<Service>> entry : changedServices.entrySet()) {
            if (State.STARTED != entry.getKey()) {
                continue;
            }//from  w  w w.  j  a v a2  s .  c o  m
            for (Service s : entry.getValue()) {
                if (State.INSTALLED == s.getDesiredState()) {
                    services.add(s.getName());
                }
            }
        }
    }

    // Flatten changed Schs that are going to be Started
    List<ServiceComponentHost> serviceComponentHosts = new ArrayList<ServiceComponentHost>();
    if (changedScHosts != null && !changedScHosts.isEmpty()) {
        for (Entry<String, Map<State, List<ServiceComponentHost>>> stringMapEntry : changedScHosts.entrySet()) {
            for (State state : stringMapEntry.getValue().keySet()) {
                if (state == State.STARTED) {
                    serviceComponentHosts.addAll(stringMapEntry.getValue().get(state));
                }
            }
        }
    }

    if (!serviceComponentHosts.isEmpty()) {
        for (ServiceComponentHost sch : serviceComponentHosts) {
            services.add(sch.getServiceName());
        }
    }

    if (services.isEmpty()) {
        return;
    }

    Map<String, List<ServiceComponentHost>> clientSchs = new HashMap<String, List<ServiceComponentHost>>();

    for (String serviceName : services) {
        Service s = cluster.getService(serviceName);
        for (String component : s.getServiceComponents().keySet()) {
            List<ServiceComponentHost> potentialHosts = new ArrayList<ServiceComponentHost>();
            ServiceComponent sc = s.getServiceComponents().get(component);
            if (sc.isClientComponent()) {
                for (ServiceComponentHost potentialSch : sc.getServiceComponentHosts().values()) {
                    Host host = clusters.getHost(potentialSch.getHostName());
                    // Host is alive and neither host nor SCH is in Maintenance State
                    if (!potentialSch.getHostState().equals(HostState.HEARTBEAT_LOST)
                            && potentialSch.getMaintenanceState() != MaintenanceState.ON
                            && host.getMaintenanceState(cluster.getClusterId()) == MaintenanceState.OFF) {
                        potentialHosts.add(potentialSch);
                    }
                }
            }
            if (!potentialHosts.isEmpty()) {
                clientSchs.put(sc.getName(), potentialHosts);
            }
        }
    }
    LOG.info("Client hosts for reinstall : " + clientSchs.size());

    if (changedScHosts != null) {
        for (Entry<String, List<ServiceComponentHost>> stringListEntry : clientSchs.entrySet()) {
            Map<State, List<ServiceComponentHost>> schMap = new EnumMap<State, List<ServiceComponentHost>>(
                    State.class);
            schMap.put(State.INSTALLED, stringListEntry.getValue());
            changedScHosts.put(stringListEntry.getKey(), schMap);
        }
    }
}

From source file:com.moviejukebox.model.Movie.java

/**
 * Copy the movie//from   www . j  a v a  2s  .c om
 *
 * @param aMovie
 * @return
 */
public static Movie newInstance(Movie aMovie) {
    Movie newMovie = new Movie();

    newMovie.baseName = aMovie.baseName;
    newMovie.baseFilename = aMovie.baseFilename;

    newMovie.title = aMovie.title;
    newMovie.titleSort = aMovie.titleSort;
    newMovie.originalTitle = aMovie.originalTitle;
    newMovie.year = aMovie.year;
    newMovie.releaseDate = aMovie.releaseDate;
    newMovie.plot = aMovie.plot;
    newMovie.outline = aMovie.outline;
    newMovie.quote = aMovie.quote;
    newMovie.tagline = aMovie.tagline;
    newMovie.company = aMovie.company;
    newMovie.runtime = aMovie.runtime;
    newMovie.language = aMovie.language;
    newMovie.videoType = aMovie.videoType;
    newMovie.subtitles = aMovie.subtitles;
    newMovie.container = aMovie.container;
    newMovie.resolution = aMovie.resolution;
    newMovie.aspect = aMovie.aspect;
    newMovie.videoSource = aMovie.videoSource;
    newMovie.videoOutput = aMovie.videoOutput;
    newMovie.fps = aMovie.fps;
    newMovie.certification = aMovie.certification;
    newMovie.showStatus = aMovie.showStatus;
    newMovie.scrapeLibrary = aMovie.scrapeLibrary;
    newMovie.extra = aMovie.extra;
    newMovie.trailerExchange = aMovie.trailerExchange;
    newMovie.trailerLastScan = aMovie.trailerLastScan;
    newMovie.libraryPath = aMovie.libraryPath;
    newMovie.movieType = aMovie.movieType;
    newMovie.formatType = aMovie.formatType;
    newMovie.top250 = aMovie.top250;
    newMovie.libraryDescription = aMovie.libraryDescription;
    newMovie.prebuf = aMovie.prebuf;
    newMovie.posterURL = aMovie.posterURL;
    newMovie.posterFilename = aMovie.posterFilename;
    newMovie.detailPosterFilename = aMovie.detailPosterFilename;
    newMovie.thumbnailFilename = aMovie.thumbnailFilename;
    newMovie.fanartURL = aMovie.fanartURL;
    newMovie.fanartFilename = aMovie.fanartFilename;
    newMovie.bannerURL = aMovie.bannerURL;
    newMovie.bannerFilename = aMovie.bannerFilename;
    newMovie.wideBannerFilename = aMovie.wideBannerFilename;
    newMovie.clearArtURL = aMovie.clearArtURL;
    newMovie.clearArtFilename = aMovie.clearArtFilename;
    newMovie.clearLogoURL = aMovie.clearLogoURL;
    newMovie.clearLogoFilename = aMovie.clearLogoFilename;
    newMovie.tvThumbURL = aMovie.tvThumbURL;
    newMovie.tvThumbFilename = aMovie.tvThumbFilename;
    newMovie.seasonThumbURL = aMovie.seasonThumbURL;
    newMovie.seasonThumbFilename = aMovie.seasonThumbFilename;
    newMovie.movieDiscURL = aMovie.movieDiscURL;
    newMovie.movieDiscFilename = aMovie.movieDiscFilename;
    newMovie.fileDate = aMovie.fileDate;
    newMovie.fileSize = aMovie.fileSize;
    newMovie.watchedFile = aMovie.watchedFile;
    newMovie.watchedNFO = aMovie.watchedNFO;
    newMovie.first = aMovie.first;
    newMovie.previous = aMovie.first;
    newMovie.next = aMovie.next;
    newMovie.last = aMovie.last;
    newMovie.file = aMovie.file;
    newMovie.containerFile = aMovie.containerFile;
    newMovie.setMaster = aMovie.setMaster;
    newMovie.setSize = aMovie.setSize;

    newMovie.idMap = new HashMap<>(aMovie.idMap);
    newMovie.countries = new LinkedHashSet<>(aMovie.countries);
    newMovie.ratings = new HashMap<>(aMovie.ratings);
    newMovie.directors = new LinkedHashSet<>(aMovie.directors);
    newMovie.sets = new HashMap<>(aMovie.sets);
    newMovie.genres = new TreeSet<>(aMovie.genres);
    newMovie.cast = new LinkedHashSet<>(aMovie.cast);
    newMovie.writers = new LinkedHashSet<>(aMovie.writers);
    newMovie.awards = new ArrayList<>(aMovie.awards);
    newMovie.people = new ArrayList<>(aMovie.people);
    newMovie.indexes = new HashMap<>(aMovie.indexes);
    newMovie.movieFiles = new TreeSet<>(aMovie.movieFiles);
    newMovie.extraFiles = new TreeSet<>(aMovie.extraFiles);
    newMovie.dirtyFlags = EnumSet.copyOf(aMovie.dirtyFlags);
    newMovie.codecs = new LinkedHashSet<>(aMovie.codecs);
    newMovie.footerFilename = new ArrayList<>(aMovie.footerFilename);
    newMovie.overrideSources = new EnumMap<>(aMovie.overrideSources);

    return newMovie;
}

From source file:com.att.aro.diagnostics.GraphPanel.java

private static void populateBurstPlot(XYPlot plot, TraceData.Analysis analysis) {

    final XYIntervalSeriesCollection burstDataCollection = new XYIntervalSeriesCollection();
    if (analysis != null) {

        Map<BurstCategory, XYIntervalSeries> seriesMap = new EnumMap<BurstCategory, XYIntervalSeries>(
                BurstCategory.class);
        final Map<BurstCategory, List<Burst>> burstMap = new HashMap<BurstCategory, List<Burst>>();
        for (BurstCategory eventType : BurstCategory.values()) {
            XYIntervalSeries series = new XYIntervalSeries(eventType);
            seriesMap.put(eventType, series);
            burstDataCollection.addSeries(series);
            burstMap.put(eventType, new ArrayList<Burst>());
        }/*from ww w  .ja  va2  s.  com*/
        final List<Burst> burstStates = analysis.getBurstInfos();
        Iterator<Burst> iter = burstStates.iterator();
        while (iter.hasNext()) {
            Burst currEvent = iter.next();
            if (currEvent != null) {
                BurstCategory burstState = currEvent.getBurstCategory();
                if (burstState != null) {
                    seriesMap.get(burstState).add(currEvent.getBeginTime(), currEvent.getBeginTime(),
                            currEvent.getEndTime(), 0.5, 0, 1);
                    burstMap.get(burstState).add(currEvent);
                }
            }
        }

        Color myGreen = new Color(34, 177, 76);
        Color lightGreen = new Color(134, 232, 162);

        XYItemRenderer renderer = plot.getRenderer();
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.TCP_PROTOCOL), Color.blue);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.TCP_LOSS_OR_DUP), Color.black);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.USER_INPUT), myGreen);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.SCREEN_ROTATION), lightGreen);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.CLIENT_APP), Color.red);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.SERVER_NET_DELAY), Color.yellow);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.LONG), Color.gray);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.PERIODICAL), Color.magenta);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.CPU), Color.cyan);
        renderer.setSeriesPaint(burstDataCollection.indexOf(BurstCategory.UNKNOWN), Color.darkGray);

        // Assign ToolTip to renderer
        renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
                BurstCategory eventType = (BurstCategory) burstDataCollection.getSeries(series).getKey();
                Burst b = burstMap.get(eventType).get(item);
                final String PREFIX = "BurstCategory.";
                return MessageFormat.format(rb.getString(PREFIX + eventType.ordinal()), b.getPackets().size(),
                        b.getBurstBytes(), b.getBurstThroughPut());
            }
        });

    }

    plot.setDataset(burstDataCollection);
}

From source file:com.att.aro.diagnostics.GraphPanel.java

private static void populateRrcPlot(XYPlot plot, TraceData.Analysis analysis) {

    final XYIntervalSeriesCollection rrcDataCollection = new XYIntervalSeriesCollection();
    if (analysis != null) {

        Map<RRCState, XYIntervalSeries> seriesMap = new EnumMap<RRCState, XYIntervalSeries>(RRCState.class);
        for (RRCState eventType : RRCState.values()) {
            XYIntervalSeries series = new XYIntervalSeries(eventType);
            seriesMap.put(eventType, series);
            rrcDataCollection.addSeries(series);
        }/*www.jav  a2 s .com*/
        List<RrcStateRange> rrcStates = analysis.getRrcStateMachine().getRRcStateRanges();
        Iterator<RrcStateRange> iter = rrcStates.iterator();
        while (iter.hasNext()) {
            RrcStateRange currEvent = iter.next();
            RRCState state = currEvent.getState();
            if (state == RRCState.STATE_FACH || state == RRCState.TAIL_FACH) {
                seriesMap.get(state).add(currEvent.getBeginTime(), currEvent.getBeginTime(),
                        currEvent.getEndTime(), 0.25, 0, 0.5);
            } else {
                seriesMap.get(state).add(currEvent.getBeginTime(), currEvent.getBeginTime(),
                        currEvent.getEndTime(), 0.5, 0, 1);
            }

        }
        XYItemRenderer renderer = plot.getRenderer();
        Color dchGreen = new Color(34, 177, 76);
        Color fachOrange = new Color(255, 201, 14);

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.STATE_IDLE), Color.white);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_IDLE), Color.white);

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.PROMO_IDLE_DCH), Color.red);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_PROMOTION), Color.red);

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.STATE_DCH), fachOrange);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_CONTINUOUS), fachOrange);

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.TAIL_DCH), getTailPaint(fachOrange));
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_CR_TAIL), getTailPaint(fachOrange));
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_DRX_SHORT), getTailPaint(fachOrange));
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.LTE_DRX_LONG), getTailPaint(fachOrange));

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.STATE_FACH), dchGreen);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.TAIL_FACH), getTailPaint(dchGreen));

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.PROMO_FACH_DCH), Color.red);

        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.WIFI_IDLE), Color.white);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.WIFI_ACTIVE), fachOrange);
        renderer.setSeriesPaint(rrcDataCollection.indexOf(RRCState.WIFI_TAIL), getTailPaint(fachOrange));

        // Assign ToolTip to renderer
        final Profile profile = analysis.getProfile();
        renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
                RRCState eventType = (RRCState) rrcDataCollection.getSeries(series).getKey();
                final String PREFIX = "RRCTooltip.";
                if (eventType == RRCState.LTE_IDLE) {
                    return MessageFormat.format(rb.getString(PREFIX + eventType),
                            ((ProfileLTE) profile).getIdlePingPeriod());
                }
                return rb.getString(PREFIX + eventType);
            }
        });

    }

    plot.setDataset(rrcDataCollection);
}

From source file:org.yccheok.jstock.gui.JStock.java

public void createCountryMenuItems() {
    final java.util.List<Country> countries = Utils.getSupportedStockMarketCountries();

    Map<Continent, JMenu> menus = new EnumMap<>(Continent.class);
    for (final Continent continent : Continent.values()) {
        JMenu jMenu = new JMenu(continent.name());
        jMenu6.add(jMenu);//from ww w.  j  ava 2 s . c  o  m
        menus.put(continent, jMenu);
    }

    for (final Country country : countries) {
        JMenu jMenu = menus.get(Continent.toContinent(country));

        // Ugly fix on spelling mistake.
        final JMenuItem mi = (JRadioButtonMenuItem) jMenu
                .add(new JRadioButtonMenuItem(country.humanString, country.icon));

        buttonGroup2.add(mi);
        mi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JStock.this.changeCountry(country);
            }
        });

        if (jStockOptions.getCountry() == country) {
            ((JRadioButtonMenuItem) mi).setSelected(true);
        }
    }
}

From source file:com.att.aro.diagnostics.GraphPanel.java

private static void populateNetworkTyesPlot(XYPlot plot, TraceData.Analysis analysis) {
    if (analysis != null) {

        final XYIntervalSeriesCollection networkDataSeries = new XYIntervalSeriesCollection();
        final Map<NetworkType, XYIntervalSeries> seriesMap = new EnumMap<NetworkType, XYIntervalSeries>(
                NetworkType.class);
        createDataSeriesForAllNetworkTypes(seriesMap, networkDataSeries);

        Iterator<NetworkBearerTypeInfo> iter = analysis.getNetworTypeInfos().iterator();
        if (iter.hasNext()) {
            while (iter.hasNext()) {
                NetworkBearerTypeInfo networkInfo = iter.next();
                if (networkInfo.getNetworkType() != NetworkType.none) {
                    seriesMap.get(networkInfo.getNetworkType()).add(networkInfo.getBeginTimestamp(),
                            networkInfo.getBeginTimestamp(), networkInfo.getEndTimestamp(), 0.5, 0, 1);
                }//from  w w w  .j  a  v a 2  s. c  om
            }
        } else {
            NetworkType nt = analysis.getTraceData().getNetworkType();
            if (nt != null && nt != NetworkType.none) {
                seriesMap.get(nt).add(0, 0, analysis.getTraceData().getTraceDuration(), 0.5, 0, 1);
            }
        }

        XYItemRenderer renderer = plot.getRenderer();
        setRenderingColorForDataSeries(renderer, networkDataSeries);

        // Assign ToolTip to renderer
        renderer.setBaseToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset dataset, int series, int item) {
                NetworkType networkType = (NetworkType) networkDataSeries.getSeries(series).getKey();
                return MessageFormat.format(rb.getString("network.tooltip"), dataset.getX(series, item),
                        ResourceBundleManager.getEnumString(networkType));
            }
        });

        plot.setDataset(networkDataSeries);

    } else {
        plot.setDataset(new XYIntervalSeriesCollection());
    }
}

From source file:sg.ncl.MainController.java

@RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST)
public String checkApplyTeamInfo(@Valid TeamPageApplyTeamForm teamPageApplyTeamForm,
        BindingResult bindingResult, HttpSession session, final RedirectAttributes redirectAttributes)
        throws WebServiceRuntimeException {

    final String LOG_PREFIX = "Existing user apply for new team: {}";

    if (bindingResult.hasErrors()) {
        log.warn(LOG_PREFIX, "Application form error " + teamPageApplyTeamForm.toString());
        return "team_page_apply_team";
    }// w ww. j  a  v a 2 s . com
    // log data to ensure data has been parsed
    log.debug(LOG_PREFIX, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString()));
    log.info(LOG_PREFIX, teamPageApplyTeamForm.toString());

    JSONObject mainObject = new JSONObject();
    JSONObject teamFields = new JSONObject();
    mainObject.put("team", teamFields);
    teamFields.put("name", teamPageApplyTeamForm.getTeamName());
    teamFields.put(DESCRIPTION, teamPageApplyTeamForm.getTeamDescription());
    teamFields.put(WEBSITE, teamPageApplyTeamForm.getTeamWebsite());
    teamFields.put(ORGANISATION_TYPE, teamPageApplyTeamForm.getTeamOrganizationType());
    teamFields.put(VISIBILITY, teamPageApplyTeamForm.getIsPublic());
    teamFields.put(IS_CLASS, teamPageApplyTeamForm.getIsClass());

    String nclUserId = session.getAttribute("id").toString();

    HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
    ResponseEntity response;

    try {
        response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST,
                request, String.class);
        String responseBody = response.getBody().toString();

        if (RestUtil.isError(response.getStatusCode())) {
            // prepare the exception mapping
            EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
            exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty ");
            exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty ");
            exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
            exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists");
            exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters");
            exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
            exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
            exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
            exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");

            MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
            ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());

            final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage()
                    : ERR_SERVER_OVERLOAD;

            log.warn(LOG_PREFIX, responseBody);
            redirectAttributes.addFlashAttribute(MESSAGE, errorMessage);
            return "redirect:/teams/apply_team";

        } else {
            // no errors, everything ok
            log.info(LOG_PREFIX, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted");
            return "redirect:/teams/team_application_submitted";
        }

    } catch (ResourceAccessException | IOException e) {
        log.error(LOG_PREFIX, e);
        throw new WebServiceRuntimeException(e.getMessage());
    }
}

From source file:sg.ncl.MainController.java

@RequestMapping(value = "/teams/join_team", method = RequestMethod.POST)
public String checkJoinTeamInfo(@Valid TeamPageJoinTeamForm teamPageJoinForm, BindingResult bindingResult,
        Model model, HttpSession session, final RedirectAttributes redirectAttributes)
        throws WebServiceRuntimeException {

    final String LOG_PREFIX = "Existing user join team: {}";

    if (bindingResult.hasErrors()) {
        log.warn(LOG_PREFIX, "Application form error " + teamPageJoinForm.toString());
        return "team_page_join_team";
    }/*w ww . j  a v a2  s  .  c om*/

    JSONObject mainObject = new JSONObject();
    JSONObject teamFields = new JSONObject();
    JSONObject userFields = new JSONObject();

    mainObject.put("team", teamFields);
    mainObject.put("user", userFields);

    userFields.put("id", session.getAttribute("id")); // ncl-id

    teamFields.put("name", teamPageJoinForm.getTeamName());

    log.info(LOG_PREFIX, USER_PREFIX + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName());

    HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString());
    ResponseEntity response;

    try {
        restTemplate.setErrorHandler(new MyResponseErrorHandler());
        response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request,
                String.class);
        String responseBody = response.getBody().toString();

        if (RestUtil.isError(response.getStatusCode())) {
            // prepare the exception mapping
            EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class);
            exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found");
            exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty");
            exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found");
            exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty");
            exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team");
            exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists");
            exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed");
            exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter");
            exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab");

            MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class);
            ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError());

            final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage()
                    : ERR_SERVER_OVERLOAD;

            log.warn(LOG_PREFIX, responseBody);
            redirectAttributes.addFlashAttribute(MESSAGE, errorMessage);
            return "redirect:/teams/join_team";

        } else {
            log.info(LOG_PREFIX, "Application for join team " + teamPageJoinForm.getTeamName() + " submitted");
            return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName();
        }

    } catch (ResourceAccessException | IOException e) {
        throw new WebServiceRuntimeException(e.getMessage());
    }
}

From source file:org.roda.core.index.utils.SolrUtils.java

private static Permissions getPermissions(SolrDocument doc) {
    Permissions permissions = new Permissions();

    EnumMap<PermissionType, Set<String>> userPermissions = new EnumMap<>(PermissionType.class);

    for (PermissionType type : PermissionType.values()) {
        String key = RodaConstants.INDEX_PERMISSION_USERS_PREFIX + type;
        Set<String> users = new HashSet<>();
        users.addAll(objectToListString(doc.get(key)));
        userPermissions.put(type, users);
    }/*from   w w  w  . j  a v  a 2 s  .co  m*/

    EnumMap<PermissionType, Set<String>> groupPermissions = new EnumMap<>(PermissionType.class);

    for (PermissionType type : PermissionType.values()) {
        String key = RodaConstants.INDEX_PERMISSION_GROUPS_PREFIX + type;
        Set<String> groups = new HashSet<>();
        groups.addAll(objectToListString(doc.get(key)));
        groupPermissions.put(type, groups);
    }

    permissions.setUsers(userPermissions);
    permissions.setGroups(groupPermissions);
    return permissions;
}

From source file:org.yccheok.jstock.gui.MainFrame.java

private void initStockInfoDatabaseMeta() {

    Runnable runnable = new Runnable() {
        @Override//from w  ww.  j a v  a 2s  .c om
        public void run() {
            // Read existing stock-info-database-meta.json
            final Map<Country, Long> localStockInfoDatabaseMeta = Utils
                    .loadStockInfoDatabaseMeta(Utils.getStockInfoDatabaseMetaFile());

            final String location = org.yccheok.jstock.network.Utils
                    .getURL(org.yccheok.jstock.network.Utils.Type.STOCK_INFO_DATABASE_META);

            final String json = Utils.downloadAsString(location);

            final Map<Country, Long> latestStockInfoDatabaseMeta = Utils.loadStockInfoDatabaseMeta(json);

            final Map<Country, Long> successStockInfoDatabaseMeta = new EnumMap<Country, Long>(Country.class);

            boolean needToInitDatabase = false;

            // Build up list of stock-info-database.csv that needed to be
            // updated.
            for (Map.Entry<Country, Long> entry : latestStockInfoDatabaseMeta.entrySet()) {
                if (Thread.currentThread().isInterrupted() || stockInfoDatabaseMetaPool == null) {
                    break;
                }

                Country country = entry.getKey();
                Long latest = entry.getValue();
                Long local = localStockInfoDatabaseMeta.get(country);

                if (false == latest.equals(local)) {
                    final String stocksCSVFileLocation = org.yccheok.jstock.engine.Utils
                            .getStocksCSVFileLocation(country);
                    final File file = Utils.downloadAsTempFile(stocksCSVFileLocation);
                    if (file != null) {
                        final java.util.List<Stock> stocks = org.yccheok.jstock.engine.Utils
                                .getStocksFromCSVFile(file);

                        if (false == stocks.isEmpty()) {
                            final Pair<StockInfoDatabase, StockNameDatabase> stockDatabase = org.yccheok.jstock.engine.Utils
                                    .toStockDatabase(stocks, country);
                            MainFrame.saveStockInfoDatabaseAsCSV(country, stockDatabase.first);
                            if (stockDatabase.second != null) {
                                MainFrame.saveStockNameDatabaseAsCSV(country, stockDatabase.second);
                            }
                            successStockInfoDatabaseMeta.put(country, latest);

                            if (country == jStockOptions.getCountry()) {
                                needToInitDatabase = true;
                            }
                        }
                    }
                }
            }

            if (successStockInfoDatabaseMeta.isEmpty()) {
                return;
            }

            // Retain old meta value.
            for (Map.Entry<Country, Long> entry : localStockInfoDatabaseMeta.entrySet()) {
                Country country = entry.getKey();
                Long old = entry.getValue();

                if (false == successStockInfoDatabaseMeta.containsKey(country)) {
                    successStockInfoDatabaseMeta.put(country, old);
                }
            }

            Utils.saveStockInfoDatabaseMeta(Utils.getStockInfoDatabaseMetaFile(), successStockInfoDatabaseMeta);

            if (needToInitDatabase) {
                initDatabase(true);
            }
        }
    };

    stockInfoDatabaseMetaPool.execute(runnable);
}