Exemplo n.º 1
0
  @Override
  public <T> Set<T> eval(QueryEnvironment<T> env, ImmutableList<Argument> args, Executor executor)
      throws QueryException, InterruptedException {
    QueryExpression from = args.get(0).getExpression();
    QueryExpression to = args.get(1).getExpression();

    Set<T> fromSet = from.eval(env, executor);
    Set<T> toSet = to.eval(env, executor);

    // Algorithm:
    // 1) compute "reachableFromX", the forward transitive closure of the "from" set;
    // 2) find the intersection of "reachableFromX" with the "to" set, and traverse the graph using
    //    the reverse dependencies. This will effectively compute the intersection between the nodes
    //    reachable from the "from" set and the reverse transitive closure of the "to" set.

    env.buildTransitiveClosure(fromSet, Integer.MAX_VALUE, executor);

    Set<T> reachableFromX = env.getTransitiveClosure(fromSet);
    Set<T> result = MoreSets.intersection(reachableFromX, toSet);
    Collection<T> worklist = result;
    while (!worklist.isEmpty()) {
      Collection<T> reverseDeps = env.getReverseDeps(worklist);
      worklist = Lists.newArrayList();
      for (T target : reverseDeps) {
        if (reachableFromX.contains(target) && result.add(target)) {
          worklist.add(target);
        }
      }
    }
    return result;
  }
Exemplo n.º 2
0
  @Override
  public <T> Set<T> eval(
      QueryEnvironment<T> env, ImmutableList<Argument> args, ListeningExecutorService executor)
      throws QueryException, InterruptedException {
    QueryExpression argument = args.get(args.size() - 1).getExpression();
    String attr = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, args.get(0).getWord());

    final String attrValue = args.get(1).getWord();
    final Predicate<Object> predicate =
        new Predicate<Object>() {
          @Override
          public boolean apply(Object input) {
            return attrValue.equals(input.toString());
          }
        };

    Set<T> result = new LinkedHashSet<>();
    for (T target : argument.eval(env, executor)) {
      ImmutableSet<Object> matchingObjects = env.filterAttributeContents(target, attr, predicate);
      if (!matchingObjects.isEmpty()) {
        result.add(target);
      }
    }
    return result;
  }
Exemplo n.º 3
0
 private static ImmutableMap<String, String> getQueryMap(final String query)
     throws MalformedRequestException {
   if (StringUtils.isBlank(query)) {
     return ImmutableMap.of();
   } else {
     final Iterable<String> params = Splitter.on('&').split(query);
     final ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
     for (final String param : params) {
       final ImmutableList<String> strings = ImmutableList.copyOf(Splitter.on('=').split(param));
       final String name = strings.get(0);
       if (strings.size() > 2) {
         throw new MalformedRequestException("Multiple '=' for parameter " + name);
       }
       final String value;
       if (strings.size() > 1) {
         value = strings.get(1);
       } else {
         value = null;
       }
       if (map.build().keySet().contains(name)) {
         throw new MalformedRequestException("Duplicate value for parameter " + name);
       }
       map.put(name, value);
     }
     return map.build();
   }
 }
Exemplo n.º 4
0
  @Test
  public void ensureFilesInSubdirectoriesAreKeptInSubDirectories() throws IOException {
    BuildRuleResolver ruleResolver = new BuildRuleResolver();

    BuildTarget target = BuildTargetFactory.newInstance("//:example");
    Genrule rule =
        ruleResolver.buildAndAddToIndex(
            Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
                .setRelativeToAbsolutePathFunctionForTesting(relativeToAbsolutePathFunction)
                .setBuildTarget(target)
                .setBash(Optional.of("ignored"))
                .addSrc("in-dir.txt")
                .addSrc("foo/bar.html")
                .addSrc("other/place.txt")
                .setOut("example-file"));

    ImmutableList.Builder<Step> builder = ImmutableList.builder();
    rule.addSymlinkCommands(builder);
    ImmutableList<Step> commands = builder.build();

    String baseTmpPath = GEN_DIR + "/example__srcs/";

    assertEquals(3, commands.size());
    MkdirAndSymlinkFileStep linkCmd = (MkdirAndSymlinkFileStep) commands.get(0);
    assertEquals("in-dir.txt", linkCmd.getSource());
    assertEquals(baseTmpPath + "in-dir.txt", linkCmd.getTarget());

    linkCmd = (MkdirAndSymlinkFileStep) commands.get(1);
    assertEquals("foo/bar.html", linkCmd.getSource());
    assertEquals(baseTmpPath + "foo/bar.html", linkCmd.getTarget());

    linkCmd = (MkdirAndSymlinkFileStep) commands.get(2);
    assertEquals("other/place.txt", linkCmd.getSource());
    assertEquals(baseTmpPath + "other/place.txt", linkCmd.getTarget());
  }
Exemplo n.º 5
0
  private void createAndroidBinaryRuleAndTestCopyNativeLibraryCommand(
      ImmutableSet<String> cpuFilters,
      String sourceDir,
      String destinationDir,
      ImmutableList<String> expectedShellCommands) {
    BuildRuleResolver ruleResolver = new BuildRuleResolver();
    AndroidBinaryRule.Builder builder =
        AndroidBinaryRule.newAndroidBinaryRuleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance("//:fbandroid_with_dash_debug_fbsign"))
            .setManifest("AndroidManifest.xml")
            .setKeystore(addKeystoreRule(ruleResolver))
            .setTarget("Google Inc:Google APIs:16");

    for (String filter : cpuFilters) {
      builder.addCpuFilter(filter);
    }

    ImmutableList.Builder<Step> commands = ImmutableList.builder();
    AndroidBinaryRule buildRule = ruleResolver.buildAndAddToIndex(builder);
    buildRule.copyNativeLibrary(sourceDir, destinationDir, commands);

    ImmutableList<Step> steps = commands.build();

    assertEquals(steps.size(), expectedShellCommands.size());
    ExecutionContext context = createMock(ExecutionContext.class);
    replay(context);

    for (int i = 0; i < steps.size(); ++i) {
      Iterable<String> observedArgs = ((BashStep) steps.get(i)).getShellCommand(context);
      String observedCommand = Joiner.on(' ').join(observedArgs);
      assertEquals(expectedShellCommands.get(i), observedCommand);
    }

    verify(context);
  }
Exemplo n.º 6
0
 @Override
 public void forEach(BiConsumer<? super K, ? super V> action) {
   checkNotNull(action);
   ImmutableList<K> keyList = keySet.asList();
   for (int i = 0; i < size(); i++) {
     action.accept(keyList.get(i), valueList.get(i));
   }
 }
Exemplo n.º 7
0
  private static String getSingleAttribute(String attribute) {
    ImmutableList<String> attributeNames = getAttributeNames(attribute);

    if (attributeNames.size() != 1 || ALL_ATTRIBUTES.equals(attributeNames.get(0))) {
      throw new IllegalArgumentException("must specify a single attribute: " + attribute);
    }

    return attributeNames.get(0);
  }
Exemplo n.º 8
0
 /**
  * Checks if this trade is cross-currency.
  *
  * <p>A cross currency swap is defined as one with legs in two different currencies.
  *
  * @return true if cross currency
  */
 public boolean isCrossCurrency() {
   // optimized for performance
   Currency firstCurrency = legs.get(0).getCurrency();
   for (int i = 1; i < legs.size(); i++) {
     if (!legs.get(i).getCurrency().equals(firstCurrency)) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 9
0
 public static String removeParent(final String parentPath, final String childPath) {
   checkArgument(isChild(parentPath, childPath));
   ImmutableList<String> parent = split(parentPath);
   ImmutableList<String> child = split(childPath);
   child = child.subList(parent.size(), child.size());
   String strippedChildPath = child.get(0);
   for (int i = 1; i < child.size(); i++) {
     appendChild(strippedChildPath, child.get(i));
   }
   return strippedChildPath;
 }
Exemplo n.º 10
0
  /**
   * This method builds a (linear) tree from a single path.
   *
   * <p>Note that, while this is just a special case of {@link #buildTreeFromMultiplePaths}, this is
   * the preferred way, because the given path could come from any analysis, e.g., a predicate
   * analysis, and the exact given path should be used for interpolation. This is not guaranteed by
   * the more general approach given in {@link #buildTreeFromMultiplePaths}, because there the
   * interpolation tree is build from a (non-unambiguous) set of states.
   */
  private ARGState buildTreeFromSinglePath(final ARGPath targetPath) {
    ImmutableList<ARGState> states = targetPath.asStatesList();

    for (int i = 0; i < states.size() - 1; i++) {
      ARGState predecessorState = states.get(i);

      ARGState successorState = states.get(i + 1);
      predecessorRelation.put(successorState, predecessorState);
      successorRelation.put(predecessorState, successorState);
    }

    return states.get(0);
  }
Exemplo n.º 11
0
  @Test
  public void traverseWithPair() throws NoSuchFieldException {
    Type type = TestFields.class.getField("pairOfPathsAndStrings").getGenericType();
    TypeCoercer<?> coercer = typeCoercerFactory.typeCoercerForType(type);

    TestTraversal traversal = new TestTraversal();
    ImmutableList<?> input = ImmutableList.of("foo", "bar");
    coercer.traverse(input, traversal);
    assertThat(
        traversal.getObjects(),
        Matchers.<Object>contains(
            ImmutableList.of(sameInstance(input.get(0)), sameInstance(input.get(1)))));
  }
 @Test(dataProvider = "tailSeries")
 public void test_tailSeries(int count, int[] expected) {
   LocalDateDoubleTimeSeries base =
       LocalDateDoubleTimeSeries.builder().putAll(DATES_2010_14, VALUES_10_14).build();
   LocalDateDoubleTimeSeries test = base.tailSeries(count);
   assertEquals(test.size(), expected.length);
   for (int i = 0; i < DATES_2010_14.size(); i++) {
     if (Arrays.binarySearch(expected, i) >= 0) {
       assertEquals(test.get(DATES_2010_14.get(i)), OptionalDouble.of(VALUES_10_14.get(i)));
     } else {
       assertEquals(test.get(DATES_2010_14.get(i)), OptionalDouble.empty());
     }
   }
 }
Exemplo n.º 13
0
  @Override
  void validate(final ValidationEnvironment env) throws EvalException {
    ValidationEnvironment localEnv = new ValidationEnvironment(env);
    FunctionSignature sig = signature.getSignature();
    FunctionSignature.Shape shape = sig.getShape();
    ImmutableList<String> names = sig.getNames();
    List<Expression> defaultExpressions = signature.getDefaultValues();

    int positionals = shape.getPositionals();
    int mandatoryPositionals = shape.getMandatoryPositionals();
    int namedOnly = shape.getNamedOnly();
    int mandatoryNamedOnly = shape.getMandatoryNamedOnly();
    boolean starArg = shape.hasStarArg();
    boolean kwArg = shape.hasKwArg();
    int named = positionals + namedOnly;
    int args = named + (starArg ? 1 : 0) + (kwArg ? 1 : 0);
    int startOptionals = mandatoryPositionals;
    int endOptionals = named - mandatoryNamedOnly;

    int j = 0; // index for the defaultExpressions
    for (int i = 0; i < args; i++) {
      String name = names.get(i);
      if (startOptionals <= i && i < endOptionals) {
        defaultExpressions.get(j++).validate(env);
      }
      localEnv.declare(name, getLocation());
    }
    for (Statement stmts : statements) {
      stmts.validate(localEnv);
    }
  }
Exemplo n.º 14
0
 public void testComplexBuilder() {
   List<Integer> colorElem = asList(0x00, 0x33, 0x66, 0x99, 0xCC, 0xFF);
   ImmutableList.Builder<Integer> webSafeColorsBuilder = ImmutableList.builder();
   for (Integer red : colorElem) {
     for (Integer green : colorElem) {
       for (Integer blue : colorElem) {
         webSafeColorsBuilder.add((red << 16) + (green << 8) + blue);
       }
     }
   }
   ImmutableList<Integer> webSafeColors = webSafeColorsBuilder.build();
   assertEquals(216, webSafeColors.size());
   Integer[] webSafeColorArray = webSafeColors.toArray(new Integer[webSafeColors.size()]);
   assertEquals(0x000000, (int) webSafeColorArray[0]);
   assertEquals(0x000033, (int) webSafeColorArray[1]);
   assertEquals(0x000066, (int) webSafeColorArray[2]);
   assertEquals(0x003300, (int) webSafeColorArray[6]);
   assertEquals(0x330000, (int) webSafeColorArray[36]);
   assertEquals(0x000066, (int) webSafeColors.get(2));
   assertEquals(0x003300, (int) webSafeColors.get(6));
   ImmutableList<Integer> addedColor = webSafeColorsBuilder.add(0x00BFFF).build();
   assertEquals(
       "Modifying the builder should not have changed any already" + " built sets",
       216,
       webSafeColors.size());
   assertEquals("the new array should be one bigger than webSafeColors", 217, addedColor.size());
   Integer[] appendColorArray = addedColor.toArray(new Integer[addedColor.size()]);
   assertEquals(0x00BFFF, (int) appendColorArray[216]);
 }
 @Test(dataProvider = "invalidSlaveCount")
 public void testInvalidSlaveCount(int slaveCount, String expectedViolations) {
   operation.setNewSlaveCount(slaveCount);
   ImmutableList<String> violations = validator.validate(operation);
   assertThat(violations.size(), is(1));
   assertThat(violations.get(0), is(expectedViolations));
 }
Exemplo n.º 16
0
 @Override
 public Collection<StoreFile> getUnneededFiles(long maxTs, List<StoreFile> filesCompacting) {
   Collection<StoreFile> expiredStoreFiles = null;
   ImmutableList<StoreFile> files = storefiles;
   // 1) We can never get rid of the last file which has the maximum seqid.
   // 2) Files that are not the latest can't become one due to (1), so the rest are fair game.
   for (int i = 0; i < files.size() - 1; ++i) {
     StoreFile sf = files.get(i);
     long fileTs = sf.getReader().getMaxTimestamp();
     if (fileTs < maxTs && !filesCompacting.contains(sf)) {
       LOG.info(
           "Found an expired store file: "
               + sf.getPath()
               + " whose maxTimeStamp is "
               + fileTs
               + ", which is below "
               + maxTs);
       if (expiredStoreFiles == null) {
         expiredStoreFiles = new ArrayList<StoreFile>();
       }
       expiredStoreFiles.add(sf);
     }
   }
   return expiredStoreFiles;
 }
Exemplo n.º 17
0
  private ResponseHandler getResponseHandler(ImmutableList<ResponseHandler> list) {
    if (list.size() == 1) {
      return list.get(0);
    }

    return new AndResponseHandler(list);
  }
 @Override
 public void visit(NodeTraversal t, Node n, Node parent) {
   for (int i = 0, len = rules.size(); i < len; i++) {
     Rule rule = rules.get(i);
     rule.check(t, n);
   }
 }
Exemplo n.º 19
0
 public ArtifactCache createArtifactCache(
     Optional<String> currentWifiSsid, BuckEventBus buckEventBus) {
   ImmutableList<String> modes = getArtifactCacheModes();
   if (modes.isEmpty()) {
     return new NoopArtifactCache();
   }
   ImmutableList.Builder<ArtifactCache> builder = ImmutableList.builder();
   boolean useDistributedCache = isWifiUsableForDistributedCache(currentWifiSsid);
   try {
     for (String mode : modes) {
       switch (ArtifactCacheNames.valueOf(mode)) {
         case dir:
           ArtifactCache dirArtifactCache = createDirArtifactCache();
           buckEventBus.register(dirArtifactCache);
           builder.add(dirArtifactCache);
           break;
         case http:
           if (useDistributedCache) {
             ArtifactCache httpArtifactCache = createHttpArtifactCache(buckEventBus);
             builder.add(httpArtifactCache);
           }
           break;
       }
     }
   } catch (IllegalArgumentException e) {
     throw new HumanReadableException("Unusable cache.mode: '%s'", modes.toString());
   }
   ImmutableList<ArtifactCache> artifactCaches = builder.build();
   if (artifactCaches.size() == 1) {
     // Don't bother wrapping a single artifact cache in MultiArtifactCache.
     return artifactCaches.get(0);
   } else {
     return new MultiArtifactCache(artifactCaches);
   }
 }
Exemplo n.º 20
0
 /**
  * Translates a feature pointed by a node from its original feature type to a given one, using
  * values from those attributes that exist in both original and destination feature type. New
  * attributes are populated with null values
  *
  * @param node The node that points to the feature. No checking is performed to ensure the node
  *     points to a feature instead of other type
  * @param featureType the destination feature type
  * @return a feature with the passed feature type and data taken from the input feature
  */
 private Feature alter(NodeRef node, RevFeatureType featureType) {
   RevFeature oldFeature =
       command(RevObjectParse.class).setObjectId(node.objectId()).call(RevFeature.class).get();
   RevFeatureType oldFeatureType;
   oldFeatureType =
       command(RevObjectParse.class)
           .setObjectId(node.getMetadataId())
           .call(RevFeatureType.class)
           .get();
   ImmutableList<PropertyDescriptor> oldAttributes = oldFeatureType.sortedDescriptors();
   ImmutableList<PropertyDescriptor> newAttributes = featureType.sortedDescriptors();
   ImmutableList<Optional<Object>> oldValues = oldFeature.getValues();
   List<Optional<Object>> newValues = Lists.newArrayList();
   for (int i = 0; i < newAttributes.size(); i++) {
     int idx = oldAttributes.indexOf(newAttributes.get(i));
     if (idx != -1) {
       Optional<Object> oldValue = oldValues.get(idx);
       newValues.add(oldValue);
     } else {
       newValues.add(Optional.absent());
     }
   }
   RevFeature newFeature = RevFeature.build(ImmutableList.copyOf(newValues));
   FeatureBuilder featureBuilder = new FeatureBuilder(featureType);
   Feature feature = featureBuilder.build(node.name(), newFeature);
   return feature;
 }
Exemplo n.º 21
0
  @Test
  public void shouldBePossibleToCreateStateList() {
    ImmutableList<AddressState> addresses = createAddressList(addresses()).asStateList();

    assertThat(addresses.get(0).city, equalTo("Uppsala"));
    assertThat(addresses.get(1).city, equalTo("Stockholm"));
  }
  private Collection<List<AbstractState>> callTransferRelation(
      final CompositeState compositeState,
      final CompositePrecision compositePrecision,
      final CFAEdge cfaEdge)
      throws CPATransferException, InterruptedException {
    int resultCount = 1;
    List<AbstractState> componentElements = compositeState.getWrappedStates();
    checkArgument(
        componentElements.size() == size, "State with wrong number of component states given");
    List<Collection<? extends AbstractState>> allComponentsSuccessors = new ArrayList<>(size);

    for (int i = 0; i < size; i++) {
      TransferRelation lCurrentTransfer = transferRelations.get(i);
      AbstractState lCurrentElement = componentElements.get(i);
      Precision lCurrentPrecision = compositePrecision.get(i);

      Collection<? extends AbstractState> componentSuccessors;
      componentSuccessors =
          lCurrentTransfer.getAbstractSuccessorsForEdge(
              lCurrentElement, lCurrentPrecision, cfaEdge);
      resultCount *= componentSuccessors.size();

      if (resultCount == 0) {
        // shortcut
        break;
      }

      allComponentsSuccessors.add(componentSuccessors);
    }

    // create cartesian product of all elements we got
    return createCartesianProduct(allComponentsSuccessors, resultCount);
  }
Exemplo n.º 23
0
  @Test
  public void shouldBePossibleToCreateList() {
    ImmutableList<Address> addresses = createAddressList(addresses()).asAddressList();

    assertThat(addresses.get(0).isFromUppsala(), is(true));
    assertThat(addresses.get(1).isFromUppsala(), is(false));
  }
Exemplo n.º 24
0
 public void setTableDataAlignment(final ImmutableList<Integer> columnAlign) {
   // set alignment
   if (this.header != null && this.columnCount > 0) {
     for (int i = 0; i < this.columnCount; i++) {
       this.header[i].setDataAlign(columnAlign.get(i).shortValue());
     }
   }
 }
    @Test(dataProvider = "invalidAvailabilityZoneCreateSpecs")
    public void testInvalidAvailabilityZoneCreateSpec(
        AvailabilityZoneCreateSpec spec, String errorMsg) {
      ImmutableList<String> violations = validator.validate(spec);

      assertThat(violations.size(), is(1));
      assertThat(violations.get(0), startsWith(errorMsg));
    }
 protected void assertTestCurrency(int i, BadgerEntity<Currency> currency) {
   int j = i % NUM_CURRENCIES;
   Currency message = currency.getMessage();
   assertEquals("US Dollar" + j, message.getName());
   assertEquals(ALL_STRINGS_3_LIST.get(j), message.getAlphabeticCode());
   assertEquals(j, message.getNumericCode());
   assertEquals(2, message.getMinorUnit());
 }
Exemplo n.º 27
0
 public static int parseAndWriteBuckCompatibleDepfile(
     ExecutionContext context,
     ProjectFilesystem filesystem,
     HeaderPathNormalizer headerPathNormalizer,
     HeaderVerification headerVerification,
     Path sourceDepFile,
     Path destDepFile,
     Path inputPath,
     Path outputPath)
     throws IOException {
   // Process the dependency file, fixing up the paths, and write it out to it's final location.
   // The paths of the headers written out to the depfile are the paths to the symlinks from the
   // root of the repo if the compilation included them from the header search paths pointing to
   // the symlink trees, or paths to headers relative to the source file if the compilation
   // included them using source relative include paths. To handle both cases we check for the
   // prerequisites both in the values and the keys of the replacement map.
   Logger.get(Depfiles.class).debug("Processing dependency file %s as Makefile", sourceDepFile);
   ImmutableMap<String, Object> params =
       ImmutableMap.<String, Object>of("input", inputPath, "output", outputPath);
   try (InputStream input = filesystem.newFileInputStream(sourceDepFile);
       BufferedReader reader = new BufferedReader(new InputStreamReader(input));
       OutputStream output = filesystem.newFileOutputStream(destDepFile);
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
       SimplePerfEvent.Scope perfEvent =
           SimplePerfEvent.scope(
               context.getBuckEventBus(), PerfEventId.of("depfile-parse"), params)) {
     ImmutableList<String> prereqs = Depfiles.parseDepfile(reader).getPrereqs();
     // Skip the first prereq, as it's the input source file.
     Preconditions.checkState(inputPath.toString().equals(prereqs.get(0)));
     ImmutableList<String> headers = prereqs.subList(1, prereqs.size());
     for (String rawHeader : headers) {
       Path header = Paths.get(rawHeader).normalize();
       Optional<Path> absolutePath =
           headerPathNormalizer.getAbsolutePathForUnnormalizedPath(header);
       if (absolutePath.isPresent()) {
         Preconditions.checkState(absolutePath.get().isAbsolute());
         writer.write(absolutePath.get().toString());
         writer.newLine();
       } else if (headerVerification.getMode() != HeaderVerification.Mode.IGNORE
           && !headerVerification.isWhitelisted(header.toString())) {
         context
             .getBuckEventBus()
             .post(
                 ConsoleEvent.create(
                     headerVerification.getMode() == HeaderVerification.Mode.ERROR
                         ? Level.SEVERE
                         : Level.WARNING,
                     "%s: included an untracked header \"%s\"",
                     inputPath,
                     header));
         if (headerVerification.getMode() == HeaderVerification.Mode.ERROR) {
           return 1;
         }
       }
     }
   }
   return 0;
 }
 /** Normalizes all shard routings to the same version. */
 public IndexShardRoutingTable normalizeVersions() {
   if (shards.isEmpty()) {
     return this;
   }
   if (shards.size() == 1) {
     return this;
   }
   long highestVersion = shards.get(0).version();
   boolean requiresNormalization = false;
   for (int i = 1; i < shards.size(); i++) {
     if (shards.get(i).version() != highestVersion) {
       requiresNormalization = true;
     }
     if (shards.get(i).version() > highestVersion) {
       highestVersion = shards.get(i).version();
     }
   }
   if (!requiresNormalization) {
     return this;
   }
   List<ShardRouting> shardRoutings = new ArrayList<>(shards.size());
   for (int i = 0; i < shards.size(); i++) {
     if (shards.get(i).version() == highestVersion) {
       shardRoutings.add(shards.get(i));
     } else {
       shardRoutings.add(new ShardRouting(shards.get(i), highestVersion));
     }
   }
   return new IndexShardRoutingTable(
       shardId, ImmutableList.copyOf(shardRoutings), primaryAllocatedPostApi);
 }
  @Test
  public void blobApiBean() throws IOException {
    final Ds3SpecParser parser = new Ds3SpecParserImpl();
    final Ds3ApiSpec spec =
        parser.getSpec(Ds3SpecParserImpl_Test.class.getResourceAsStream("/specs/blobApiBean.xml"));
    assertThat(spec.getTypes().size(), is(1));

    final Ds3Type blobApiBean =
        spec.getTypes().get("com.spectralogic.s3.common.platform.domain.BulkObject");
    assertThat(blobApiBean, is(notNullValue()));

    final ImmutableList<Ds3Element> elements = blobApiBean.getElements();
    assertThat(elements.size(), is(7));
    assertThat(elements.get(0).getName(), is("InCache"));
    assertThat(elements.get(0).getNullable(), is(true));
    assertThat(elements.get(1).getName(), is("Latest"));
    assertThat(elements.get(1).getNullable(), is(false));
    assertThat(elements.get(2).getName(), is("Length"));
    assertThat(elements.get(2).getNullable(), is(false));
    assertThat(elements.get(3).getName(), is("Name"));
    assertThat(elements.get(3).getNullable(), is(true));
    assertThat(elements.get(4).getName(), is("Offset"));
    assertThat(elements.get(4).getNullable(), is(false));
    assertThat(elements.get(5).getName(), is("PhysicalPlacement"));
    assertThat(elements.get(5).getNullable(), is(true));
    assertThat(elements.get(6).getName(), is("Version"));
    assertThat(elements.get(6).getNullable(), is(false));
  }
  /** Test present value sensitivity for ISDA */
  public void test_presentValueSensitivity_ISDA() {
    RateObservationFn<RateObservation> mockObs = mock(RateObservationFn.class);
    DiscountFactors mockDf = mock(DiscountFactors.class);
    SimpleRatesProvider simpleProv = new SimpleRatesProvider(VAL_DATE, mockDf);

    ExpandedFra fraExp = FRA.expand();
    double forwardRate = 0.05;
    double discountRate = 0.015;
    double paymentTime = 0.3;
    double discountFactor = Math.exp(-discountRate * paymentTime);
    LocalDate fixingDate = FRA.getStartDate();
    PointSensitivityBuilder sens = IborRateSensitivity.of(FRA.getIndex(), fixingDate, 1d);
    when(mockDf.discountFactor(fraExp.getPaymentDate())).thenReturn(discountFactor);
    when(mockDf.zeroRatePointSensitivity(fraExp.getPaymentDate()))
        .thenReturn(
            ZeroRateSensitivity.of(
                fraExp.getCurrency(), fraExp.getPaymentDate(), -discountFactor * paymentTime));
    when(mockObs.rateSensitivity(
            fraExp.getFloatingRate(), fraExp.getStartDate(), fraExp.getEndDate(), simpleProv))
        .thenReturn(sens);
    when(mockObs.rate(fraExp.getFloatingRate(), FRA.getStartDate(), FRA.getEndDate(), simpleProv))
        .thenReturn(forwardRate);
    DiscountingFraProductPricer test = new DiscountingFraProductPricer(mockObs);
    PointSensitivities sensitivity = test.presentValueSensitivity(fraExp, simpleProv);
    double eps = 1.e-7;
    double fdDscSense = dscSensitivity(FRA, forwardRate, discountFactor, paymentTime, eps);
    double fdSense = presentValueFwdSensitivity(FRA, forwardRate, discountFactor, eps);

    ImmutableList<PointSensitivity> sensitivities = sensitivity.getSensitivities();
    assertEquals(sensitivities.size(), 2);
    IborRateSensitivity sensitivity0 = (IborRateSensitivity) sensitivities.get(0);
    assertEquals(sensitivity0.getIndex(), FRA.getIndex());
    assertEquals(sensitivity0.getFixingDate(), fixingDate);
    assertEquals(sensitivity0.getSensitivity(), fdSense, FRA.getNotional() * eps);
    ZeroRateSensitivity sensitivity1 = (ZeroRateSensitivity) sensitivities.get(1);
    assertEquals(sensitivity1.getCurrency(), FRA.getCurrency());
    assertEquals(sensitivity1.getDate(), fraExp.getPaymentDate());
    assertEquals(sensitivity1.getSensitivity(), fdDscSense, FRA.getNotional() * eps);

    // test via FraTrade
    DiscountingFraTradePricer testTrade = new DiscountingFraTradePricer(test);
    assertEquals(
        testTrade.presentValueSensitivity(FRA_TRADE, simpleProv),
        test.presentValueSensitivity(fraExp, simpleProv));
  }