List of usage examples for java.util EnumMap EnumMap
public EnumMap(Map<K, ? extends V> m)
From source file:eu.itesla_project.online.tools.RunImpactAnalysisOnStateTool.java
@Override public void run(CommandLine line) throws Exception { String workflowId = line.getOptionValue("workflow"); Integer stateId = Integer.valueOf(line.getOptionValue("state")); Set<String> contingencyIds = null; if (line.hasOption("contingencies")) { contingencyIds = Sets.newHashSet(line.getOptionValue("contingencies").split(",")); }/* ww w. java 2s .c o m*/ System.out.println("loading state " + stateId + " of workflow " + workflowId + " from the online db ..."); OnlineConfig config = OnlineConfig.load(); OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create(); // load the network Network network = onlinedb.getState(workflowId, stateId); if (network != null) { ComputationManager computationManager = new LocalComputationManager(); ContingenciesAndActionsDatabaseClient contingencyDb = config.getContingencyDbClientFactoryClass() .newInstance().create(); SimulatorFactory simulatorFactory = config.getSimulatorFactoryClass().newInstance(); Stabilization stabilization = simulatorFactory.createStabilization(network, computationManager, 0); ImpactAnalysis impactAnalysis = simulatorFactory.createImpactAnalysis(network, computationManager, 0, contingencyDb); Map<String, Object> initContext = new HashMap<>(); SimulationParameters simulationParameters = SimulationParameters.load(); stabilization.init(simulationParameters, initContext); impactAnalysis.init(simulationParameters, initContext); System.out.println("running stabilization simulation..."); StabilizationResult sr = stabilization.run(); System.out.println("stabilization status: " + sr.getStatus()); if (sr.getStatus() == StabilizationStatus.COMPLETED) { System.out.println("running impact analysis..."); ImpactAnalysisResult iar = impactAnalysis.run(sr.getState(), contingencyIds); Table table = new Table(1 + SecurityIndexType.values().length, BorderStyle.CLASSIC_WIDE); table.addCell("Contingency"); for (SecurityIndexType securityIndexType : SecurityIndexType.values()) { table.addCell(securityIndexType.toString()); } Multimap<String, SecurityIndex> securityIndexesPerContingency = Multimaps .index(iar.getSecurityIndexes(), new Function<SecurityIndex, String>() { @Override public String apply(SecurityIndex securityIndex) { return securityIndex.getId().getContingencyId(); } }); for (Map.Entry<String, Collection<SecurityIndex>> entry : securityIndexesPerContingency.asMap() .entrySet()) { String contingencyId = entry.getKey(); table.addCell(contingencyId); Map<SecurityIndexType, Boolean> ok = new EnumMap<>(SecurityIndexType.class); for (SecurityIndex securityIndex : entry.getValue()) { ok.put(securityIndex.getId().getSecurityIndexType(), securityIndex.isOk()); } for (SecurityIndexType securityIndexType : SecurityIndexType.values()) { Boolean b = ok.get(securityIndexType); String str; if (b == null) { str = "NA"; } else { str = b ? "OK" : "NOK"; } table.addCell(str); } } System.out.println(table.render()); } else { System.out.println("Error running stabilization - metrics = " + sr.getMetrics()); } } else { System.out.println("no state " + stateId + " of workflow " + workflowId + " stored in the online db"); } onlinedb.close(); }
From source file:fr.free.movierenamer.scrapper.impl.movie.TracktScrapper.java
@Override protected MovieInfo fetchMediaInfo(Movie searchResult, IdInfo id, AvailableLanguages language) throws Exception { URL searchUrl = new URL("http", apiHost, "/movie/summary.json/" + apikey + "/" + id); JSONObject json = URIRequest.getJsonDocument(searchUrl.toURI()); final Map<MediaInfo.MediaProperty, String> mediaFields = new EnumMap<MediaInfo.MediaProperty, String>( MediaInfo.MediaProperty.class); Map<MovieInfo.MovieProperty, String> fields = new EnumMap<MovieInfo.MovieProperty, String>( MovieInfo.MovieProperty.class); Map<MovieInfo.MovieMultipleProperty, List<String>> multipleFields = new EnumMap<MovieInfo.MovieMultipleProperty, List<String>>( MovieInfo.MovieMultipleProperty.class); mediaFields.put(MediaInfo.MediaProperty.title, JSONUtils.selectString("title", json)); String syear = JSONUtils.selectString("year", json); if (syear != null && !syear.isEmpty()) { fields.put(MovieInfo.MovieProperty.releasedDate, syear); mediaFields.put(MediaInfo.MediaProperty.year, syear); }//w w w. j a v a2 s . c o m fields.put(MovieInfo.MovieProperty.overview, JSONUtils.selectString("overview", json)); fields.put(MovieInfo.MovieProperty.runtime, JSONUtils.selectString("runtime", json)); fields.put(MovieInfo.MovieProperty.tagline, JSONUtils.selectString("tagline", json)); fields.put(MovieInfo.MovieProperty.certificationCode, JSONUtils.selectString("certification", json)); JSONObject jsrate = JSONUtils.selectObject("ratings", json); if (jsrate != null) { String rate = JSONUtils.selectString("percentage", jsrate); if (rate != null && !rate.equals("")) { Double rating = Double.parseDouble(rate) / 10; mediaFields.put(MediaInfo.MediaProperty.rating, "" + rating); } Integer votes = JSONUtils.selectInteger("votes", jsrate); if (votes != null) { fields.put(MovieInfo.MovieProperty.votes, "" + votes); } } List<String> genres = new ArrayList<String>(); String jgenres = JSONUtils.selectString("genres", json); if (jgenres != null && !jgenres.isEmpty()) { genres = Arrays.asList(StringUtils.fromString(jgenres)); } multipleFields.put(MovieInfo.MovieMultipleProperty.genres, genres); List<IdInfo> ids = new ArrayList<IdInfo>(); addId(ids, json, "imdb_id", ScrapperUtils.AvailableApiIds.IMDB); addId(ids, json, "tmdb_id", ScrapperUtils.AvailableApiIds.THEMOVIEDB); addId(ids, json, "rt_id", ScrapperUtils.AvailableApiIds.ROTTENTOMATOES); MovieInfo movieInfo = new MovieInfo(mediaFields, ids, fields, multipleFields); return movieInfo; }
From source file:eu.itesla_project.online.tools.RunSecurityRulesOnStateTool.java
@Override public void run(CommandLine line) throws Exception { String workflowId = line.getOptionValue("workflow"); Integer stateId = Integer.valueOf(line.getOptionValue("state")); System.out.println("loading state " + stateId + " of workflow " + workflowId + " from the online db ..."); OnlineConfig config = OnlineConfig.load(); OnlineDb onlinedb = config.getOnlineDbFactoryClass().newInstance().create(); // load the network Network network = onlinedb.getState(workflowId, stateId); if (network != null) { OnlineWorkflowParameters parameters = onlinedb.getWorkflowParameters(workflowId); String offlineWorkflowId = parameters.getOfflineWorkflowId(); if (line.hasOption("offline-workflow")) offlineWorkflowId = line.getOptionValue("offline-workflow"); System.out.println("checking state " + stateId + " of workflow " + workflowId + " against rules of offline workflow " + offlineWorkflowId + " ..."); RulesDbClient rulesDb = config.getRulesDbClientFactoryClass().newInstance().create("rulesdb"); RuleAttributeSet attributeSet = RuleAttributeSet.MONTE_CARLO; if (line.hasOption("wca")) attributeSet = RuleAttributeSet.WORST_CASE; double purityThreshold = parameters.getRulesPurityThreshold(); // get rules from db Collection<RuleId> ruleIds = rulesDb.listRules(offlineWorkflowId, attributeSet); // TODO filter rules that does not apply to the network // .../* w w w. j a va 2s. co m*/ // sort rules per contingency Multimap<String, RuleId> ruleIdsPerContingency = Multimaps.index(ruleIds, new Function<RuleId, String>() { @Override public String apply(RuleId ruleId) { return ruleId.getSecurityIndexId().getContingencyId(); } }); Map<HistoDbAttributeId, Object> values = IIDM2DB .extractCimValues(network, new IIDM2DB.Config(null, false)).getSingleValueMap(); SecurityIndexType[] securityIndexTypes = parameters.getSecurityIndexes() == null ? SecurityIndexType.values() : parameters.getSecurityIndexes() .toArray(new SecurityIndexType[parameters.getSecurityIndexes().size()]); Table table = new Table(1 + securityIndexTypes.length, BorderStyle.CLASSIC_WIDE); table.addCell("Contingency"); for (SecurityIndexType securityIndexType : securityIndexTypes) { table.addCell(securityIndexType.toString()); } // check rules for (Map.Entry<String, Collection<RuleId>> entry : ruleIdsPerContingency.asMap().entrySet()) { String contingencyId = entry.getKey(); table.addCell(contingencyId); Map<SecurityIndexType, CheckStatus> checkStatus = new EnumMap<>(SecurityIndexType.class); for (SecurityIndexType securityIndexType : securityIndexTypes) { checkStatus.put(securityIndexType, CheckStatus.NA); } for (RuleId ruleId : entry.getValue()) { List<SecurityRule> rules = rulesDb.getRules(offlineWorkflowId, attributeSet, contingencyId, ruleId.getSecurityIndexId().getSecurityIndexType()); if (rules.size() > 0) { SecurityRule rule = rules.get(0); SecurityRuleExpression securityRuleExpression = rule.toExpression(purityThreshold); boolean ok = securityRuleExpression.check(values).isSafe(); checkStatus.put(rule.getId().getSecurityIndexId().getSecurityIndexType(), ok ? CheckStatus.OK : CheckStatus.NOK); } } for (SecurityIndexType securityIndexType : securityIndexTypes) { table.addCell(checkStatus.get(securityIndexType).name()); } } System.out.println(table.render()); } else { System.out.println("no state " + stateId + " of workflow " + workflowId + " stored in the online db"); } onlinedb.close(); }
From source file:org.janusgraph.graphdb.database.log.TransactionLogHeader.java
private DataOutput serializeHeader(Serializer serializer, int capacity, LogTxStatus status, TransactionConfiguration txConfig) { EnumMap<LogTxMeta, Object> metaMap = new EnumMap<LogTxMeta, Object>(LogTxMeta.class); if (txConfig != null) { for (LogTxMeta meta : LogTxMeta.values()) { Object value = meta.getValue(txConfig); if (value != null) { metaMap.put(meta, value); }/* w ww .j av a 2 s. com*/ } } return serializeHeader(serializer, capacity, status, metaMap); }
From source file:org.jodconverter.document.DocumentFormat.java
/** * Creates a new read-only document format with the specified name, extension and mime-type. * * @param name The name of the format./*from w w w .ja va2s .com*/ * @param extensions The file name extensions of the format. * @param mediaType The media type (mime type) of the format. * @param inputFamily The DocumentFamily of the document. * @param loadProperties The properties required to load(open) a document of this format. * @param storeProperties The properties required to store(save) a document of this format to a * document of another family. * @param unmodifiable {@code true} if the created document format cannot be modified after * creation, {@code false} otherwise. */ private DocumentFormat(final String name, final Collection<String> extensions, final String mediaType, final DocumentFamily inputFamily, final Map<String, Object> loadProperties, final Map<DocumentFamily, Map<String, Object>> storeProperties, final boolean unmodifiable) { this.name = name; this.extensions = new ArrayList<>(extensions); this.mediaType = mediaType; this.inputFamily = inputFamily; this.loadProperties = Optional.ofNullable(loadProperties) // Create a copy of the map. .map(HashMap<String, Object>::new) // Make the map read only if required. .map(mapCopy -> unmodifiable ? Collections.unmodifiableMap(mapCopy) : mapCopy).orElse(null); this.storeProperties = Optional.ofNullable(storeProperties) // Create a copy of the map. .map(map -> { final EnumMap<DocumentFamily, Map<String, Object>> familyMap = new EnumMap<>( DocumentFamily.class); map.forEach((family, propMap) -> familyMap.put(family, unmodifiable ? Collections.unmodifiableMap(new HashMap<>(propMap)) : new HashMap<>(propMap))); return familyMap; }) // Make the map read only if required. .map(mapCopy -> unmodifiable ? Collections.unmodifiableMap(mapCopy) : mapCopy).orElse(null); }
From source file:fr.free.movierenamer.scrapper.impl.trailer.VideoDetectiveScrapper.java
@Override protected TrailerInfo fetchTrailerInfo(Trailer searchResult) throws Exception { URL url = searchResult.getTrailerUrl(); Matcher matcher = idPattern.matcher(url.toExternalForm()); if (!matcher.find()) { throw new Exception("No id found for " + searchResult); }//from w w w. ja va 2s . c o m Map<TrailerProperty, String> info = new EnumMap<TrailerProperty, String>(TrailerProperty.class); Map<Quality, URL> streams = new EnumMap<Quality, URL>(Quality.class); String id = matcher.group(1); String urlStr = String.format(infoUrl, cusomerId, id); URL uri = new URL(urlStr); JSONObject json = URIRequest.getJsonDocument(uri.toURI()); List<JSONObject> pnodes = JSONUtils.selectList("playlist", json); info.put(TrailerProperty.title, searchResult.getName()); info.put(TrailerProperty.provider, searchResult.getProviderName()); info.put(TrailerProperty.runtime, searchResult.getRuntime()); info.put(TrailerProperty.overview, JSONUtils.selectString("description", pnodes.get(0))); List<JSONObject> nodes = JSONUtils.selectList("sources", pnodes.get(0)); for (JSONObject node : nodes) { String label = JSONUtils.selectString("label", node); if (label != null) { Bitrate bt; try { bt = Bitrate.valueOf("B_" + (label.replace(" ", "_"))); } catch (Exception ex) { continue; } if (streams.containsKey(bt.getQuality())) { continue; } streams.put(bt.getQuality(), new URL(JSONUtils.selectString("file", node))); } } return new TrailerInfo(info, streams, searchResult.getLang()); }
From source file:org.matsim.contrib.dvrp.util.chart.RouteCharts.java
private static Map<TaskStatus, CoordSource> createLinkSourceByStatus(Schedule schedule) { Stream<DriveTask> tasks = Schedules.driveTasks(schedule); // creating lists of DriveTasks Map<TaskStatus, List<DriveTask>> taskListByStatus = tasks .collect(Collectors.groupingBy(t -> t.getStatus())); // creating LinkSources Map<TaskStatus, CoordSource> linkSourceByStatus = new EnumMap<>(TaskStatus.class); for (TaskStatus ts : TaskStatus.values()) { linkSourceByStatus.put(ts, ScheduleCoordSources.createCoordSource(taskListByStatus.get(ts))); }/*from ww w . ja v a 2 s . c om*/ return linkSourceByStatus; }
From source file:edu.cornell.mannlib.vitro.webapp.modelaccess.impl.ContextModelAccessImpl.java
private Map<WhichService, Dataset> populateDatasetMap() { Map<WhichService, Dataset> map = new EnumMap<>(WhichService.class); map.put(CONTENT, factory.getDataset(CONTENT)); map.put(CONFIGURATION, factory.getDataset(CONFIGURATION)); log.debug("DatasetMap: " + map); return Collections.unmodifiableMap(map); }
From source file:org.structr.core.entity.SchemaNode.java
@Override public String getSource(final ErrorBuffer errorBuffer) throws FrameworkException { final Collection<StructrModule> modules = StructrApp.getConfiguration().getModules().values(); final App app = StructrApp.getInstance(securityContext); final Map<Actions.Type, List<ActionEntry>> saveActions = new EnumMap<>(Actions.Type.class); final Map<String, Set<String>> viewProperties = new LinkedHashMap<>(); final Set<String> existingPropertyNames = new LinkedHashSet<>(); final Set<String> propertyNames = new LinkedHashSet<>(); final Set<Validator> validators = new LinkedHashSet<>(); final Set<String> enums = new LinkedHashSet<>(); final StringBuilder src = new StringBuilder(); final Class baseType = AbstractNode.class; final String _className = getProperty(name); final String _extendsClass = getProperty(extendsClass); final String superClass = _extendsClass != null ? _extendsClass : baseType.getSimpleName(); src.append("package org.structr.dynamic;\n\n"); SchemaHelper.formatImportStatements(this, src, baseType); src.append("public class "); src.append(_className);//from w ww . j av a 2 s. c o m src.append(" extends "); src.append(superClass); SchemaHelper.formatInterfacesFromModules(src, this); src.append(" {\n\n"); // migrate schema relationships for (final SchemaRelationship outRel : getOutgoingRelationships(SchemaRelationship.class)) { final PropertyMap relNodeProperties = new PropertyMap(); relNodeProperties.put(SchemaRelationshipNode.sourceNode, outRel.getSourceNode()); relNodeProperties.put(SchemaRelationshipNode.targetNode, outRel.getTargetNode()); relNodeProperties.put(SchemaRelationshipNode.name, outRel.getProperty(SchemaRelationship.name)); relNodeProperties.put(SchemaRelationshipNode.sourceNotion, outRel.getProperty(SchemaRelationship.sourceNotion)); relNodeProperties.put(SchemaRelationshipNode.targetNotion, outRel.getProperty(SchemaRelationship.targetNotion)); relNodeProperties.put(SchemaRelationshipNode.extendsClass, outRel.getProperty(SchemaRelationship.extendsClass)); relNodeProperties.put(SchemaRelationshipNode.cascadingDeleteFlag, outRel.getProperty(SchemaRelationship.cascadingDeleteFlag)); relNodeProperties.put(SchemaRelationshipNode.autocreationFlag, outRel.getProperty(SchemaRelationship.autocreationFlag)); relNodeProperties.put(SchemaRelationshipNode.relationshipType, outRel.getProperty(SchemaRelationship.relationshipType)); relNodeProperties.put(SchemaRelationshipNode.sourceMultiplicity, outRel.getProperty(SchemaRelationship.sourceMultiplicity)); relNodeProperties.put(SchemaRelationshipNode.targetMultiplicity, outRel.getProperty(SchemaRelationship.targetMultiplicity)); relNodeProperties.put(SchemaRelationshipNode.sourceJsonName, outRel.getProperty(SchemaRelationship.sourceJsonName)); relNodeProperties.put(SchemaRelationshipNode.targetJsonName, outRel.getProperty(SchemaRelationship.targetJsonName)); app.create(SchemaRelationshipNode.class, relNodeProperties); app.delete(outRel); } for (final SchemaRelationship inRel : getIncomingRelationships(SchemaRelationship.class)) { final PropertyMap relNodeProperties = new PropertyMap(); relNodeProperties.put(SchemaRelationshipNode.sourceNode, inRel.getSourceNode()); relNodeProperties.put(SchemaRelationshipNode.targetNode, inRel.getTargetNode()); relNodeProperties.put(SchemaRelationshipNode.name, inRel.getProperty(SchemaRelationship.name)); relNodeProperties.put(SchemaRelationshipNode.sourceNotion, inRel.getProperty(SchemaRelationship.sourceNotion)); relNodeProperties.put(SchemaRelationshipNode.targetNotion, inRel.getProperty(SchemaRelationship.targetNotion)); relNodeProperties.put(SchemaRelationshipNode.extendsClass, inRel.getProperty(SchemaRelationship.extendsClass)); relNodeProperties.put(SchemaRelationshipNode.cascadingDeleteFlag, inRel.getProperty(SchemaRelationship.cascadingDeleteFlag)); relNodeProperties.put(SchemaRelationshipNode.autocreationFlag, inRel.getProperty(SchemaRelationship.autocreationFlag)); relNodeProperties.put(SchemaRelationshipNode.relationshipType, inRel.getProperty(SchemaRelationship.relationshipType)); relNodeProperties.put(SchemaRelationshipNode.sourceMultiplicity, inRel.getProperty(SchemaRelationship.sourceMultiplicity)); relNodeProperties.put(SchemaRelationshipNode.targetMultiplicity, inRel.getProperty(SchemaRelationship.targetMultiplicity)); relNodeProperties.put(SchemaRelationshipNode.sourceJsonName, inRel.getProperty(SchemaRelationship.sourceJsonName)); relNodeProperties.put(SchemaRelationshipNode.targetJsonName, inRel.getProperty(SchemaRelationship.targetJsonName)); app.create(SchemaRelationshipNode.class, relNodeProperties); app.delete(inRel); } // output related node definitions, collect property views for (final SchemaRelationshipNode outRel : getProperty(SchemaNode.relatedTo)) { final String propertyName = outRel.getPropertyName(_className, existingPropertyNames, true); //outRel.setProperty(SchemaRelationship.targetJsonName, propertyName); src.append(outRel.getPropertySource(propertyName, true)); //existingPropertyNames.clear(); addPropertyNameToViews(propertyName, viewProperties); } // output related node definitions, collect property views for (final SchemaRelationshipNode inRel : getProperty(SchemaNode.relatedFrom)) { final String propertyName = inRel.getPropertyName(_className, existingPropertyNames, false); //inRel.setProperty(SchemaRelationship.sourceJsonName, propertyName); src.append(inRel.getPropertySource(propertyName, false)); //existingPropertyNames.clear(); addPropertyNameToViews(propertyName, viewProperties); } // extract properties from node src.append(SchemaHelper.extractProperties(this, propertyNames, validators, enums, viewProperties, errorBuffer)); src.append(SchemaHelper.extractViews(this, viewProperties, errorBuffer)); src.append(SchemaHelper.extractMethods(this, saveActions)); // output possible enum definitions for (final String enumDefition : enums) { src.append(enumDefition); } for (Entry<String, Set<String>> entry : viewProperties.entrySet()) { final String viewName = entry.getKey(); final Set<String> view = entry.getValue(); if (!view.isEmpty()) { dynamicViews.add(viewName); SchemaHelper.formatView(src, _className, viewName, viewName, view); } } if (getProperty(defaultSortKey) != null) { String order = getProperty(defaultSortOrder); if (order == null || "desc".equals(order)) { order = "GraphObjectComparator.DESCENDING"; } else { order = "GraphObjectComparator.ASCENDING"; } src.append("\n\t@Override\n"); src.append("\tpublic PropertyKey getDefaultSortKey() {\n"); src.append("\t\treturn ").append(getProperty(defaultSortKey)).append("Property;\n"); src.append("\t}\n"); src.append("\n\t@Override\n"); src.append("\tpublic String getDefaultSortOrder() {\n"); src.append("\t\treturn ").append(order).append(";\n"); src.append("\t}\n"); } SchemaHelper.formatValidators(src, validators); SchemaHelper.formatSaveActions(this, src, saveActions); // insert source code from module for (final StructrModule module : modules) { src.append("\n\n// ----- dynamic code inserted by "); src.append(module.getName()); src.append(" -----\n"); module.insertSourceCode(this, src); } src.append("}\n"); return src.toString(); }
From source file:nl.strohalm.cyclos.controls.groups.EditGroupAction.java
public DataBinder<? extends Group> getDataBinder(final Group.Nature nature) { if (dataBinders == null) { dataBinders = new EnumMap<Group.Nature, DataBinder<? extends Group>>(Group.Nature.class); final BeanBinder<BasicGroupSettings> basicSettingsBinder = BeanBinder.instance(BasicGroupSettings.class, "basicSettings"); final BeanBinder<MemberGroupSettings> memberSettingsBinder = BeanBinder .instance(MemberGroupSettings.class, "memberSettings"); final BeanBinder<AdminGroup> adminGroupBinder = BeanBinder.instance(AdminGroup.class); initBasic(adminGroupBinder, basicSettingsBinder); initSystem(adminGroupBinder);/* ww w. j a v a 2 s.co m*/ dataBinders.put(Group.Nature.ADMIN, adminGroupBinder); final BeanBinder<MemberGroup> memberGroupBinder = BeanBinder.instance(MemberGroup.class); initBasic(memberGroupBinder, basicSettingsBinder); initSystem(memberGroupBinder); initMember(memberGroupBinder, memberSettingsBinder); dataBinders.put(Group.Nature.MEMBER, memberGroupBinder); final BeanBinder<OperatorGroup> operatorGroupBinder = BeanBinder.instance(OperatorGroup.class); initBasic(operatorGroupBinder, basicSettingsBinder); initOperator(operatorGroupBinder); dataBinders.put(Group.Nature.OPERATOR, operatorGroupBinder); final BeanBinder<BrokerGroup> brokerGroupBinder = BeanBinder.instance(BrokerGroup.class); initBasic(brokerGroupBinder, basicSettingsBinder); initSystem(brokerGroupBinder); initMember(brokerGroupBinder, memberSettingsBinder); initBroker(brokerGroupBinder); dataBinders.put(Group.Nature.BROKER, brokerGroupBinder); } return dataBinders.get(nature); }