List of usage examples for com.google.common.collect ImmutableMap get
V get(Object key);
From source file:com.google.api.codegen.config.ResourceNameMessageConfigs.java
static ResourceNameMessageConfigs createMessageResourceTypesConfig(DiscoApiModel model, ConfigProto configProto, String defaultPackage) {/* w w w .j a va 2 s . co m*/ ImmutableMap.Builder<String, ResourceNameMessageConfig> builder = ImmutableMap.builder(); for (ResourceNameMessageConfigProto messageResourceTypesProto : configProto .getResourceNameGenerationList()) { ResourceNameMessageConfig messageResourceTypeConfig = ResourceNameMessageConfig .createResourceNameMessageConfig(model.getDiagCollector(), messageResourceTypesProto, defaultPackage); builder.put(messageResourceTypeConfig.messageName(), messageResourceTypeConfig); } ImmutableMap<String, ResourceNameMessageConfig> messageResourceTypeConfigMap = builder.build(); ListMultimap<String, FieldModel> fieldsByMessage = ArrayListMultimap.create(); DiscoGapicNamer discoGapicNamer = new DiscoGapicNamer(); for (Method method : model.getDocument().methods()) { String fullName = discoGapicNamer.getRequestMessageFullName(method, defaultPackage); ResourceNameMessageConfig messageConfig = messageResourceTypeConfigMap.get(fullName); if (messageConfig == null) { continue; } for (Schema property : method.parameters().values()) { if (messageConfig.getEntityNameForField(property.getIdentifier()) != null) { fieldsByMessage.put(fullName, DiscoveryField.create(property, model)); } } } return new AutoValue_ResourceNameMessageConfigs(messageResourceTypeConfigMap, fieldsByMessage); }
From source file:com.facebook.buck.cxx.toolchain.CxxPlatforms.java
/** Returns the configured default cxx platform. */ public static UnresolvedCxxPlatform getConfigDefaultCxxPlatform(CxxBuckConfig cxxBuckConfig, ImmutableMap<Flavor, UnresolvedCxxPlatform> cxxPlatformsMap, UnresolvedCxxPlatform systemDefaultCxxPlatform) { UnresolvedCxxPlatform defaultCxxPlatform; Optional<String> defaultPlatform = cxxBuckConfig.getDefaultPlatform(); if (defaultPlatform.isPresent()) { defaultCxxPlatform = cxxPlatformsMap.get(InternalFlavor.of(defaultPlatform.get())); if (defaultCxxPlatform == null) { LOG.info("Couldn't find default platform %s, falling back to system default", defaultPlatform.get()); } else {//from w w w. java 2 s .c o m LOG.debug("Using config default C++ platform %s", defaultCxxPlatform); return defaultCxxPlatform; } } else { LOG.debug("Using system default C++ platform %s", systemDefaultCxxPlatform); } return systemDefaultCxxPlatform; }
From source file:com.telefonica.iot.cygnus.management.MetricsHandlers.java
/** * Merges metrics from all the given sources and sinks. It is protected in order it can be tested. * @param sources//from w w w.j av a 2 s. com * @param sinks * @return */ protected static CygnusMetrics mergeMetrics(ImmutableMap<String, SourceRunner> sources, ImmutableMap<String, SinkRunner> sinks) { CygnusMetrics mergedMetrics = new CygnusMetrics(); if (sources != null) { for (String key : sources.keySet()) { Source source; HTTPSourceHandler handler; try { SourceRunner sr = sources.get(key); source = sr.getSource(); Field f = source.getClass().getDeclaredField("handler"); f.setAccessible(true); handler = (HTTPSourceHandler) f.get(source); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { LOGGER.error("There was a problem when getting a sink. Details: " + e.getMessage()); continue; } // try catch if (handler instanceof CygnusHandler) { CygnusHandler ch = (CygnusHandler) handler; CygnusMetrics sourceMetrics = ch.getServiceMetrics(); mergedMetrics.merge(sourceMetrics); } // if } // for } // if if (sinks != null) { for (String key : sinks.keySet()) { Sink sink; try { SinkRunner sr = sinks.get(key); SinkProcessor sp = sr.getPolicy(); Field f = sp.getClass().getDeclaredField("sink"); f.setAccessible(true); sink = (Sink) f.get(sp); } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) { LOGGER.error("There was a problem when getting a sink. Details: " + e.getMessage()); continue; } // try catch if (sink instanceof CygnusSink) { CygnusSink cs = (CygnusSink) sink; CygnusMetrics sinkMetrics = cs.getServiceMetrics(); mergedMetrics.merge(sinkMetrics); } // if } // for } // if return mergedMetrics; }
From source file:grakn.core.graql.gremlin.TraversalPlanner.java
private static void updateFixedCostSubsReachableByIndex(ImmutableMap<NodeId, Node> allNodes, Map<Node, Double> nodesWithFixedCost, Set<Fragment> fragments) { Set<Fragment> validSubFragments = fragments.stream().filter(fragment -> { if (fragment instanceof InSubFragment) { Node superType = allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.start())); if (nodesWithFixedCost.containsKey(superType) && nodesWithFixedCost.get(superType) > 0D) { Node subType = allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.end())); return !nodesWithFixedCost.containsKey(subType); }// w w w .java 2s .c o m } return false; }).collect(Collectors.toSet()); if (!validSubFragments.isEmpty()) { validSubFragments.forEach(fragment -> { // TODO: should decrease the weight of sub type after each level nodesWithFixedCost.put(allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.end())), nodesWithFixedCost.get(allNodes.get(NodeId.of(NodeId.Type.VAR, fragment.start())))); }); // recursively process all the sub fragments updateFixedCostSubsReachableByIndex(allNodes, nodesWithFixedCost, fragments); } }
From source file:com.spectralogic.ds3autogen.utils.ConverterUtil.java
/** * Gets a set of type names used within a list of Ds3Types *//*from w w w .j a va2 s. c o m*/ protected static ImmutableSet<String> getUsedTypesFromAllTypes(final ImmutableMap<String, Ds3Type> typeMap, final ImmutableSet<String> usedTypes) { if (isEmpty(usedTypes) || isEmpty(typeMap)) { return ImmutableSet.of(); } final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.addAll(usedTypes); for (final String type : usedTypes) { final Ds3Type ds3Type = typeMap.get(type); if (ds3Type != null) { builder.addAll(getUsedTypesFromType(ds3Type)); } else { //Log but do not throw an exception because there are cases where a type //doesn't need to be generated. Especially true during testing. LOG.error("Could not find used type in Type Map: " + type); } } final ImmutableSet<String> newUsedTypes = builder.build(); if (newUsedTypes.size() > usedTypes.size()) { return getUsedTypesFromAllTypes(typeMap, newUsedTypes); } return newUsedTypes; }
From source file:com.foudroyantfactotum.mod.fousarchive.midi.MidiDetails.java
public static MidiDetails fromMap(ImmutableMap<String, String> map) { final String[] elem = new String[tags.length + 1]; for (Map.Entry<String, String> entry : map.entrySet()) if (ctt.containsKey(entry.getKey())) elem[ctt.get(entry.getKey())] = entry.getValue(); if (elem[0] == null || elem[7] == null) return null; return new MidiDetails(elem, Long.parseLong(map.get("maxTicks"))); }
From source file:com.baasbox.controllers.Social.java
/** * Login the user through socialnetwork specified * // w ww. j a va 2 s.co m * An oauth_token and oauth_secret provided by oauth steps * are mandatory * @param socialNetwork the social network name (facebook,google) * @return 200 status code with the X-BB-SESSION token for further calls */ @With({ AdminCredentialWrapFilter.class, ConnectToDBFilter.class }) public static Result loginWith(String socialNetwork) { String appcode = (String) ctx().args.get("appcode"); //after this call, db connection is lost! SocialLoginService sc = SocialLoginService.by(socialNetwork, appcode); Token t = extractOAuthTokensFromRequest(request()); if (t == null) { return badRequest( String.format("Both %s and %s should be specified as query parameters or in the json body", OAUTH_TOKEN, OAUTH_SECRET)); } UserInfo result = null; try { if (sc.validationRequest(t.getToken())) { result = sc.getUserInfo(t); } else { return badRequest("Provided token is not valid"); } } catch (BaasBoxSocialException e1) { return badRequest(e1.getError()); } catch (BaasBoxSocialTokenValidationException e2) { return badRequest("Unable to validate provided token"); } if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("UserInfo received: " + result.toString()); result.setFrom(socialNetwork); result.setToken(t.getToken()); //Setting token as secret for one-token only social networks result.setSecret( t.getSecret() != null && StringUtils.isNotEmpty(t.getSecret()) ? t.getSecret() : t.getToken()); UserDao userDao = UserDao.getInstance(); ODocument existingUser = null; try { existingUser = userDao.getBySocialUserId(result); } catch (SqlInjectionException sie) { return internalServerError(ExceptionUtils.getMessage(sie)); } if (existingUser != null) { String username = null; try { username = UserService.getUsernameByProfile(existingUser); if (username == null) { throw new InvalidModelException("username for profile is null"); } } catch (InvalidModelException e) { internalServerError("unable to login with " + socialNetwork + " : " + ExceptionUtils.getMessage(e)); } String password = UserService.generateFakeUserPassword(username, (Date) existingUser.field(UserDao.USER_SIGNUP_DATE)); ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider .getSessionTokenProvider().setSession(appcode, username, password); response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN)); ObjectNode on = Json.newObject(); if (existingUser != null) { on = (ObjectNode) Json.parse(User.prepareResponseToJson(existingUser)); } on.put(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN)); return ok(on); } else { if (BaasBoxLogger.isDebugEnabled()) BaasBoxLogger.debug("User does not exists with tokens...trying to create"); String username = UUID.randomUUID().toString(); Date signupDate = new Date(); try { String password = UserService.generateFakeUserPassword(username, signupDate); JsonNode privateData = null; if (result.getAdditionalData() != null && !result.getAdditionalData().isEmpty()) { privateData = Json.toJson(result.getAdditionalData()); } UserService.signUp(username, password, signupDate, null, privateData, null, null, true); ODocument profile = UserService.getUserProfilebyUsername(username); UserService.addSocialLoginTokens(profile, result); ImmutableMap<SessionKeys, ? extends Object> sessionObject = SessionTokenProvider .getSessionTokenProvider().setSession(appcode, username, password); response().setHeader(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN)); ObjectNode on = Json.newObject(); if (profile != null) { on = (ObjectNode) Json.parse(User.prepareResponseToJson(profile)); } on.put(SessionKeys.TOKEN.toString(), (String) sessionObject.get(SessionKeys.TOKEN)); return ok(on); } catch (Exception uaee) { return internalServerError(ExceptionUtils.getMessage(uaee)); } } }
From source file:eu.eidas.auth.commons.EIDASUtil.java
/** * Returns the identifier of some configuration given a set of configurations and the corresponding configuration * key.// w ww . ja v a 2s .com * * @param configKey The key that IDs some configuration. * @return The configuration String value. */ @Nullable public static String getConfig(@Nullable String configKey) { Preconditions.checkNotNull(configKey, "configKey"); ImmutableMap<String, String> properties = INSTANCE.getProperties(); final String propertyValue; if (properties.isEmpty()) { LOG.warn("BUSINESS EXCEPTION : Configs not loaded - property-Key value is null or empty {} ", configKey); propertyValue = configKey; } else { propertyValue = properties.get(configKey); if (StringUtils.isEmpty(propertyValue)) { LOG.warn("BUSINESS EXCEPTION : Invalid property-Key value is null or empty {}", configKey); } } return propertyValue; }
From source file:it.unibz.krdb.obda.owlrefplatform.core.dagjgrapht.EquivalencesDAGImpl.java
public static <TT> EquivalencesDAGImpl<TT> getEquivalencesDAG(DefaultDirectedGraph<TT, DefaultEdge> graph) { // each set contains vertices which together form a strongly connected // component within the given graph GabowSCC<TT, DefaultEdge> inspector = new GabowSCC<>(graph); List<Equivalences<TT>> equivalenceSets = inspector.stronglyConnectedSets(); // create the vertex index ImmutableMap.Builder<TT, Equivalences<TT>> vertexIndexBuilder = new ImmutableMap.Builder<>(); for (Equivalences<TT> equivalenceSet : equivalenceSets) { for (TT node : equivalenceSet) vertexIndexBuilder.put(node, equivalenceSet); }//from w w w. ja va 2 s .c o m ImmutableMap<TT, Equivalences<TT>> vertexIndex = vertexIndexBuilder.build(); // compute the edges between the SCCs Map<Equivalences<TT>, Set<Equivalences<TT>>> outgoingEdges = new HashMap<>(); for (DefaultEdge edge : graph.edgeSet()) { Equivalences<TT> v1 = vertexIndex.get(graph.getEdgeSource(edge)); Equivalences<TT> v2 = vertexIndex.get(graph.getEdgeTarget(edge)); if (v1 == v2) continue; // do not add loops Set<Equivalences<TT>> out = outgoingEdges.get(v1); if (out == null) { out = new HashSet<>(); outgoingEdges.put(v1, out); } out.add(v2); } // compute the transitively reduced DAG SimpleDirectedGraph<Equivalences<TT>, DefaultEdge> dag = new SimpleDirectedGraph<>(DefaultEdge.class); for (Equivalences<TT> equivalenceSet : equivalenceSets) dag.addVertex(equivalenceSet); for (Map.Entry<Equivalences<TT>, Set<Equivalences<TT>>> edges : outgoingEdges.entrySet()) { Equivalences<TT> v1 = edges.getKey(); for (Equivalences<TT> v2 : edges.getValue()) { // an edge from v1 to v2 is redundant if // v1 has an edge going to a vertex v2p // from which v2 is reachable (in one step) boolean redundant = false; if (edges.getValue().size() > 1) { for (Equivalences<TT> v2p : edges.getValue()) { Set<Equivalences<TT>> t2p = outgoingEdges.get(v2p); if (t2p != null && t2p.contains(v2)) { redundant = true; break; } } } if (!redundant) dag.addEdge(v1, v2); } } return new EquivalencesDAGImpl<TT>(graph, dag, vertexIndex, vertexIndex); }
From source file:com.facebook.buck.core.cell.impl.DefaultCellPathResolver.java
/** * Helper function to precompute the {@link CellName} to Path mapping * * @return Map of cell name to path.// w w w.ja v a2s. com */ private static ImmutableMap<CellName, Path> bootstrapPathMapping(Path root, ImmutableMap<String, Path> cellPaths) { ImmutableMap.Builder<CellName, Path> builder = ImmutableMap.builder(); // Add the implicit empty root cell builder.put(CellName.ROOT_CELL_NAME, root); HashSet<Path> seenPaths = new HashSet<>(); ImmutableSortedSet<String> sortedCellNames = ImmutableSortedSet.<String>naturalOrder() .addAll(cellPaths.keySet()).build(); for (String cellName : sortedCellNames) { Path cellRoot = Objects.requireNonNull(cellPaths.get(cellName), "cellName is derived from the map, get() should always return a value."); try { cellRoot = cellRoot.toRealPath().normalize(); } catch (IOException e) { LOG.warn("cellroot [" + cellRoot + "] does not exist in filesystem"); } if (seenPaths.contains(cellRoot)) { continue; } builder.put(CellName.of(cellName), cellRoot); seenPaths.add(cellRoot); } return builder.build(); }