예제 #1
0
 NominalType(ImmutableMap<String, JSType> typeMap, RawNominalType rawType) {
   Preconditions.checkState(
       typeMap.isEmpty()
           || typeMap.keySet().containsAll(rawType.getTypeParameters())
               && rawType.getTypeParameters().containsAll(typeMap.keySet()));
   this.typeMap = typeMap;
   this.rawType = rawType;
 }
예제 #2
0
    private void installSecondaryDexFiles() throws Exception {
      final ImmutableMap<String, Path> hashToSources = getRequiredDexFiles();
      final ImmutableSet<String> requiredHashes = hashToSources.keySet();
      final ImmutableSet<String> presentHashes = prepareSecondaryDexDir(requiredHashes);
      final Set<String> hashesToInstall = Sets.difference(requiredHashes, presentHashes);

      Map<String, Path> filesToInstallByHash =
          Maps.filterKeys(hashToSources, Predicates.in(hashesToInstall));

      // This is a bit gross.  It was a late addition.  Ideally, we could eliminate this, but
      // it wouldn't be terrible if we don't.  We store the dexed jars on the device
      // with the full SHA-1 hashes in their names.  This is the format that the loader uses
      // internally, so ideally we would just load them in place.  However, the code currently
      // expects to be able to copy the jars from a directory that matches the name in the
      // metadata file, like "secondary-1.dex.jar".  We don't want to give up putting the
      // hashes in the file names (because we use that to skip re-uploads), so just hack
      // the metadata file to have hash-like names.
      String metadataContents =
          com.google.common.io.Files.toString(
                  projectFilesystem
                      .resolve(exopackageInfo.getDexInfo().get().getMetadata())
                      .toFile(),
                  Charsets.UTF_8)
              .replaceAll(
                  "secondary-(\\d+)\\.dex\\.jar (\\p{XDigit}{40}) ", "secondary-$2.dex.jar $2 ");

      installFiles(
          "secondary_dex",
          ImmutableMap.copyOf(filesToInstallByHash),
          metadataContents,
          "secondary-%s.dex.jar",
          SECONDARY_DEX_DIR);
    }
 public static String dumpConfigurationAsJson() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory jfactory = mapper.getJsonFactory();
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator gen = jfactory.createJsonGenerator(sw);
     gen.writeStartArray();
     for (String v : keys) {
       String st = dumpConfigurationAsJson(v);
       ObjectMapper op = new ObjectMapper();
       JsonNode p = op.readTree(st);
       Logger.debug("OBJECT:" + p.toString());
       Logger.debug("STRING:" + st);
       // JsonParser jp = jfactory.createJsonParser(st);
       gen.writeTree(p);
     }
     gen.writeEndArray();
     gen.close();
     return sw.toString();
   } catch (Exception e) {
     Logger.error("Cannot generate a json for the configuration", e);
   }
   return "[]";
 } // dumpConfigurationAsJson()
예제 #4
0
 @Override
 public String errorMessage(String name) {
   String suffix =
       "Available attributes: "
           + Joiner.on(", ").join(Ordering.natural().sortedCopy(values.keySet()));
   return String.format(errorMessage, name) + "\n" + suffix;
 }
 public void testHashing() {
   for (String stringToTest : INPUTS) {
     for (String algorithmToTest : ALGORITHMS.keySet()) {
       assertMessageDigestHashing(HashTestUtils.ascii(stringToTest), algorithmToTest);
     }
   }
 }
예제 #6
0
  public static AnyRequest parse(final String originalTarget) throws MalformedRequestException {
    final Matcher matcher = DOCUMENT_PATTERN.matcher(originalTarget);
    if (matcher.find() && matcher.groupCount() >= 4) {

      // Document source name plus extension, minus page identifier.
      final String fullTarget = matcher.group(2) + "." + matcher.group(4);

      final boolean showProblems = fullTarget.endsWith(ERRORPAGE_SUFFIX);

      final String targetMinusError;
      if (showProblems) {
        targetMinusError = fullTarget.substring(0, fullTarget.length() - ERRORPAGE_SUFFIX.length());
      } else {
        targetMinusError = fullTarget;
      }

      final String rawDocumentMimeType = extractExtension(targetMinusError);
      final String rawDocumentSourceName =
          targetMinusError.substring(
              0, targetMinusError.length() - rawDocumentMimeType.length() - 1);

      final String maybePageIdentifier = matcher.group(3);
      final PageIdentifier pageIdentifier =
          maybePageIdentifier == null ? null : new PageIdentifier(maybePageIdentifier);

      final RenditionMimeType renditionMimeType =
          RenditionMimeType.maybeValueOf(
              rawDocumentMimeType == null ? null : rawDocumentMimeType.toUpperCase());

      final ImmutableMap<String, String> parameterMap =
          matcher.groupCount() >= 5
              ? getQueryMap(matcher.group(5))
              : ImmutableMap.<String, String>of();
      verifyAllParameterNames(parameterMap.keySet());

      final ResourceName alternateStylesheet = extractResourceName(parameterMap);

      final ImmutableSet<Tag> tagset = extractTags(parameterMap);

      final AnyRequest request;
      if (renditionMimeType == null) {
        request = new GenericRequest(originalTarget, rawDocumentSourceName, rawDocumentMimeType);
      } else {
        request =
            new GenericRequest(
                originalTarget,
                rawDocumentSourceName,
                showProblems,
                renditionMimeType,
                pageIdentifier,
                alternateStylesheet,
                tagset);
      }
      return request;

    } else {
      throw new MalformedRequestException("Could not parse: '" + originalTarget + "'.");
    }
  }
 public static String dumpConfiguration() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   StringBuilder sb = new StringBuilder();
   for (String v : keys) {
     sb.append(dumpConfiguration(v));
     sb.append("\n");
   }
   return sb.toString();
 } // dumpConfiguration()
예제 #8
0
 public static Iterable<? extends XcodeprojBuildSetting> defaultWarningsForXcode() {
   return Iterables.transform(
       DEFAULT_WARNINGS.keySet(),
       new Function<String, XcodeprojBuildSetting>() {
         @Override
         public XcodeprojBuildSetting apply(String key) {
           return XcodeprojBuildSetting.newBuilder().setName(key).setValue("YES").build();
         }
       });
 }
  // -------------------------------------------------------------------------
  public void test_cashFlowEquivalentAndSensitivity() {
    Swap swap = Swap.builder().legs(IBOR_LEG, FIXED_LEG).build();
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedFull =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivitySwap(swap.expand(), PROVIDER);
    ImmutableList<NotionalExchange> keyComputedFull = computedFull.keySet().asList();
    ImmutableList<PointSensitivityBuilder> valueComputedFull = computedFull.values().asList();
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedIborLeg =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivityIborLeg(
            IBOR_LEG.expand(), PROVIDER);
    ImmutableMap<NotionalExchange, PointSensitivityBuilder> computedFixedLeg =
        CashFlowEquivalentCalculator.cashFlowEquivalentAndSensitivityFixedLeg(
            FIXED_LEG.expand(), PROVIDER);
    assertEquals(computedFixedLeg.keySet().asList(), keyComputedFull.subList(0, 2));
    assertEquals(computedIborLeg.keySet().asList(), keyComputedFull.subList(2, 6));
    assertEquals(computedFixedLeg.values().asList(), valueComputedFull.subList(0, 2));
    assertEquals(computedIborLeg.values().asList(), valueComputedFull.subList(2, 6));

    double eps = 1.0e-7;
    RatesFiniteDifferenceSensitivityCalculator calc =
        new RatesFiniteDifferenceSensitivityCalculator(eps);
    int size = keyComputedFull.size();
    for (int i = 0; i < size; ++i) {
      final int index = i;
      CurveCurrencyParameterSensitivities expected =
          calc.sensitivity(
              PROVIDER,
              p ->
                  ((NotionalExchange)
                          CashFlowEquivalentCalculator.cashFlowEquivalentSwap(swap.expand(), p)
                              .getPaymentEvents()
                              .get(index))
                      .getPaymentAmount());
      PointSensitivityBuilder point =
          computedFull.get(
              CashFlowEquivalentCalculator.cashFlowEquivalentSwap(swap.expand(), PROVIDER)
                  .getPaymentEvents()
                  .get(index));
      CurveCurrencyParameterSensitivities computed =
          PROVIDER.curveParameterSensitivity(point.build());
      assertTrue(computed.equalWithTolerance(expected, eps * NOTIONAL));
    }
  }
예제 #10
0
    private void installNativeLibraryFiles() throws Exception {
      ImmutableMultimap<String, Path> allLibraries = getAllLibraries();
      ImmutableSet.Builder<String> providedLibraries = ImmutableSet.builder();
      for (String abi : getDeviceAbis()) {
        ImmutableMap<String, Path> libraries =
            getRequiredLibrariesForAbi(allLibraries, abi, providedLibraries.build());

        installNativeLibrariesForAbi(abi, libraries);
        providedLibraries.addAll(libraries.keySet());
      }
    }
예제 #11
0
 public ImmutableMap<IjLibrary, DependencyType> getDependentLibrariesFor(IjModule source) {
   final ImmutableMap<IjProjectElement, DependencyType> deps = getDepsFor(source);
   return FluentIterable.from(deps.keySet())
       .filter(IjLibrary.class)
       .toMap(
           new Function<IjLibrary, DependencyType>() {
             @Override
             public DependencyType apply(IjLibrary input) {
               return Preconditions.checkNotNull(deps.get(input));
             }
           });
 }
예제 #12
0
 public void renameFile(String from, String to) throws IOException {
   synchronized (mutex) {
     StoreFileMetaData fromMetaData = filesMetadata.get(from); // we should always find this one
     if (fromMetaData == null) {
       throw new FileNotFoundException(from);
     }
     directoryService.renameFile(fromMetaData.directory(), from, to);
     StoreFileMetaData toMetaData =
         new StoreFileMetaData(
             to, fromMetaData.length(), fromMetaData.checksum(), fromMetaData.directory());
     filesMetadata =
         MapBuilder.newMapBuilder(filesMetadata).remove(from).put(to, toMetaData).immutableMap();
     files = filesMetadata.keySet().toArray(new String[filesMetadata.size()]);
   }
 }
 @PostConstruct
 public void init() {
   final ImmutableMap<String, AppManifest> initialTenantMap = tenantConfig.tenantMap();
   log.debug(
       "Registering {} subscribers for {} tenants: {}",
       getClass().getName(),
       initialTenantMap.size(),
       initialTenantMap.keySet());
   for (final Map.Entry<String, AppManifest> tenant : initialTenantMap.entrySet()) {
     createSubscribers(tenant.getKey(), tenant.getValue(), "Init");
   }
   if (tenantRepo != null) {
     tenantRepo.addListener(this);
   }
 }
예제 #14
0
  private boolean classIsDefinitelyMutable(ClassNode klass) {
    if (superClassIsDefinitelyMutable(klass.superName)) {
      log.add("Mutable parent: " + klass.name + " < " + klass.superName);
      return true;
    }

    for (FieldNode field : klass.fields) {
      if ((field.access & Opcodes.ACC_STATIC) != 0) {
        continue;
      }
      if ((field.access & Opcodes.ACC_FINAL) == 0) {
        log.add("Non-final field: " + klass.name + "#" + field.name + ":" + field.desc);
        return true;
      }
      if (field.name.contains("$")) {
        // Generated fields are assumed to be effectively immutable.
        // This could, in principle, miss an issue like a static reference to a
        // seemingly-immutable inner class object that maintains a hidden reference
        // to its mutable outer object, but that seems unlikely.
        continue;
      }

      Type type = Type.getType(field.desc);

      if (IMMUTABLE_TYPE_SORTS.contains(type.getSort())) {
        continue;
      }

      if (type.getSort() != Type.OBJECT) {
        log.add("Odd sort: " + klass.name + "#" + field.name + ":" + field.desc);
        return true;
      }

      if (allClasses.keySet().contains(type.getInternalName())) {
        if (classesWithMutableDescendents.contains(type.getInternalName())) {
          log.add("Internal mutable field: " + klass.name + "#" + field.name + ":" + field.desc);
          return true;
        }
      } else {
        if (!EXTERNAL_IMMUTABLE_CLASSES.contains(type.getInternalName())) {
          log.add("External mutable field: " + klass.name + "#" + field.name + ":" + field.desc);
          return true;
        }
      }
    }

    return false;
  }
예제 #15
0
  private void go() {
    while (true) {
      madeProgress = false;
      for (ClassNode klass : allClasses.values()) {
        analyzeClass(klass);
      }
      if (!madeProgress) {
        break;
      }
    }

    immutableClasses =
        ImmutableSet.copyOf(
            Sets.difference(
                allClasses.keySet(),
                Sets.union(trulyMutableClasses, classesWithMutableDescendents)));
  }
  @Override
  public com.google.common.base.Optional<Model> modelFor(ModelContext modelContext) {
    ResolvedType propertiesHost = modelContext.alternateFor(modelContext.resolvedType(resolver));
    if (isContainerType(propertiesHost)
        || isMapType(propertiesHost)
        || propertiesHost.getErasedType().isEnum()
        || isBaseType(Types.typeNameFor(propertiesHost.getErasedType()))
        || modelContext.hasSeenBefore(propertiesHost)) {
      LOG.debug(
          "Skipping model of type {} as its either a container type, map, enum or base type, or its already "
              + "been handled",
          resolvedTypeSignature(propertiesHost).or("<null>"));
      return Optional.absent();
    }
    ImmutableMap<String, ModelProperty> propertiesIndex =
        uniqueIndex(properties(modelContext, propertiesHost), byPropertyName());
    LOG.debug(
        "Inferred {} properties. Properties found {}",
        propertiesIndex.size(),
        Joiner.on(", ").join(propertiesIndex.keySet()));

    SortedSet<Map.Entry<String, ModelProperty>> sortedProperties =
        new TreeSet<Map.Entry<String, ModelProperty>>(
            new Comparator<Map.Entry<String, ModelProperty>>() {
              @Override
              public int compare(
                  Map.Entry<String, ModelProperty> e1, Map.Entry<String, ModelProperty> e2) {
                if ((e1.getValue().getPosition().compareTo(e2.getValue().getPosition()) == 0)) {
                  return e1.getValue().getName().compareTo(e2.getValue().getName());
                }
                return new Integer(e1.getValue().getPosition())
                    .compareTo(e2.getValue().getPosition());
              }
            });

    sortedProperties.addAll(propertiesIndex.entrySet());

    Map<String, ModelProperty> properties = new LinkedHashMap<String, ModelProperty>();

    // Map<String, ModelProperty> properties = newTreeMap();
    // properties.putAll(propertiesIndex);
    for (Map.Entry<String, ModelProperty> value : sortedProperties) {
      properties.put(value.getKey(), value.getValue());
    }
    return Optional.of(modelBuilder(propertiesHost, properties, modelContext));
  }
예제 #17
0
 NominalType instantiateGenerics(Map<String, JSType> newTypeMap) {
   if (newTypeMap.isEmpty()) {
     return this;
   }
   if (!this.rawType.isGeneric()) {
     return this.rawType.getAsNominalType();
   }
   ImmutableMap.Builder<String, JSType> builder = ImmutableMap.builder();
   ImmutableMap<String, JSType> resultMap;
   if (!typeMap.isEmpty()) {
     // This branch is entered when a generic type appears "instantiated"
     // in some other type, and now we're actually instantiating it to concrete
     // types rather than to type variables, eg, here we instantiate Array's T to U,
     // and when we call f, we instantiate U to boolean.
     // /**
     //  * @template U
     //  * @param {!Array<U>} x
     //  */
     // function f(x) { return x[0]; }
     // f([true, false]);
     for (String oldKey : typeMap.keySet()) {
       builder.put(oldKey, typeMap.get(oldKey).substituteGenerics(newTypeMap));
     }
     resultMap = builder.build();
   } else {
     ImmutableList<String> typeParams = this.rawType.getTypeParameters();
     for (String newKey : typeParams) {
       if (newTypeMap.containsKey(newKey)) {
         builder.put(newKey, newTypeMap.get(newKey));
       }
     }
     resultMap = builder.build();
     if (resultMap.isEmpty()) {
       return this;
     }
     // This works around a bug in FunctionType, because we can't know where
     // FunctionType#receiverType is coming from.
     // If the condition is true, receiverType comes from a method declaration,
     // and we should not create a new type here.
     if (resultMap.size() < typeParams.size()) {
       return this;
     }
   }
   return new NominalType(resultMap, this.rawType);
 }
예제 #18
0
 /**
  * Convert the object to string using Skylark syntax. The output tries to be reversible (but
  * there is no guarantee, it depends on the actual values).
  */
 @Override
 public String toString() {
   StringBuilder builder = new StringBuilder();
   boolean first = true;
   builder.append("struct(");
   // Sort by key to ensure deterministic output.
   for (String key : Ordering.natural().sortedCopy(values.keySet())) {
     if (!first) {
       builder.append(", ");
     }
     first = false;
     builder.append(key);
     builder.append(" = ");
     Printer.write(builder, values.get(key));
   }
   builder.append(")");
   return builder.toString();
 }
  @Test
  public void integrationTestMetaData2() {
    DataServiceImpl dataServiceImpl = Mockito.mock(DataServiceImpl.class);
    MetaDataServiceImpl metaDataService = new MetaDataServiceImpl(dataServiceImpl);

    DefaultEntityMetaData newEntityMetaData = new DefaultEntityMetaData("attributes");
    newEntityMetaData.addAttribute("ID");

    List<String> skipEntities = Lists.<String>newArrayList("attributes");
    String defaultPackage = "base";
    ImmutableMap<String, EntityMetaData> newEntitiesMetaDataMap = Mockito.mock(ImmutableMap.class);
    when(newEntitiesMetaDataMap.get("attributes")).thenReturn(newEntityMetaData);
    when(newEntitiesMetaDataMap.keySet()).thenReturn(ImmutableSet.of("attributes"));

    LinkedHashMap<String, Boolean> entitiesImportable = new LinkedHashMap<String, Boolean>();
    entitiesImportable.put("attributes", true);
    assertEquals(
        metaDataService.integrationTestMetaData(
            newEntitiesMetaDataMap, skipEntities, defaultPackage),
        entitiesImportable);
  }
  @Override
  public Optional<ImmutableWorkerInfo> findWorkerForTask(
      final WorkerTaskRunnerConfig config,
      final ImmutableMap<String, ImmutableWorkerInfo> zkWorkers,
      final Task task) {
    // don't run other datasources on affinity workers; we only want our configured datasources to
    // run on them
    ImmutableMap.Builder<String, ImmutableWorkerInfo> builder = new ImmutableMap.Builder<>();
    for (String workerHost : zkWorkers.keySet()) {
      if (!affinityWorkerHosts.contains(workerHost)) {
        builder.put(workerHost, zkWorkers.get(workerHost));
      }
    }
    ImmutableMap<String, ImmutableWorkerInfo> eligibleWorkers = builder.build();

    List<String> workerHosts = affinityConfig.getAffinity().get(task.getDataSource());
    if (workerHosts == null) {
      return super.findWorkerForTask(config, eligibleWorkers, task);
    }

    ImmutableMap.Builder<String, ImmutableWorkerInfo> affinityBuilder =
        new ImmutableMap.Builder<>();
    for (String workerHost : workerHosts) {
      ImmutableWorkerInfo zkWorker = zkWorkers.get(workerHost);
      if (zkWorker != null) {
        affinityBuilder.put(workerHost, zkWorker);
      }
    }
    ImmutableMap<String, ImmutableWorkerInfo> affinityWorkers = affinityBuilder.build();

    if (!affinityWorkers.isEmpty()) {
      Optional<ImmutableWorkerInfo> retVal = super.findWorkerForTask(config, affinityWorkers, task);
      if (retVal.isPresent()) {
        return retVal;
      }
    }

    return super.findWorkerForTask(config, eligibleWorkers, task);
  }
예제 #21
0
 @Override
 public Map<String, Settings> getGroups(String settingPrefix) throws SettingsException {
   if (settingPrefix.charAt(settingPrefix.length() - 1) != '.') {
     settingPrefix = settingPrefix + ".";
   }
   // we don't really care that it might happen twice
   Map<String, Map<String, String>> map = new LinkedHashMap<String, Map<String, String>>();
   for (Object o : settings.keySet()) {
     String setting = (String) o;
     if (setting.startsWith(settingPrefix)) {
       String nameValue = setting.substring(settingPrefix.length());
       int dotIndex = nameValue.indexOf('.');
       if (dotIndex == -1) {
         throw new SettingsException(
             "Failed to get setting group for ["
                 + settingPrefix
                 + "] setting prefix and setting ["
                 + setting
                 + "] because of a missing '.'");
       }
       String name = nameValue.substring(0, dotIndex);
       String value = nameValue.substring(dotIndex + 1);
       Map<String, String> groupSettings = map.get(name);
       if (groupSettings == null) {
         groupSettings = new LinkedHashMap<String, String>();
         map.put(name, groupSettings);
       }
       groupSettings.put(value, get(setting));
     }
   }
   Map<String, Settings> retVal = new LinkedHashMap<String, Settings>();
   for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) {
     retVal.put(
         entry.getKey(),
         new ImmutableSettings(Collections.unmodifiableMap(entry.getValue()), classLoader));
   }
   return Collections.unmodifiableMap(retVal);
 }
예제 #22
0
  /**
   * This test validates that the md5sum() method returns hashes that match the official test
   * vectors specified in RFC 1321, The MD5 Message-Digest Algorithm.
   *
   * @throws Exception
   */
  @Test
  public void testValidateMd5Sum() throws Exception {
    ImmutableMap<String, String> testVectors =
        ImmutableMap.<String, String>builder()
            .put("", "d41d8cd98f00b204e9800998ecf8427e")
            .put("a", "0cc175b9c0f1b6a831c399e269772661")
            .put("abc", "900150983cd24fb0d6963f7d28e17f72")
            .put("message digest", "f96b697d7cb7938d525a2f31aaf161d0")
            .put("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b")
            .put(
                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
                "d174ab98d277d9f5a5611c2c9f419d9f")
            .put(
                "12345678901234567890123456789012345678901234567890123456789012345678901234567890",
                "57edf4a22be3c955ac49da2e2107b67a")
            .build();

    for (String testInput : testVectors.keySet()) {
      FileSystemUtils.writeContentAsLatin1(testFile, testInput);
      HashCode result = NativePosixFiles.md5sum(testFile.getPathString());
      assertThat(testVectors).containsEntry(testInput, result.toString());
    }
  }
예제 #23
0
    private void installNativeLibrariesForAbi(String abi, ImmutableMap<String, Path> libraries)
        throws Exception {
      if (libraries.isEmpty()) {
        return;
      }

      ImmutableSet<String> requiredHashes = libraries.keySet();
      ImmutableSet<String> presentHashes = prepareNativeLibsDir(abi, requiredHashes);

      Map<String, Path> filesToInstallByHash =
          Maps.filterKeys(libraries, Predicates.not(Predicates.in(presentHashes)));

      String metadataContents =
          Joiner.on('\n')
              .join(
                  FluentIterable.from(libraries.entrySet())
                      .transform(
                          new Function<Map.Entry<String, Path>, String>() {
                            @Override
                            public String apply(Map.Entry<String, Path> input) {
                              String hash = input.getKey();
                              String filename = input.getValue().getFileName().toString();
                              int index = filename.indexOf('.');
                              String libname =
                                  index == -1 ? filename : filename.substring(0, index);
                              return String.format("%s native-%s.so", libname, hash);
                            }
                          }));

      installFiles(
          "native_library",
          ImmutableMap.copyOf(filesToInstallByHash),
          metadataContents,
          "native-%s.so",
          NATIVE_LIBS_DIR.resolve(abi));
    }
예제 #24
0
 public GameAILoader() {
   _finder = new ClassAIFinder();
   _classes = _finder.getAIClasses(AI.class, "ch.hesso");
   ImmutableMap.Builder<String, AI> builder = ImmutableMap.builder();
   for (Class<? extends AI> ai : _classes) {
     try {
       AI instance = ai.newInstance();
       instance.initialize(GameController.this);
       if (instance.kind().equals(PLAYER)) {
         _default = instance;
         _defaultAIName = instance.name();
       }
       builder.put(instance.name(), instance);
       initClassFields(ai, instance);
     } catch (InstantiationException | IllegalAccessException e) {
       LOG.log(Level.SEVERE, "[GameController.GameAILoader.GameAILoader]: " + e.getMessage());
     }
   }
   _ais = builder.build();
   if (_default == null && _ais.size() > 0) {
     _default = _ais.values().asList().get(0);
     _defaultAIName = _ais.keySet().asList().get(0);
   }
 }
예제 #25
0
 /** Implements {@link FileSystem#supportedFileAttributeViews()}. */
 public ImmutableSet<String> supportedFileAttributeViews() {
   return providersByName.keySet();
 }
예제 #26
0
 public Iterator<String> iterator() {
   return vals.keySet().iterator();
 }
예제 #27
0
 public Set<Integer> longsIndeces() {
   return longPositions.keySet();
 }
예제 #28
0
 /** Returns the (immutable, unordered) set of names of all the known rule classes. */
 public Set<String> getRuleClassNames() {
   return ruleClassMap.keySet();
 }
예제 #29
0
  @Override
  public HttpRequest filter(HttpRequest request) throws HttpException {
    checkArgument(
        request.getHeaders().containsKey(HOST), "request is not ready to sign; host not present");
    String host = request.getFirstHeaderOrNull(HOST);
    String form = request.getPayload().getRawContent().toString();
    checkArgument(
        form.indexOf(ACTION) != -1, "request is not ready to sign; Action not present %s", form);

    String timestamp = iso8601Timestamp.get();
    String datestamp = timestamp.substring(0, 8);

    String service = serviceAndRegion.service();
    String region = serviceAndRegion.region(host);
    String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request");

    // content-type is not a required signing param. However, examples use this, so we include it to
    // ease testing.
    ImmutableMap.Builder<String, String> signedHeadersBuilder =
        ImmutableMap.<String, String>builder() //
            .put("content-type", request.getPayload().getContentMetadata().getContentType()) //
            .put("host", host) //
            .put("x-amz-date", timestamp);

    HttpRequest.Builder<?> requestBuilder =
        request
            .toBuilder() //
            .removeHeader(AUTHORIZATION) //
            .replaceHeader("X-Amz-Date", timestamp);

    if (form.indexOf(VERSION) == -1) {
      requestBuilder.addFormParam("Version", apiVersion);
    }

    Credentials credentials = creds.get();

    if (credentials instanceof SessionCredentials) {
      String token = SessionCredentials.class.cast(credentials).getSessionToken();
      requestBuilder.replaceHeader("X-Amz-Security-Token", token);
      signedHeadersBuilder.put("x-amz-security-token", token);
    }

    ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build();

    String stringToSign =
        createStringToSign(requestBuilder.build(), signedHeaders, credentialScope);
    byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service);
    String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey));

    StringBuilder authorization = new StringBuilder("AWS4-HMAC-SHA256 ");
    authorization
        .append("Credential=")
        .append(credentials.identity)
        .append('/')
        .append(credentialScope)
        .append(", ");
    authorization
        .append("SignedHeaders=")
        .append(Joiner.on(';').join(signedHeaders.keySet()))
        .append(", ");
    authorization.append("Signature=").append(signature);

    return requestBuilder.addHeader(AUTHORIZATION, authorization.toString()).build();
  }
 public Iterator<String> iterator() {
   return params.keySet().iterator();
 }