public RequestDispatcher(Iterable<GrizzletHandler> grizzlets) {
   Map<String, Map<HttpMethod, GrizzletHandler>> modifiableHandlersMap = Maps.newHashMap();
   for (GrizzletHandler handler : grizzlets) {
     Map<HttpMethod, GrizzletHandler> handlerByMethod =
         modifiableHandlersMap.get(handler.getPath());
     if (handlerByMethod == null) {
       handlerByMethod = Maps.newEnumMap(HttpMethod.class);
       modifiableHandlersMap.put(handler.getPath(), handlerByMethod);
     }
     for (HttpMethod method : handler.getMethods()) {
       GrizzletHandler alreadyHandler = handlerByMethod.put(method, handler);
       if (alreadyHandler != null) {
         throw new IllegalArgumentException(
             "More than one handler detected for path='"
                 + handler.getPath()
                 + "', method='"
                 + method.name()
                 + '\'');
       }
     }
   }
   for (Map.Entry<String, Map<HttpMethod, GrizzletHandler>> entry :
       modifiableHandlersMap.entrySet()) {
     modifiableHandlersMap.put(entry.getKey(), Collections.unmodifiableMap(entry.getValue()));
   }
   handlers = ImmutableMap.copyOf(modifiableHandlersMap);
 }
final class TravelModes {

  static final BiMap<TravelMode, String> TRAVEL_MODE_IDS = HashBiMap.create();
  static final BiMap<TravelMode, String> TRAVEL_MODES = HashBiMap.create();
  static final Map<TravelMode, String> ROUTE_DESCRIPTIONS = Maps.newHashMap();
  static final Map<TravelMode, String> SUBROUTE_DESCRIPTIONS = Maps.newHashMap();

  static {
    TRAVEL_MODE_IDS.put(TravelMode.BICYCLING, "bicycling");
    TRAVEL_MODE_IDS.put(TravelMode.CAR, "car");
    TRAVEL_MODE_IDS.put(TravelMode.PUBLIC_TRANSIT, "publicTransit");
    TRAVEL_MODE_IDS.put(TravelMode.WALKING, "walking");

    TRAVEL_MODES.put(TravelMode.BICYCLING, "bicycling");
    TRAVEL_MODES.put(TravelMode.CAR, "driving");
    TRAVEL_MODES.put(TravelMode.PUBLIC_TRANSIT, "transit");
    TRAVEL_MODES.put(TravelMode.WALKING, "walking");

    ROUTE_DESCRIPTIONS.put(TravelMode.BICYCLING, "by bicycle");
    ROUTE_DESCRIPTIONS.put(TravelMode.CAR, "by car");
    ROUTE_DESCRIPTIONS.put(TravelMode.PUBLIC_TRANSIT, "by public transit");
    ROUTE_DESCRIPTIONS.put(TravelMode.WALKING, "walking");

    SUBROUTE_DESCRIPTIONS.put(TravelMode.BICYCLING, "Bicycling");
    SUBROUTE_DESCRIPTIONS.put(TravelMode.CAR, "Car");
    SUBROUTE_DESCRIPTIONS.put(TravelMode.PUBLIC_TRANSIT, "Public transit");
    SUBROUTE_DESCRIPTIONS.put(TravelMode.WALKING, "Walking");
  }
}
  public Configuration(Map<String, Object> m) {
    this.source = m;

    strings = Maps.newHashMap();
    ints = Maps.newHashMap();
    bools = Maps.newHashMap();

    if (m != null) {
      for (Map.Entry<String, Object> e : m.entrySet()) {
        try {
          if (e.getValue() instanceof String) {
            strings.put(e.getKey(), (String) e.getValue());
          } else if (e.getValue() instanceof Integer) {
            ints.put(e.getKey(), (Integer) e.getValue());
          } else if (e.getValue() instanceof Long) {
            ints.put(
                e.getKey(),
                ((Long) e.getValue())
                    .intValue()); // We only support integers but MongoDB likes to return longs.
          } else if (e.getValue() instanceof Double) {
            ints.put(e.getKey(), ((Double) e.getValue()).intValue()); // same as for longs lol
          } else if (e.getValue() instanceof Boolean) {
            bools.put(e.getKey(), (Boolean) e.getValue());
          } else {
            LOG.error(
                "Cannot handle type [{}] of plugin configuration key <{}>.",
                e.getValue().getClass().getCanonicalName(),
                e.getKey());
          }
        } catch (Exception ex) {
          LOG.warn("Could not read input configuration key <" + e.getKey() + ">. Skipping.", ex);
        }
      }
    }
  }
 @Override
 public Map<Set<Entry<String, String>>, Map<String, String>> getAllOptions() {
   return Maps.filterValues(
       Maps.transformValues(
           segments, dataEntry -> dataEntry == null ? null : dataEntry.getOptions()),
       el -> el != null);
 }
 @Override
 public Map<Set<Entry<String, String>>, Integer> getAllDefaultValues() {
   return Maps.filterValues(
       Maps.transformValues(
           segments, dataEntry -> dataEntry == null ? null : dataEntry.getPermissionDefault()),
       v -> v != null);
 }
Exemple #6
0
    public HttpPost getPostMethod() throws Exception {
      if (post == null) {
        Map<String, Object> message = Maps.newHashMap();
        ArrayList<Map<String, Object>> actionInstanceArray = new ArrayList<>();
        for (int i = 0; i < qualifiedName.size(); i++) {
          Map<String, Object> actionInstance = Maps.newHashMap();
          actionInstance.put("descriptor", qualifiedName.get(i));
          if (actionParams.get(i) != null) {
            actionInstance.put("params", actionParams.get(i));
          }
          actionInstanceArray.add(actionInstance);
        }
        if (app == null) {
          app =
              Aura.getDefinitionService()
                  .getDefDescriptor("auratest:test_SimpleServerRenderedPage", ApplicationDef.class);
        }
        message.put("actions", actionInstanceArray.toArray());
        String jsonMessage = Json.serialize(message);
        Map<String, String> params = Maps.newHashMap();
        params.put("message", jsonMessage);
        params.put("aura.token", getTestServletConfig().getCsrfToken());

        params.put("aura.context", getAuraTestingUtil().buildContextForPost(mode, app, null, dn));
        post = obtainPostMethod("/aura", params);
      }
      return post;
    }
      @Override
      public Map<Symbol, Symbol> visitProject(ProjectNode node, Set<Symbol> lookupSymbols) {
        // Map from output Symbols to source Symbols
        Map<Symbol, Symbol> directSymbolTranslationOutputMap =
            Maps.transformValues(
                Maps.filterValues(node.getAssignments(), SymbolReference.class::isInstance),
                Symbol::from);
        Map<Symbol, Symbol> outputToSourceMap =
            lookupSymbols
                .stream()
                .filter(directSymbolTranslationOutputMap.keySet()::contains)
                .collect(toImmutableMap(identity(), directSymbolTranslationOutputMap::get));

        checkState(
            !outputToSourceMap.isEmpty(),
            "No lookup symbols were able to pass through the projection");

        // Map from source Symbols to underlying index source Symbols
        Map<Symbol, Symbol> sourceToIndexMap =
            node.getSource().accept(this, ImmutableSet.copyOf(outputToSourceMap.values()));

        // Generate the Map the connects lookup symbols to underlying index source symbols
        Map<Symbol, Symbol> outputToIndexMap =
            Maps.transformValues(
                Maps.filterValues(outputToSourceMap, in(sourceToIndexMap.keySet())),
                Functions.forMap(sourceToIndexMap));
        return ImmutableMap.copyOf(outputToIndexMap);
      }
  /**
   * Sets the new enum lists for this schema. The sets in the provided maps are converted into
   * lists, and sorted according to their natural ordering.
   *
   * @param enums The new enum sets for this schema.
   */
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void setEnumsSetComparable(Map<String, Set<Comparable>> enums) {
    Preconditions.checkNotNull(enums);
    areEnumsUpdated = true;

    Map<String, List<Object>> enumsList = Maps.newHashMap();

    // Check that all the given keys are valid
    Preconditions.checkArgument(
        configurationSchema.getKeyDescriptor().getFields().getFields().containsAll(enums.keySet()),
        "The given map doesn't contain valid keys. Valid keys are %s and the provided keys are %s",
        configurationSchema.getKeyDescriptor().getFields().getFields(),
        enums.keySet());

    // Todo check the type of the objects, for now just set them on the enum.
    for (Map.Entry<String, Set<Comparable>> entry : enums.entrySet()) {
      String name = entry.getKey();
      Set<Comparable> vals = entry.getValue();

      Preconditions.checkNotNull(name);
      Preconditions.checkNotNull(vals);

      for (Object value : entry.getValue()) {
        Preconditions.checkNotNull(value);
      }

      List<Comparable> valsListComparable = Lists.newArrayList(vals);
      Collections.sort(valsListComparable);
      List<Object> valsList = (List) valsListComparable;
      enumsList.put(name, valsList);
    }

    currentEnumVals = Maps.newHashMap(enumsList);
  }
Exemple #9
0
 private void label(SubmitRecord.Label n, AccountInfo who) {
   switch (n.status) {
     case OK:
       if (ok == null) {
         ok = Maps.newLinkedHashMap();
       }
       ok.put(n.label, who);
       break;
     case REJECT:
       if (reject == null) {
         reject = Maps.newLinkedHashMap();
       }
       reject.put(n.label, who);
       break;
     case NEED:
       if (need == null) {
         need = Maps.newLinkedHashMap();
       }
       need.put(n.label, new None());
       break;
     case MAY:
       if (may == null) {
         may = Maps.newLinkedHashMap();
       }
       may.put(n.label, who);
       break;
     case IMPOSSIBLE:
       if (impossible == null) {
         impossible = Maps.newLinkedHashMap();
       }
       impossible.put(n.label, new None());
       break;
   }
 }
 private static LinkedHashMap<IProjectStage, Map<IProjectStageSkill, IWorkLoad>>
     extractSkillToWorkLoadMapList(
         List<String> words, List<IProjectStage> stages, List<IProjectStageSkill> skillsList) {
   LinkedHashMap<IProjectStage, Map<IProjectStageSkill, IWorkLoad>> stageToWorkLoadMap =
       Maps.newLinkedHashMap();
   LinkedHashMap<IProjectStage, List<String>> estimationStringMap =
       extractEstimationStringMap(words, stages);
   Map<IProjectStage, List<IProjectStageSkill>> stageToSkillMap =
       extractStageToSkillMap(stages, skillsList);
   for (Entry<IProjectStage, List<String>> estimationStringEntry :
       estimationStringMap.entrySet()) {
     Map<IProjectStageSkill, IWorkLoad> workLoadMap = Maps.newHashMap();
     IProjectStage stage = estimationStringEntry.getKey();
     List<String> estimationStrings = estimationStringEntry.getValue();
     List<IProjectStageSkill> stageSkillList = stageToSkillMap.get(stage);
     for (int i = 0; i < stageSkillList.size(); i++) {
       String estimationString = estimationStrings.get(i);
       IProjectStageSkill skill = stageSkillList.get(i);
       if (estimationString == null || estimationString.trim().isEmpty()) {
         continue;
       }
       Float estimation = Float.parseFloat(estimationString.replace(',', '.'));
       IWorkLoad load = new WorkLoad(estimation, DEFAULT_WORKLOAD_TIMEUNIT);
       workLoadMap.put(skill, load);
     }
     stageToWorkLoadMap.put(stage, workLoadMap);
   }
   return stageToWorkLoadMap;
 }
 private static class OperatorClassInfo {
   String comment;
   final Map<String, String> tags = new HashMap<String, String>();
   final Map<String, MethodInfo> getMethods = Maps.newHashMap();
   final Map<String, MethodInfo> setMethods = Maps.newHashMap();
   final Map<String, String> fields = new HashMap<String, String>();
 }
 private static Map<IEpic, Map<IStory, Set<String>>> extractEpicsToStoryPredsMap(
     List<String> epicsStrings, List<IProjectStage> stages, List<IProjectStageSkill> skillList) {
   Map<IEpic, Map<IStory, Set<String>>> epicsToStoryMap = Maps.newHashMap();
   Map<IStory, Set<String>> storyToPredIdMap = Maps.newHashMap();
   String epicTitle = null;
   String epicId = null;
   for (String storyString : epicsStrings) {
     if (Strings.isNullOrEmpty(storyString.trim())) {
       continue;
     }
     LOGGER.debug("create story for string: {}", storyString);
     Iterable<String> strings = Splitter.on('\t').split(storyString);
     List<String> words = Lists.newArrayList(strings);
     if (!words.get(0).isEmpty()) {
       if (epicTitle != null) {
         IEpic epic = new Epic(epicId, epicTitle, storyToPredIdMap.keySet());
         epicsToStoryMap.put(epic, storyToPredIdMap);
       }
       storyToPredIdMap = Maps.newHashMap();
       epicId = words.get(EPIC_ID_COL_INDEX);
       epicTitle = words.get(EPIC_TITLE_COL_INDEX);
     }
     Entry<IStory, Set<String>> storyToPredIdsEntry =
         extractStoryAndPredecessorIds(words, stages, skillList);
     storyToPredIdMap.put(storyToPredIdsEntry.getKey(), storyToPredIdsEntry.getValue());
   }
   // TODO last epic is missing
   return epicsToStoryMap;
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  private <T extends Entity> brooklyn.entity.proxying.EntitySpec<?> toCoreEntitySpec(
      Class<T> clazz, String name, Map<String, String> configO) {
    Map<String, String> config =
        (configO == null)
            ? Maps.<String, String>newLinkedHashMap()
            : Maps.newLinkedHashMap(configO);

    brooklyn.entity.proxying.EntitySpec<? extends Entity> result;
    if (clazz.isInterface()) {
      result = brooklyn.entity.proxying.EntitySpec.create(clazz);
    } else {
      // If this is a concrete class, particularly for an Application class, we want the proxy
      // to expose all interfaces it implements.
      Class interfaceclazz =
          (Application.class.isAssignableFrom(clazz)) ? Application.class : Entity.class;
      Set<Class<?>> additionalInterfaceClazzes =
          Reflections.getInterfacesIncludingClassAncestors(clazz);
      result =
          brooklyn.entity.proxying.EntitySpec.create(interfaceclazz)
              .impl(clazz)
              .additionalInterfaces(additionalInterfaceClazzes);
    }

    if (!Strings.isEmpty(name)) result.displayName(name);
    result.configure(convertFlagsToKeys(result.getImplementation(), config));
    return result;
  }
  @SuppressWarnings("unchecked")
  private brooklyn.entity.proxying.EntitySpec<? extends Entity> toCoreEntitySpec(
      brooklyn.rest.domain.EntitySpec spec) {
    String type = spec.getType();
    String name = spec.getName();
    Map<String, String> config =
        (spec.getConfig() == null)
            ? Maps.<String, String>newLinkedHashMap()
            : Maps.newLinkedHashMap(spec.getConfig());

    Class<? extends Entity> tempclazz;
    try {
      tempclazz = getCatalog().loadClassByType(type, Entity.class);
    } catch (NoSuchElementException e) {
      try {
        tempclazz = (Class<? extends Entity>) getCatalog().getRootClassLoader().loadClass(type);
        log.info("Catalog does not contain item for type {}; loaded class directly instead", type);
      } catch (ClassNotFoundException e2) {
        log.warn(
            "No catalog item for type {}, and could not load class directly; rethrowing", type);
        throw e;
      }
    }
    final Class<? extends Entity> clazz = tempclazz;
    brooklyn.entity.proxying.EntitySpec<? extends Entity> result;
    if (clazz.isInterface()) {
      result = brooklyn.entity.proxying.EntitySpec.create(clazz);
    } else {
      result = brooklyn.entity.proxying.EntitySpec.create(Entity.class).impl(clazz);
    }
    if (!Strings.isEmpty(name)) result.displayName(name);
    result.configure(convertFlagsToKeys(result.getType(), config));
    configureRenderingMetadata(spec, result);
    return result;
  }
  @Override
  public void setGroupMapping(Map<String, String> mapping) {
    Map<String, String> internal;
    if (mapping == null) {
      internal = Collections.emptyMap();
    } else {
      // we store ids internally but external users use the group names
      try {
        final Map<String, Role> nameToRole =
            Maps.uniqueIndex(roleService.loadAll(), Roles.roleToNameFunction());

        internal =
            Maps.newHashMap(
                Maps.transformValues(
                    mapping,
                    new Function<String, String>() {
                      @Nullable
                      @Override
                      public String apply(@Nullable String groupName) {
                        if (groupName == null || !nameToRole.containsKey(groupName)) {
                          return null;
                        }
                        return nameToRole.get(groupName).getId();
                      }
                    }));
      } catch (NotFoundException e) {
        LOG.error("Unable to convert group names to ids", e);
        throw new IllegalStateException("Unable to convert group names to ids", e);
      }
    }

    fields.put(GROUP_MAPPING, internal);
  }
  private class CheckProvidesCallback extends AbstractShallowCallback {
    private final Map<String, Node> provides = Maps.newHashMap();
    private final Map<String, Node> ctors = Maps.newHashMap();
    private final CodingConvention convention;

    CheckProvidesCallback(CodingConvention convention) {
      this.convention = convention;
    }

    @Override
    public void visit(NodeTraversal t, Node n, Node parent) {
      switch (n.getType()) {
        case Token.CALL:
          String providedClassName = codingConvention.extractClassNameIfProvide(n, parent);
          if (providedClassName != null) {
            provides.put(providedClassName, n);
          }
          break;
        case Token.FUNCTION:
          visitFunctionNode(n, parent);
          break;
        case Token.SCRIPT:
          visitScriptNode(t, n);
      }
    }

    private void visitFunctionNode(Node n, Node parent) {
      Node name = null;
      JSDocInfo info = parent.getJSDocInfo();
      if (info != null && info.isConstructor()) {
        name = parent.getFirstChild();
      } else {
        // look to the child, maybe it's a named function
        info = n.getJSDocInfo();
        if (info != null && info.isConstructor()) {
          name = n.getFirstChild();
        }
      }
      if (name != null && name.isQualifiedName()) {
        String qualifiedName = name.getQualifiedName();
        if (!this.convention.isPrivate(qualifiedName)) {
          Visibility visibility = info.getVisibility();
          if (!visibility.equals(JSDocInfo.Visibility.PRIVATE)) {
            ctors.put(qualifiedName, name);
          }
        }
      }
    }

    private void visitScriptNode(NodeTraversal t, Node n) {
      for (String ctorName : ctors.keySet()) {
        if (!provides.containsKey(ctorName)) {
          compiler.report(
              t.makeError(ctors.get(ctorName), checkLevel, MISSING_PROVIDE_WARNING, ctorName));
        }
      }
      provides.clear();
      ctors.clear();
    }
  }
Exemple #17
0
  @Nonnull
  @VisibleForTesting
  public Map<Path, String> parsePackageStrings(
      @Nonnull List<Path> absolutePaths, @Nonnull List<Path> executionPaths) throws Exception {

    ListeningExecutorService executorService =
        MoreExecutors.listeningDecorator(
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));

    Map<Path, ListenableFuture<String>> futures = Maps.newHashMap();
    for (int i = 0; i < absolutePaths.size(); i++) {
      final Path source = executionPaths.get(i);
      futures.put(
          absolutePaths.get(i),
          executorService.submit(
              new Callable<String>() {
                @Override
                public String call() throws Exception {
                  return getDeclaredPackageOfJavaFile(source);
                }
              }));
    }
    Map<Path, String> map = Maps.newHashMap();
    for (Entry<Path, ListenableFuture<String>> entry : futures.entrySet()) {
      String value = entry.getValue().get();
      if (value != null) {
        map.put(entry.getKey(), value);
      }
    }
    return map;
  }
Exemple #18
0
 public SparkRuntime(
     SparkPipeline pipeline,
     JavaSparkContext sparkContext,
     Configuration conf,
     Map<PCollectionImpl<?>, Set<Target>> outputTargets,
     Map<PCollectionImpl<?>, MaterializableIterable> toMaterialize,
     Map<PCollection<?>, StorageLevel> toCache,
     Map<PipelineCallable<?>, Set<Target>> allPipelineCallables) {
   this.pipeline = pipeline;
   this.sparkContext = sparkContext;
   this.conf = conf;
   this.counters =
       sparkContext.accumulator(
           Maps.<String, Map<String, Long>>newHashMap(), new CounterAccumulatorParam());
   this.ctxt =
       new SparkRuntimeContext(
           sparkContext.appName(),
           counters,
           sparkContext.broadcast(WritableUtils.toByteArray(conf)));
   this.outputTargets = Maps.newTreeMap(DEPTH_COMPARATOR);
   this.outputTargets.putAll(outputTargets);
   this.toMaterialize = toMaterialize;
   this.toCache = toCache;
   this.allPipelineCallables = allPipelineCallables;
   this.activePipelineCallables = allPipelineCallables.keySet();
   this.status.set(Status.READY);
   this.monitorThread =
       new Thread(
           new Runnable() {
             @Override
             public void run() {
               monitorLoop();
             }
           });
 }
 /** Constructor for restore case. */
 private Allocation(
     final String reservationId,
     final String instanceId,
     final String instanceUuid,
     final int launchIndex,
     final boolean usePrivateAddressing,
     final VmType vmType,
     final BootableSet bootSet,
     final Partition partition,
     final SshKeyPair sshKeyPair,
     final byte[] userData,
     final UserFullName ownerFullName) {
   this.minCount = 1;
   this.maxCount = 1;
   this.vmType = vmType;
   this.bootSet = bootSet;
   this.partition = partition;
   this.sshKeyPair = sshKeyPair;
   this.userData = userData;
   this.ownerFullName = ownerFullName;
   this.reservationId = reservationId;
   this.reservationIndex = -1l;
   this.instanceIds = Maps.newHashMap();
   this.instanceIds.put(launchIndex, instanceId);
   this.instanceUuids = Maps.newHashMap();
   this.instanceUuids.put(launchIndex, instanceUuid);
   this.allocationTokens.add(new ResourceToken(this, launchIndex));
   this.context = null;
   this.monitoring = false;
   this.usePrivateAddressing = usePrivateAddressing;
   this.clientToken = null;
   this.request = inferRequest();
 }
  public void build() throws IOException {

    moduleNameToMakeFileMap = Maps.newHashMap();
    makeFileToModuleNamesMap = Maps.newHashMap();
    logger.info("Building index from " + indexFile.getCanonicalPath());
    Files.readLines(
        indexFile,
        Charset.forName("UTF-8"),
        new LineProcessor<Object>() {
          int count = 0;

          @Override
          public boolean processLine(String line) throws IOException {
            count++;
            String[] arr = line.split(":");
            if (arr.length < 2) {
              logger.log(Level.WARNING, "Ignoring index line " + count + ". Bad format: " + line);
            } else {
              String makeFile = arr[0];
              String moduleName = arr[1];
              moduleNameToMakeFileMap.put(moduleName, makeFile);
              append(makeFile, moduleName);
            }
            return true;
          }

          @Override
          public Object getResult() {
            return null;
          }
        });
  }
public class AllDownloads {

  private Map<String, SetSaved> sets = Maps.newHashMap();
  private Map<String, FileSaved> allDownloadsByDiggest = Maps.newHashMap();
  private Map<String, FileSaved> allDownloadsBySource = Maps.newHashMap();

  public AllDownloads() {}

  public Map<String, SetSaved> getSets() {
    return sets;
  }

  public Map<String, FileSaved> getAllDownloadsByDiggest() {
    return allDownloadsByDiggest;
  }

  public Map<String, FileSaved> getAllDownloadsBySource() {
    return allDownloadsBySource;
  }

  public AllDownloads addDownloadedFile(FileSaved fileSaved) {
    synchronized (this) {
      allDownloadsByDiggest.put(fileSaved.getDiggest(), fileSaved);
      allDownloadsBySource.put(fileSaved.getSource().getSource(), fileSaved);
    }
    return this;
  }

  public AllDownloads addDownloadedSet(SetSaved setSaved) {
    synchronized (this) {
      sets.put(setSaved.getSource().getSource(), setSaved);
    }
    return this;
  }
}
  private Map<String, FilteringPropertyFilter> createSubfilters(
      final Class<?> entityClass, final Map<String, ObjectGraph> entitySubgraphs) {
    final Set<String> processed = Sets.newHashSet();
    final Map<String, FilteringPropertyFilter> subfilters = Maps.newHashMap();

    for (final Map.Entry<String, ObjectGraph> entry : entitySubgraphs.entrySet()) {
      final String fieldName = entry.getKey();

      if (fieldName.startsWith("_")) continue;

      final ObjectGraph graph = entry.getValue();

      // Subgraph Fields.
      final Map<String, ObjectGraph> subgraphs = graph.getSubgraphs(fieldName);

      Map<String, FilteringPropertyFilter> subSubfilters = Maps.newHashMap();
      if (!subgraphs.isEmpty()) {
        final Class<?> subEntityClass = graph.getEntityClass();

        processed.add(getProcessedSubgraph(entityClass, fieldName, subEntityClass));
        subSubfilters = createSubfilters(fieldName, subEntityClass, subgraphs, processed);
      }

      final FilteringPropertyFilter filter =
          new FilteringPropertyFilter(
              graph.getEntityClass(), graph.getFields(fieldName), subSubfilters);

      subfilters.put(fieldName, filter);
    }

    return subfilters;
  }
 @Override
 public Map<Set<Entry<String, String>>, Map<String, Integer>> getAllPermissions() {
   return Maps.filterValues(
       Maps.transformValues(
           segments, dataEntry -> dataEntry == null ? null : dataEntry.getPermissions()),
       o -> o != null);
 }
  private CheckPointOutputOperator checkpoint(AbstractSingleFileOutputOperator<Integer> writer) {
    CheckPointOutputOperator checkPointWriter = new CheckPointOutputOperator();
    checkPointWriter.counts = Maps.newHashMap();

    for (String keys : writer.counts.keySet()) {
      checkPointWriter.counts.put(keys, new MutableLong(writer.counts.get(keys).longValue()));
    }

    checkPointWriter.endOffsets = Maps.newHashMap();

    for (String keys : writer.endOffsets.keySet()) {
      checkPointWriter.endOffsets.put(
          keys, new MutableLong(writer.endOffsets.get(keys).longValue()));
    }

    checkPointWriter.openPart = Maps.newHashMap();

    for (String keys : writer.openPart.keySet()) {
      checkPointWriter.openPart.put(keys, new MutableInt(writer.openPart.get(keys).intValue()));
    }

    checkPointWriter.filePath = writer.filePath;
    checkPointWriter.maxOpenFiles = writer.maxOpenFiles;
    checkPointWriter.replication = writer.replication;
    checkPointWriter.totalBytesWritten = writer.totalBytesWritten;
    checkPointWriter.maxLength = writer.maxLength;
    checkPointWriter.rollingFile = writer.rollingFile;
    checkPointWriter.outputFileName = writer.outputFileName;

    return checkPointWriter;
  }
  /**
   * @param customerUser The Customer User
   * @return A HAL representation of the result
   */
  @DELETE
  @Timed
  public Response deregisterUser(@RestrictedTo({Authority.ROLE_CUSTOMER}) User customerUser) {

    Preconditions.checkNotNull(customerUser);

    // Remove all identifying information from the User
    // but leave the entity available for audit purposes
    // We leave the secret key in case the user has been
    // accidentally deleted and the user wants to be
    // reinstated
    customerUser.setApiKey("");
    customerUser.setContactMethodMap(Maps.<ContactMethod, ContactMethodDetail>newHashMap());
    customerUser.setUsername("");
    customerUser.setPasswordDigest("");
    customerUser.setPasswordResetAt(DateUtils.nowUtc());
    customerUser.setLocked(true);
    customerUser.setDeleted(true);
    customerUser.setReasonForDelete("Customer deregistered");
    customerUser.setUserFieldMap(Maps.<UserField, UserFieldDetail>newHashMap());

    // Persist the User with cascade for the Customer
    User persistentUser = userDao.saveOrUpdate(customerUser);

    // Provide a minimal representation to the client
    // so that they can see their secret key as a last resort
    // manual recovery option
    ClientUserBridge bridge = new ClientUserBridge(uriInfo, Optional.of(customerUser));
    URI location = uriInfo.getAbsolutePathBuilder().path(persistentUser.getApiKey()).build();

    return created(bridge, persistentUser, location);
  }
/** User: xiongyuanwei Date: 12-7-17 Time: 下午8:38 */
public class StateFactory {

  private static Map<String, State> mapping = Maps.newHashMap();
  private static Map<String, State> mapping2 = Maps.newHashMap();
  private static Map<Long, State> mapping3 = Maps.newHashMap();

  static {
    for (State state : State.values()) {
      mapping.put(state.getNodeName(), state);
      mapping2.put(state.getName(), state);
      mapping3.put(state.getId(), state);
    }
  }

  public static State getStateByNodeName(String nodeName) {
    return mapping.get(nodeName);
  }

  public static State getStateByTaskName(String taskName) {
    return mapping2.get(taskName);
  }

  public static State getStateById(long stateId) {
    return mapping3.get(stateId);
  }
}
 public boolean check() {
   final Properties oldProps = new Properties();
   if (BindingFileSearch.CACHE_LIST.exists()) {
     try {
       Reader propIn = Files.newReader(BindingFileSearch.CACHE_LIST, Charset.defaultCharset());
       oldProps.load(propIn);
     } catch (Exception ex) {
       LOG.debug(ex, ex);
     }
   }
   Map<String, String> oldBindings = Maps.fromProperties(oldProps);
   Map<String, String> newBindings = Maps.fromProperties(BindingFileSearch.CURRENT_PROPS);
   if (oldBindings.equals(newBindings)) {
     LOG.info("Found up-to-date binding class cache: skipping message binding.");
     return true;
   } else {
     MapDifference<String, String> diffBindings = Maps.difference(oldBindings, newBindings);
     LOG.info("Binding class cache expired (old,new): \n" + diffBindings.entriesDiffering());
     try {
       Files.deleteRecursively(SubDirectory.CLASSCACHE.getFile());
     } catch (IOException ex) {
       LOG.error(ex, ex);
     }
     SubDirectory.CLASSCACHE.getFile().mkdir();
     return false;
   }
 }
Exemple #28
0
  /**
   * Remember that we are trying to cast something of type {@code supertype} to {@code subtype}.
   *
   * <p>Since at runtime we can only check the class (type constructor), the rest of the subtype
   * should be known statically, from supertype. This method reconstructs all static information
   * that can be obtained from supertype.
   *
   * <p>Example 1: supertype = Collection<String> subtype = List<...> result = List<String>, all
   * arguments are inferred
   *
   * <p>Example 2: supertype = Any subtype = List<...> result = List<*>, some arguments were not
   * inferred, replaced with '*'
   */
  public static TypeReconstructionResult findStaticallyKnownSubtype(
      @NotNull KotlinType supertype, @NotNull TypeConstructor subtypeConstructor) {
    assert !supertype.isMarkedNullable() : "This method only makes sense for non-nullable types";

    // Assume we are casting an expression of type Collection<Foo> to List<Bar>
    // First, let's make List<T>, where T is a type variable
    ClassifierDescriptor descriptor = subtypeConstructor.getDeclarationDescriptor();
    assert descriptor != null : "Can't create default type for " + subtypeConstructor;
    KotlinType subtypeWithVariables = descriptor.getDefaultType();

    // Now, let's find a supertype of List<T> that is a Collection of something,
    // in this case it will be Collection<T>
    KotlinType supertypeWithVariables =
        TypeCheckingProcedure.findCorrespondingSupertype(subtypeWithVariables, supertype);

    final List<TypeParameterDescriptor> variables =
        subtypeWithVariables.getConstructor().getParameters();

    Map<TypeConstructor, TypeProjection> substitution;
    if (supertypeWithVariables != null) {
      // Now, let's try to unify Collection<T> and Collection<Foo> solution is a map from T to Foo
      TypeUnifier.UnificationResult solution =
          TypeUnifier.unify(
              new TypeProjectionImpl(supertype),
              new TypeProjectionImpl(supertypeWithVariables),
              new Predicate<TypeConstructor>() {
                @Override
                public boolean apply(TypeConstructor typeConstructor) {
                  ClassifierDescriptor descriptor = typeConstructor.getDeclarationDescriptor();
                  return descriptor instanceof TypeParameterDescriptor
                      && variables.contains(descriptor);
                }
              });
      substitution = Maps.newHashMap(solution.getSubstitution());
    } else {
      // If there's no corresponding supertype, no variables are determined
      // This may be OK, e.g. in case 'Any as List<*>'
      substitution = Maps.newHashMapWithExpectedSize(variables.size());
    }

    // If some of the parameters are not determined by unification, it means that these parameters
    // are lost,
    // let's put stars instead, so that we can only cast to something like List<*>, e.g. (a: Any) as
    // List<*>
    boolean allArgumentsInferred = true;
    for (TypeParameterDescriptor variable : variables) {
      TypeProjection value = substitution.get(variable.getTypeConstructor());
      if (value == null) {
        substitution.put(variable.getTypeConstructor(), TypeUtils.makeStarProjection(variable));
        allArgumentsInferred = false;
      }
    }

    // At this point we have values for all type parameters of List
    // Let's make a type by substituting them: List<T> -> List<Foo>
    KotlinType substituted =
        TypeSubstitutor.create(substitution).substitute(subtypeWithVariables, Variance.INVARIANT);

    return new TypeReconstructionResult(substituted, allArgumentsInferred);
  }
  @Test
  public void defaultConfigNoEsFile() {
    // check that all ES settings will be taken from the default values in Configuration.java if
    // nothing is specified.
    Map<String, String> minimalSettings = Maps.newHashMap();
    ElasticsearchConfiguration defaultConfig = setupConfig(minimalSettings);

    Map<String, String> settings = Maps.newHashMap();
    ElasticsearchConfiguration config = setupConfig(settings);

    Map<String, String> nodeSettings = EsNodeProvider.readNodeSettings(config);

    assertEquals(defaultConfig.getClusterName(), nodeSettings.get("cluster.name"));
    assertEquals(defaultConfig.getNodeName(), nodeSettings.get("node.name"));
    assertEquals(Boolean.toString(defaultConfig.isMasterNode()), nodeSettings.get("node.master"));
    assertEquals(Boolean.toString(defaultConfig.isDataNode()), nodeSettings.get("node.data"));
    assertEquals(Boolean.toString(defaultConfig.isHttpEnabled()), nodeSettings.get("http.enabled"));
    assertEquals(
        String.valueOf(defaultConfig.getTransportTcpPort()),
        nodeSettings.get("transport.tcp.port"));
    assertEquals(
        defaultConfig.getInitialStateTimeout(),
        nodeSettings.get("discovery.initial_state_timeout"));
    assertEquals(
        Boolean.toString(defaultConfig.isMulticastDiscovery()),
        nodeSettings.get("discovery.zen.ping.multicast.enabled"));
    assertEquals(Boolean.toString(false), nodeSettings.get("action.auto_create_index"));
  }
 /** Returns a {@link Map} of {@link JobId} to {@link Job} objects for all of the jobs known. */
 @Override
 public Map<JobId, Job> getJobs() {
   log.debug("getting jobs");
   final String folder = Paths.configJobs();
   final ZooKeeperClient client = provider.get("getJobs");
   try {
     final List<String> ids;
     try {
       ids = client.getChildren(folder);
     } catch (NoNodeException e) {
       return Maps.newHashMap();
     }
     final Map<JobId, Job> descriptors = Maps.newHashMap();
     for (final String id : ids) {
       final JobId jobId = JobId.fromString(id);
       final String path = Paths.configJob(jobId);
       final byte[] data = client.getData(path);
       final Job descriptor = parse(data, Job.class);
       descriptors.put(descriptor.getId(), descriptor);
     }
     return descriptors;
   } catch (KeeperException | IOException e) {
     throw new HeliosRuntimeException("getting jobs failed", e);
   }
 }