예제 #1
0
  @Test
  public void testMergesAndDedupesTopicsAcrossVariants() {
    BtVodEntry btVodEntrySD = episodeRow(FULL_EPISODE_TITLE, PRODUCT_GUID);
    ParentRef parentRef = new ParentRef(BRAND_URI);
    Series series = new Series();
    series.setCanonicalUri("seriesUri");
    series.withSeriesNumber(1);

    BtVodEntry btVodEntryHD = episodeRow(FULL_EPISODE_TITLE, PRODUCT_GUID);
    btVodEntryHD.setTitle(FULL_EPISODE_TITLE + " - HD");
    btVodEntryHD.setGuid(PRODUCT_GUID + "_HD");

    when(seriesProvider.seriesFor(btVodEntrySD)).thenReturn(Optional.of(series));
    when(seriesProvider.seriesFor(btVodEntryHD)).thenReturn(Optional.of(series));

    when(imageExtractor.imagesFor(Matchers.<BtVodEntry>any())).thenReturn(ImmutableSet.<Image>of());
    when(btVodBrandProvider.brandRefFor(btVodEntrySD)).thenReturn(Optional.of(parentRef));
    when(btVodBrandProvider.brandRefFor(btVodEntryHD)).thenReturn(Optional.of(parentRef));
    when(newTopicContentMatchingPredicate.apply(isA(VodEntryAndContent.class))).thenReturn(true);
    when(kidsTopicPredicate.apply(argThat(new VodEntryHasGuid(btVodEntryHD.getGuid()))))
        .thenReturn(true);

    itemExtractor.process(btVodEntrySD);
    itemExtractor.process(btVodEntryHD);

    Item writtenItem = Iterables.getOnlyElement(itemExtractor.getProcessedItems().values());

    assertThat(writtenItem.getTopicRefs().size(), is(2));
  }
예제 #2
0
  @Test
  public void testMergesVersionsForHDandSD() {
    BtVodEntry btVodEntrySD = episodeRow(FULL_EPISODE_TITLE, PRODUCT_GUID);
    ParentRef parentRef = new ParentRef(BRAND_URI);
    Series series = new Series();
    series.setCanonicalUri("seriesUri");
    series.withSeriesNumber(1);

    BtVodEntry btVodEntryHD = episodeRow(FULL_EPISODE_TITLE, PRODUCT_GUID);
    btVodEntryHD.setTitle(FULL_EPISODE_TITLE + " - HD");
    btVodEntryHD.setGuid(PRODUCT_GUID + "_HD");

    when(seriesProvider.seriesFor(btVodEntrySD)).thenReturn(Optional.of(series));
    when(seriesProvider.seriesFor(btVodEntryHD)).thenReturn(Optional.of(series));

    when(imageExtractor.imagesFor(Matchers.<BtVodEntry>any())).thenReturn(ImmutableSet.<Image>of());
    when(btVodBrandProvider.brandRefFor(btVodEntrySD)).thenReturn(Optional.of(parentRef));
    when(btVodBrandProvider.brandRefFor(btVodEntryHD)).thenReturn(Optional.of(parentRef));

    itemExtractor.process(btVodEntrySD);
    itemExtractor.process(btVodEntryHD);

    Item writtenItem = Iterables.getOnlyElement(itemExtractor.getProcessedItems().values());

    assertThat(writtenItem.getTitle(), is(REAL_EPISODE_TITLE));
    assertThat(writtenItem.getDescription(), is(SYNOPSIS));
    assertThat(writtenItem.getContainer(), is(parentRef));

    assertThat(writtenItem.getVersions().size(), is(2));
    assertThat(writtenItem.getClips().size(), is(2));
  }
예제 #3
0
  @Test
  public void testDoesntMergeEpisodesWithSameTitleAcrossDifferentBrands() {
    BtVodEntry btVodEntry =
        episodeRow(SERIES_TITLE + ": S1 S1-E9 " + REAL_EPISODE_TITLE, PRODUCT_GUID);
    BtVodEntry btVodEntryFromDifferentSeries =
        episodeRow("A different " + SERIES_TITLE + ": S1 S1-E9 " + REAL_EPISODE_TITLE, "99999");

    ParentRef parentRef = new ParentRef(BRAND_URI);
    ParentRef parentRefDiffSeries = new ParentRef(URI_PREFIX + "brands/a-different-1234");

    Series series = new Series();
    series.setCanonicalUri("seriesUri");
    series.withSeriesNumber(1);

    when(seriesProvider.seriesFor(btVodEntry)).thenReturn(Optional.of(series));

    when(imageExtractor.imagesFor(Matchers.<BtVodEntry>any())).thenReturn(ImmutableSet.<Image>of());

    when(btVodBrandProvider.brandRefFor(btVodEntry)).thenReturn(Optional.of(parentRef));
    when(btVodBrandProvider.brandRefFor(btVodEntryFromDifferentSeries))
        .thenReturn(Optional.of(parentRefDiffSeries));
    when(seriesProvider.seriesFor(btVodEntry)).thenReturn(Optional.of(series));
    when(seriesProvider.seriesFor(btVodEntryFromDifferentSeries)).thenReturn(Optional.of(series));

    itemExtractor.process(btVodEntry);
    itemExtractor.process(btVodEntryFromDifferentSeries);

    assertThat(itemExtractor.getProcessedItems().size(), is(2));
  }
예제 #4
0
  public static void main(String args[]) {
    Card n = null;
    List<Optional<Card>> board = new ArrayList<Optional<Card>>();
    List<Optional<Card>> holeCards = new ArrayList<Optional<Card>>();
    List<Optional<Card>> opponentHoleCards = new ArrayList<Optional<Card>>();

    holeCards.add(
        Optional.of(new Card(Suit.fromFirstLetterLowerCase("s"), Rank.fromFirstLetter("14"))));
    holeCards.add(
        Optional.of(new Card(Suit.fromFirstLetterLowerCase("c"), Rank.fromFirstLetter("13"))));

    opponentHoleCards.add(
        Optional.of(new Card(Suit.fromFirstLetterLowerCase("d"), Rank.fromFirstLetter("2"))));
    opponentHoleCards.add(
        Optional.of(new Card(Suit.fromFirstLetterLowerCase("h"), Rank.fromFirstLetter("3"))));

    // board.add(Optional.of(new Card( Suit.fromFirstLetterLowerCase("s"),
    // Rank.fromFirstLetter("13"))));
    // board.add(Optional.of(new Card( Suit.fromFirstLetterLowerCase("h"),
    // Rank.fromFirstLetter("2"))));
    // board.add(Optional.of(new Card( Suit.fromFirstLetterLowerCase("h"),
    // Rank.fromFirstLetter("3"))));
    // board.add(Optional.of(new Card( Suit.fromFirstLetterLowerCase("s"),
    // Rank.fromFirstLetter("13"))));
    board.add(Optional.fromNullable(n));
    board.add(Optional.fromNullable(n));
    board.add(Optional.fromNullable(n));
    board.add(Optional.fromNullable(n));
    board.add(Optional.fromNullable(n));

    AIHelper ai = new AIHelper();
    System.out.println(ai.getWinningChance(board, holeCards, opponentHoleCards));
  }
예제 #5
0
  private Optional<Brand> getBrandWithoutChannel(ProgData progData, Timestamp updatedAt) {

    String brandId = progData.getSeriesId();
    if (Strings.isNullOrEmpty(brandId) || Strings.isNullOrEmpty(brandId.trim())) {
      return Optional.absent();
    }

    String brandUri = PaHelper.getBrandUri(brandId);
    Alias brandAlias = PaHelper.getBrandAlias(brandId);

    Maybe<Identified> possiblePrevious =
        contentResolver.findByCanonicalUris(ImmutableList.of(brandUri)).getFirstValue();

    Brand brand =
        possiblePrevious.hasValue()
            ? (Brand) possiblePrevious.requireValue()
            : new Brand(brandUri, "pa:b-" + brandId, Publisher.PA);

    brand.addAlias(brandAlias);
    brand.setTitle(progData.getTitle());
    brand.setDescription(Strings.emptyToNull(progData.getSeriesSynopsis()));
    setCertificate(progData, brand);
    setGenres(progData, brand);
    setTopicRefs(brand);

    if (isClosedBrand(Optional.of(brand))) {
      brand.setScheduleOnly(true);
    }

    brand.setLastUpdated(updatedAt.toDateTimeUTC());

    return Optional.of(brand);
  }
예제 #6
0
  public boolean refresh(final Path path) throws IOException {
    try (FileSystem fs = path.getFileSystem(new Configuration())) {
      if (_fileStatus.isPresent()) {
        Optional<FileStatus> oldStatus = this._fileStatus;
        try {
          Optional<FileStatus> newStatus = Optional.of(fs.getFileStatus(path));
          this.exists = newStatus.isPresent();

          return (oldStatus.isPresent() != this._fileStatus.isPresent()
              || oldStatus.get().getModificationTime() != newStatus.get().getModificationTime()
              || oldStatus.get().isDirectory() != newStatus.get().isDirectory()
              || oldStatus.get().getLen() != newStatus.get().getLen());
        } catch (FileNotFoundException e) {
          _fileStatus = Optional.absent();
          this.exists = false;
          return true;
        }
      } else {
        if (path.getFileSystem(new Configuration()).exists(path)) {
          _fileStatus = Optional.of(fs.getFileStatus(path));
          return true;
        } else {
          return false;
        }
      }
    }
  }
  @Test
  public void test_user_correct_hashed_password() throws Exception {

    final String providedUsername = "******";
    when(clientCredentialsData.getUsername()).thenReturn(Optional.of(providedUsername));
    final String providedPassword = "******";
    when(clientCredentialsData.getPassword()).thenReturn(Optional.of(providedPassword));
    when(clientCredentialsData.getInetAddress())
        .thenReturn(Optional.of(InetAddress.getLoopbackAddress()));

    final String filePassword = "******";
    when(configuration.getUser(providedUsername)).thenReturn(filePassword);
    when(configuration.isSalted()).thenReturn(false);
    when(configuration.isHashed()).thenReturn(true);
    final String algorithm = "SHA-512";
    when(configuration.getHashingAlgorithm()).thenReturn(algorithm);
    final int iterations = 1000000;
    when(configuration.getHashingIterations()).thenReturn(iterations);

    fileAuthenticator = new FileAuthenticator(configuration, passwordComparator);
    when(passwordComparator.validateHashedPassword(
            algorithm, providedPassword, filePassword, iterations))
        .thenReturn(true);

    FileAuthenticator fileAuthenticator = new FileAuthenticator(configuration, passwordComparator);
    final Boolean isAuthenticated = fileAuthenticator.checkCredentials(clientCredentialsData);

    assertTrue(isAuthenticated);
  }
  private Optional<Thumbnail> findBestFit(Image image, Integer width, Integer height) {
    if (width == null || height == null) {
      // First handle the case where we have only one dimension width or height
      for (Thumbnail thumbnail : image.getThumbnails()) {
        if ((thumbnail.getRatio().equals("1:0") && height == null)
            || (thumbnail.getRatio().equals("0:1") && width == null)) {
          return Optional.of(thumbnail);
        }
      }
      return Optional.absent();
    }

    // Then handle the general case where we have both dimensions width and height
    Thumbnail foundRatio = null;
    String expectedRatio = ImageUtils.imageRatio(width, height);

    for (Thumbnail thumbnail : image.getThumbnails()) {
      if (thumbnail.getRatio().equals(expectedRatio)) {
        if (thumbnail.getWidth().equals(width) && thumbnail.getHeight().equals(height)) {
          // Exact match, stop searching
          return Optional.of(thumbnail);
        } else {
          // Ratio match, keep searching
          foundRatio = thumbnail;
        }
      }
    }
    return Optional.fromNullable(foundRatio);
  }
예제 #9
0
 /**
  * Attempts to get the room this tile represents if it is one, or <code>Optional.absent()</code>
  * if it is not.
  *
  * @return an optional of the room this tile is or absent if it is not a room.
  */
 public Optional<Room> getRoom() {
   switch (this) {
     case ROOM_DINING_ROOM:
       return Optional.of(Room.DINING_ROOM);
     case ROOM_GUEST_HOUSE:
       return Optional.of(Room.GUEST_HOUSE);
     case ROOM_HALL:
       return Optional.of(Room.HALL);
     case ROOM_KITCHEN:
       return Optional.of(Room.KITCHEN);
     case ROOM_LIVING_ROOM:
       return Optional.of(Room.LIVING_ROOM);
     case ROOM_OBSERVATORY:
       return Optional.of(Room.OBSERVATORY);
     case ROOM_PATIO:
       return Optional.of(Room.PATIO);
     case ROOM_POOL:
       return Optional.of(Room.POOL);
     case ROOM_SPA:
       return Optional.of(Room.SPA);
     case ROOM_THEATRE:
       return Optional.of(Room.THEATRE);
     default:
       return Optional.absent();
   }
 }
예제 #10
0
 @Override
 /* @Nullable */
 protected Map<JvmIdentifiableElement, LightweightTypeReference> getFlattenedReassignedTypes() {
   if (flattenedReassignedTypes != null) {
     // already computed
     return flattenedReassignedTypes.orNull();
   }
   Map<JvmIdentifiableElement, LightweightTypeReference> result =
       parent.getFlattenedReassignedTypes();
   if (result == null) {
     // parent doesn't have reassigned types
     // use only locally reassigned types
     return (flattenedReassignedTypes = Optional.fromNullable(super.getFlattenedReassignedTypes()))
         .orNull();
   }
   Map<JvmIdentifiableElement, LightweightTypeReference> myReassignedTypes =
       basicGetReassignedTypes();
   if (myReassignedTypes.isEmpty()) {
     // no locally reassigned types, use result from parent which was already checked for null
     return (flattenedReassignedTypes = Optional.of(result)).orNull();
   }
   // merge parent's reassigned types and locally reassigned types
   result = Maps.newHashMap(result);
   result.putAll(myReassignedTypes);
   return (flattenedReassignedTypes = Optional.of(result)).orNull();
 }
예제 #11
0
파일: Proto.java 프로젝트: akune/immutables
    @Value.Lazy
    public Optional<AbstractDeclaring> okTypeAdaptersProvider() {
      Optional<DeclaringType> typeDefining =
          declaringType().isPresent()
              ? Optional.of(declaringType().get().associatedTopLevel())
              : Optional.<DeclaringType>absent();

      Optional<OkTypeAdaptersMirror> typeDefined =
          typeDefining.isPresent()
              ? typeDefining.get().okTypeAdapters()
              : Optional.<OkTypeAdaptersMirror>absent();

      Optional<OkTypeAdaptersMirror> packageDefined = packageOf().okTypeAdapters();

      if (packageDefined.isPresent()) {
        if (typeDefined.isPresent()) {
          report()
              .withElement(typeDefining.get().element())
              .annotationNamed(OkTypeAdaptersMirror.simpleName())
              .warning(
                  "@%s is also used on the package, this type level annotation is ignored",
                  OkTypeAdaptersMirror.simpleName());
        }
        return Optional.<AbstractDeclaring>of(packageOf());
      }

      return typeDefined.isPresent()
          ? Optional.<AbstractDeclaring>of(typeDefining.get())
          : Optional.<AbstractDeclaring>absent();
    }
예제 #12
0
  @Test
  public void shouldUpdateRuleKey() throws Exception {

    @SuppressWarnings("unchecked")
    RuleKeyBuilder<RuleKey> ruleKeyBuilder = createMock(RuleKeyBuilder.class);

    expect(ruleKeyBuilder.setReflectively("minSdkVersion", Optional.of(5)))
        .andReturn(ruleKeyBuilder);
    expect(ruleKeyBuilder.setReflectively("targetSdkVersion", Optional.of(7)))
        .andReturn(ruleKeyBuilder);
    expect(ruleKeyBuilder.setReflectively("versionCode", Optional.of(11)))
        .andReturn(ruleKeyBuilder);
    expect(ruleKeyBuilder.setReflectively("versionName", Optional.of("thirteen")))
        .andReturn(ruleKeyBuilder);
    expect(ruleKeyBuilder.setReflectively("debugMode", Optional.absent()))
        .andReturn(ruleKeyBuilder);

    replay(ruleKeyBuilder);

    ManifestEntries entries =
        ManifestEntries.builder()
            .setMinSdkVersion(5)
            .setTargetSdkVersion(7)
            .setVersionCode(11)
            .setVersionName("thirteen")
            .build();

    // The appendToRuleKey should set both present and absent properties
    entries.appendToRuleKey(ruleKeyBuilder);
  }
 @Test
 public void failsToListAllWithException() throws Throwable {
   when(frontendClient.list(projectId, Project.KIND, Optional.absent(), Optional.of(1)))
       .thenThrow(new ExternalException("failed"));
   assertThat(
       listNetworks(Optional.absent(), Optional.of(1), Optional.absent()).getStatus(), is(500));
 }
  /**
   * In devstack and going forward, namespaces are being deprecated. When namespace is missing (or
   * replaced with a "fake" /fake namespace), allow matching by name and alias.
   */
  public void testPresentWhenNameSpaceIsFakeAndMatchByNameOrAlias()
      throws SecurityException, NoSuchMethodException {
    // Revert to alias
    Extension floatingIpsWithFakeNamespace =
        floatingIps.toBuilder().namespace(URI.create("http://docs.openstack.org/ext/fake")).build();

    // Revert to name
    Extension floatingIpsWithFakeNamespaceAndAlias =
        floatingIps
            .toBuilder()
            .namespace(URI.create("http://docs.openstack.org/ext/fake"))
            .alias("fake")
            .build();

    Multimap<URI, URI> aliases = ImmutableMultimap.of();

    assertEquals(
        whenExtensionsAndAliasesInRegionInclude(
                "region", ImmutableSet.of(floatingIpsWithFakeNamespace), aliases)
            .apply(getFloatingIPExtension(ImmutableList.<Object>of("region"))),
        Optional.of("foo"));

    assertEquals(
        whenExtensionsAndAliasesInRegionInclude(
                "region", ImmutableSet.of(floatingIpsWithFakeNamespaceAndAlias), aliases)
            .apply(getFloatingIPExtension(ImmutableList.<Object>of("region"))),
        Optional.of("foo"));
  }
  /**
   * Returns an {@link Optional} containing the last element in this fluent iterable. If the
   * iterable is empty, {@code Optional.absent()} is returned.
   *
   * @throws NullPointerException if the last element is null; if this is a possibility, use {@link
   *     Iterables#getLast} instead.
   */
  public final Optional<E> last() {
    // Iterables#getLast was inlined here so we don't have to throw/catch a NSEE

    // TODO(kevinb): Support a concurrently modified collection?
    if (iterable instanceof List) {
      List<E> list = (List<E>) iterable;
      if (list.isEmpty()) {
        return Optional.absent();
      }
      return Optional.of(list.get(list.size() - 1));
    }
    Iterator<E> iterator = iterable.iterator();
    if (!iterator.hasNext()) {
      return Optional.absent();
    }

    /*
     * TODO(kevinb): consider whether this "optimization" is worthwhile. Users
     * with SortedSets tend to know they are SortedSets and probably would not
     * call this method.
     */
    if (iterable instanceof SortedSet) {
      SortedSet<E> sortedSet = (SortedSet<E>) iterable;
      return Optional.of(sortedSet.last());
    }

    while (true) {
      E current = iterator.next();
      if (!iterator.hasNext()) {
        return Optional.of(current);
      }
    }
  }
  @Test
  public void succeedsToListByName() throws Throwable {
    VirtualSubnet expectedVirtualSubnet = new VirtualSubnet();
    expectedVirtualSubnet.setId(UUID.randomUUID().toString());
    expectedVirtualSubnet.setName("virtualNetwork");

    when(frontendClient.list(
            projectId, Project.KIND, Optional.of("virtualNetwork"), Optional.of(1)))
        .thenReturn(new ResourceList<>(ImmutableList.of(expectedVirtualSubnet)));

    Response response =
        listNetworks(Optional.of("virtualNetwork"), Optional.of(1), Optional.absent());
    assertThat(response.getStatus(), is(Response.Status.OK.getStatusCode()));

    ResourceList<VirtualSubnet> virtualNetworks =
        response.readEntity(new GenericType<ResourceList<VirtualSubnet>>() {});
    assertThat(virtualNetworks.getItems().size(), is(1));

    VirtualSubnet actualVirtualSubnet = virtualNetworks.getItems().get(0);
    assertThat(actualVirtualSubnet, is(expectedVirtualSubnet));

    String apiRoutePath =
        UriBuilder.fromPath(SubnetResourceRoutes.SUBNET_PATH)
            .build(expectedVirtualSubnet.getId())
            .toString();
    assertThat(actualVirtualSubnet.getSelfLink().endsWith(apiRoutePath), is(true));
    assertThat(new URI(actualVirtualSubnet.getSelfLink()).isAbsolute(), is(true));
  }
예제 #17
0
  @Test
  public void whenAndroidDirectoryResolverChangesParserInvalidated()
      throws IOException, InterruptedException {
    ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot().toPath());

    Object daemon =
        Main.getDaemon(
            new TestCellBuilder()
                .setAndroidDirectoryResolver(
                    new FakeAndroidDirectoryResolver(
                        Optional.<Path>absent(),
                        Optional.<Path>absent(),
                        Optional.<Path>absent(),
                        Optional.of("something")))
                .setFilesystem(filesystem)
                .build(),
            new ObjectMapper());

    assertNotEquals(
        "Daemon should be replaced when not equal.",
        daemon,
        Main.getDaemon(
            new TestCellBuilder()
                .setAndroidDirectoryResolver(
                    new FakeAndroidDirectoryResolver(
                        Optional.<Path>absent(),
                        Optional.<Path>absent(),
                        Optional.<Path>absent(),
                        Optional.of("different")))
                .setFilesystem(filesystem)
                .build(),
            new ObjectMapper()));
  }
  @Test
  public void depfileBasedRuleKeyRebuildsAfterChangeToUsedHeaderUsingFileRelativeInclusion()
      throws Exception {
    CxxPlatform cxxPlatform =
        DefaultCxxPlatforms.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));
    BuildTarget target = BuildTargetFactory.newInstance("//:binary_with_used_relative_header");
    String usedHeaderName = "source_relative_header.h";
    String sourceName = "source_relative_header.cpp";
    BuildTarget preprocessTarget =
        getPreprocessTarget(cxxPlatform, target, sourceName, AbstractCxxSource.Type.CXX);

    // Run the build and verify that the C++ source was preprocessed.
    workspace.runBuckBuild("--config", "build.depfiles=true", target.toString()).assertSuccess();
    BuckBuildLog.BuildLogEntry firstRunEntry =
        workspace.getBuildLog().getLogEntry(preprocessTarget);
    assertThat(
        firstRunEntry.getSuccessType(), equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));

    // Modify the used header.
    workspace.writeContentsToPath("static inline int newFunction() { return 20; }", usedHeaderName);

    // Run the build again and verify that we recompiled as the header caused the depfile rule key
    // to change.
    workspace.runBuckBuild("--config", "build.depfiles=true", target.toString()).assertSuccess();
    BuckBuildLog.BuildLogEntry secondRunEntry =
        workspace.getBuildLog().getLogEntry(preprocessTarget);
    assertThat(
        secondRunEntry.getSuccessType(), equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));

    // Also, make sure all three rule keys are actually different.
    assertThat(secondRunEntry.getRuleKey(), Matchers.not(equalTo(firstRunEntry.getRuleKey())));
  }
 @Override
 protected boolean createItem(int iD, int partIndex) {
   switch (partIndex) {
     case 0:
       ItemList.greenClothHead =
           Optional.of(
               (new ItemZuluArmor(iD, ProjectZulu_Core.desertClothMaterial, renderIndex, 0))
                   .setUnlocalizedName(
                       DefaultProps.blockKey + ":" + name[partIndex].toLowerCase()));
       return true;
     case 1:
       ItemList.greenClothChest =
           Optional.of(
               (new ItemZuluArmor(iD, ProjectZulu_Core.desertClothMaterial, renderIndex, 1))
                   .setUnlocalizedName(
                       DefaultProps.blockKey + ":" + name[partIndex].toLowerCase()));
       return true;
     case 2:
       ItemList.greenClothLeg =
           Optional.of(
               (new ItemZuluArmor(iD, ProjectZulu_Core.desertClothMaterial, renderIndex, 2))
                   .setUnlocalizedName(
                       DefaultProps.blockKey + ":" + name[partIndex].toLowerCase()));
       return true;
     case 3:
       ItemList.greenClothBoots =
           Optional.of(
               (new ItemZuluArmor(iD, ProjectZulu_Core.desertClothMaterial, renderIndex, 3))
                   .setUnlocalizedName(
                       DefaultProps.blockKey + ":" + name[partIndex].toLowerCase()));
       return true;
   }
   return false;
 }
  @Override
  public void setUpMessageQueue() {

    messageEvents.clear();

    // Standard client will start as attached

    // Cipher key success (first unlock)
    final MessageEvent event1 =
        new MessageEvent(
            MessageEventType.CIPHERED_KEY_VALUE,
            Optional.<HardwareWalletMessage>of(MessageEventFixtures.newCipheredKeyValue()),
            Optional.<Message>absent());

    messageEvents.add(event1);

    // Cipher key success (second unlock after restore)
    final MessageEvent event2 =
        new MessageEvent(
            MessageEventType.CIPHERED_KEY_VALUE,
            Optional.<HardwareWalletMessage>of(MessageEventFixtures.newCipheredKeyValue()),
            Optional.<Message>absent());

    messageEvents.add(event2);
  }
예제 #21
0
  @Test
  public final void shouldCreateCorrectOrderDates1() {
    // given
    Entity order =
        mockOrder(
            START_DATE_1.toDate(),
            START_DATE_2.toDate(),
            START_DATE_3.toDate(),
            END_DATE_1.toDate(),
            END_DATE_2.toDate(),
            END_DATE_3.toDate());

    // when
    Optional<OrderDates> maybeOrderDates = OrderDates.of(order);

    // then
    Assert.assertTrue(maybeOrderDates.isPresent());
    OrderDates orderDates = maybeOrderDates.get();

    Assert.assertEquals(START_DATE_1, orderDates.getStart().planned());
    Assert.assertEquals(Optional.of(START_DATE_2), orderDates.getStart().corrected());
    Assert.assertEquals(Optional.of(START_DATE_3), orderDates.getStart().effective());

    Assert.assertEquals(START_DATE_2, orderDates.getStart().correctedWithFallback());
    Assert.assertEquals(START_DATE_3, orderDates.getStart().effectiveWithFallback());

    Assert.assertEquals(END_DATE_1, orderDates.getEnd().planned());
    Assert.assertEquals(Optional.of(END_DATE_2), orderDates.getEnd().corrected());
    Assert.assertEquals(Optional.of(END_DATE_3), orderDates.getEnd().effective());

    Assert.assertEquals(END_DATE_2, orderDates.getEnd().correctedWithFallback());
    Assert.assertEquals(END_DATE_3, orderDates.getEnd().effectiveWithFallback());
  }
예제 #22
0
파일: HTTPTest.java 프로젝트: arnou/restx
 @Test
 public void should_find_mime_type() throws Exception {
   assertThat(HTTP.getContentTypeFromExtension("test.js"))
       .isEqualTo(Optional.of("application/x-javascript"));
   assertThat(HTTP.getContentTypeFromExtension("html")).isEqualTo(Optional.of("text/html"));
   assertThat(HTTP.getContentTypeFromExtension("css")).isEqualTo(Optional.of("text/css"));
 }
  @Test
  public void depfileBasedRuleKeyAvoidsRecompilingAfterChangeToUnusedHeader() throws Exception {
    CxxPlatform cxxPlatform =
        DefaultCxxPlatforms.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));
    BuildTarget target = BuildTargetFactory.newInstance("//:binary_with_unused_header");
    String unusedHeaderName = "unused_header.h";
    String sourceName = "source.cpp";
    BuildTarget preprocessTarget =
        getPreprocessTarget(cxxPlatform, target, sourceName, AbstractCxxSource.Type.CXX);

    // Run the build and verify that the C++ source was preprocessed.
    workspace.runBuckBuild("--config", "build.depfiles=true", target.toString()).assertSuccess();
    BuckBuildLog.BuildLogEntry firstRunEntry =
        workspace.getBuildLog().getLogEntry(preprocessTarget);
    assertThat(
        firstRunEntry.getSuccessType(), equalTo(Optional.of(BuildRuleSuccessType.BUILT_LOCALLY)));

    // Now modify the unused header.
    workspace.writeContentsToPath(
        "static inline int newFunction() { return 20; }", unusedHeaderName);

    // Run the build again and verify that got a matching depfile rule key, and therefore
    // didn't recompile.
    workspace.runBuckBuild("--config", "build.depfiles=true", target.toString()).assertSuccess();
    BuckBuildLog.BuildLogEntry secondRunEntry =
        workspace.getBuildLog().getLogEntry(preprocessTarget);
    assertThat(
        secondRunEntry.getSuccessType(),
        equalTo(Optional.of(BuildRuleSuccessType.MATCHING_DEP_FILE_RULE_KEY)));

    // Also, make sure the original rule keys are actually different.
    assertThat(secondRunEntry.getRuleKey(), Matchers.not(equalTo(firstRunEntry.getRuleKey())));
  }
예제 #24
0
 public AndroidBinaryBuilder setIntraDexReorderResources(
     boolean enableReorder, SourcePath reorderTool, SourcePath reorderData) {
   arg.reorderClassesIntraDex = Optional.of(enableReorder);
   arg.dexReorderToolFile = Optional.of(reorderTool);
   arg.dexReorderDataDumpFile = Optional.of(reorderData);
   return this;
 }
예제 #25
0
파일: GenruleTest.java 프로젝트: h87kg/buck
  @Test
  public void testShouldIncludeDxInEnvironmentIfPresent() {
    File fakeDx = new File("."); // We do no checks on whether dx is executable, but it must exist
    AndroidPlatformTarget android = EasyMock.createNiceMock(AndroidPlatformTarget.class);
    EasyMock.expect(android.getDxExecutable()).andStubReturn(fakeDx);
    EasyMock.replay(android);

    Genrule rule =
        Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance("//example:genrule"))
            .setBash(Optional.of("true"))
            .setOut("/dev/null")
            .build(new BuildRuleResolver());

    ExecutionContext context =
        ExecutionContext.builder()
            .setConsole(new TestConsole())
            .setProjectFilesystem(new ProjectFilesystem(new File(".")))
            .setAndroidPlatformTarget(Optional.of(android))
            .setEventBus(BuckEventBusFactory.newInstance())
            .setPlatform(Platform.detect())
            .build();

    ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
    rule.addEnvironmentVariables(context, builder);
    ImmutableMap<String, String> env = builder.build();

    assertEquals(fakeDx.getAbsolutePath(), env.get("DX"));

    EasyMock.verify(android);
  }
  @Test
  public void test_user_wrong_salt_hash_format() throws Exception {

    final String providedUsername = "******";
    when(clientCredentialsData.getUsername()).thenReturn(Optional.of(providedUsername));
    final String providedPassword = "******";
    when(clientCredentialsData.getPassword()).thenReturn(Optional.of(providedPassword));
    when(clientCredentialsData.getInetAddress())
        .thenReturn(Optional.of(InetAddress.getLoopbackAddress()));

    final String filePassword = "******";
    when(configuration.getUser(providedUsername)).thenReturn(filePassword);
    when(configuration.isSalted()).thenReturn(true);
    when(configuration.isHashed()).thenReturn(true);
    final String algorithm = "SHA-512";
    when(configuration.getHashingAlgorithm()).thenReturn(algorithm);
    final int iterations = 1000000;
    when(configuration.getHashingIterations()).thenReturn(iterations);

    final String salt = "salt";
    final String hash = "hash";
    HashedSaltedPassword abc = new HashedSaltedPassword(hash, salt);

    fileAuthenticator = new FileAuthenticator(configuration, passwordComparator);
    when(passwordComparator.validateHashedAndSaltedPassword(
            algorithm, providedPassword, hash, iterations, salt))
        .thenReturn(true);

    FileAuthenticatorForTest2 fileAuthenticator =
        new FileAuthenticatorForTest2(configuration, passwordComparator, abc);
    final Boolean isAuthenticated = fileAuthenticator.checkCredentials(clientCredentialsData);

    assertFalse(isAuthenticated);
  }
예제 #27
0
  public YarnService(
      Config config,
      String applicationName,
      String applicationId,
      YarnConfiguration yarnConfiguration,
      FileSystem fs,
      EventBus eventBus)
      throws Exception {
    this.applicationName = applicationName;
    this.applicationId = applicationId;

    this.config = config;

    this.eventBus = eventBus;

    this.gobblinMetrics =
        config.getBoolean(ConfigurationKeys.METRICS_ENABLED_KEY)
            ? Optional.of(buildGobblinMetrics())
            : Optional.<GobblinMetrics>absent();

    this.eventSubmitter =
        config.getBoolean(ConfigurationKeys.METRICS_ENABLED_KEY)
            ? Optional.of(buildEventSubmitter())
            : Optional.<EventSubmitter>absent();

    this.yarnConfiguration = yarnConfiguration;
    this.fs = fs;

    this.amrmClientAsync =
        closer.register(
            AMRMClientAsync.createAMRMClientAsync(1000, new AMRMClientCallbackHandler()));
    this.amrmClientAsync.init(this.yarnConfiguration);
    this.nmClientAsync =
        closer.register(NMClientAsync.createNMClientAsync(new NMClientCallbackHandler()));
    this.nmClientAsync.init(this.yarnConfiguration);

    this.initialContainers = config.getInt(GobblinYarnConfigurationKeys.INITIAL_CONTAINERS_KEY);
    this.requestedContainerMemoryMbs =
        config.getInt(GobblinYarnConfigurationKeys.CONTAINER_MEMORY_MBS_KEY);
    this.requestedContainerCores = config.getInt(GobblinYarnConfigurationKeys.CONTAINER_CORES_KEY);
    this.containerHostAffinityEnabled =
        config.getBoolean(GobblinYarnConfigurationKeys.CONTAINER_HOST_AFFINITY_ENABLED);

    this.helixInstanceMaxRetries =
        config.getInt(GobblinYarnConfigurationKeys.HELIX_INSTANCE_MAX_RETRIES);

    this.containerJvmArgs =
        config.hasPath(GobblinYarnConfigurationKeys.CONTAINER_JVM_ARGS_KEY)
            ? Optional.of(config.getString(GobblinYarnConfigurationKeys.CONTAINER_JVM_ARGS_KEY))
            : Optional.<String>absent();

    this.containerLaunchExecutor =
        Executors.newFixedThreadPool(
            10,
            ExecutorsUtils.newThreadFactory(
                Optional.of(LOGGER), Optional.of("ContainerLaunchExecutor")));

    this.tokens = getSecurityTokens();
  }
예제 #28
0
  static Optional<String> run(String[] args) {
    int argCount = args.length;

    if (argCount < 3 || argCount > 4) {
      return Optional.of(USAGE);
    }

    try {
      Logging.init();
      Logger log = Logger.getLogger(DeaggCalc.class.getName());
      Path tempLog = HazardCalc.createTempLog();
      FileHandler fh = new FileHandler(tempLog.getFileName().toString());
      fh.setFormatter(new Logging.ConsoleFormatter());
      log.getParent().addHandler(fh);

      log.info(PROGRAM + ": initializing...");
      Path modelPath = Paths.get(args[0]);
      HazardModel model = HazardModel.load(modelPath);

      CalcConfig config = model.config();
      if (argCount == 4) {
        Path userConfigPath = Paths.get(args[3]);
        config =
            CalcConfig.Builder.copyOf(model.config())
                .extend(CalcConfig.Builder.fromFile(userConfigPath))
                .build();
      }
      log.info(config.toString());

      log.info("");
      Sites sites = HazardCalc.readSites(args[1], config, log);
      log.info("Sites: " + sites);

      double returnPeriod = Double.valueOf(args[2]);

      Path out = calc(model, config, sites, returnPeriod, log);

      // transfer log and write config
      Files.move(tempLog, out.resolve(PROGRAM + ".log"));
      config.write(out);

      log.info(PROGRAM + ": finished");
      return Optional.absent();

    } catch (Exception e) {
      StringBuilder sb =
          new StringBuilder()
              .append(NEWLINE)
              .append(PROGRAM + ": error")
              .append(NEWLINE)
              .append(" Arguments: ")
              .append(Arrays.toString(args))
              .append(NEWLINE)
              .append(NEWLINE)
              .append(Throwables.getStackTraceAsString(e))
              .append(USAGE);
      return Optional.of(sb.toString());
    }
  }
예제 #29
0
파일: GenruleTest.java 프로젝트: h87kg/buck
  @Test
  public void testGetShellCommand() {
    String bash = "rm -rf /usr";
    String cmdExe = "rmdir /s /q C:\\Windows";
    String cmd = "echo \"Hello\"";
    String genruleName = "//example:genrule";
    ExecutionContext linuxExecutionContext = newEmptyExecutionContext(Platform.LINUX);
    ExecutionContext windowsExecutionContext = newEmptyExecutionContext(Platform.WINDOWS);

    // Test platform-specific
    Genrule rule =
        Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance(genruleName))
            .setBash(Optional.of(bash))
            .setCmdExe(Optional.of(cmdExe))
            .setOut("out.txt")
            .build(new BuildRuleResolver());

    ImmutableList<String> command = rule.createGenruleStep().getShellCommand(linuxExecutionContext);
    assertEquals(ImmutableList.of("/bin/bash", "-e", "-c", bash), command);

    command = rule.createGenruleStep().getShellCommand(windowsExecutionContext);
    assertEquals(ImmutableList.of("cmd.exe", "/c", cmdExe), command);

    // Test fallback
    rule =
        Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance("//example:genrule"))
            .setCmd(Optional.of(cmd))
            .setOut("out.txt")
            .build(new BuildRuleResolver());
    command = rule.createGenruleStep().getShellCommand(linuxExecutionContext);
    assertEquals(ImmutableList.of("/bin/bash", "-e", "-c", cmd), command);

    command = rule.createGenruleStep().getShellCommand(windowsExecutionContext);
    assertEquals(ImmutableList.of("cmd.exe", "/c", cmd), command);

    // Test command absent
    rule =
        Genrule.newGenruleBuilder(new FakeAbstractBuildRuleBuilderParams())
            .setBuildTarget(BuildTargetFactory.newInstance("//example:genrule"))
            .setOut("out.txt")
            .build(new BuildRuleResolver());
    try {
      rule.createGenruleStep().getShellCommand(linuxExecutionContext);
    } catch (HumanReadableException e) {
      assertEquals(
          String.format("You must specify either bash or cmd for genrule %s.", genruleName),
          e.getHumanReadableErrorMessage());
    }

    try {
      rule.createGenruleStep().getShellCommand(windowsExecutionContext);
    } catch (HumanReadableException e) {
      assertEquals(
          String.format("You must specify either cmd_exe or cmd for genrule %s.", genruleName),
          e.getHumanReadableErrorMessage());
    }
  }
예제 #30
0
 /** Generates metrics for the instrumentation of this class. */
 protected void regenerateMetrics() {
   if (isInstrumentationEnabled()) {
     this.datasetsCleanFailureMeter =
         Optional.of(this.metricContext.meter(DatasetCleanerMetrics.DATASETS_CLEAN_FAILURE));
     this.datasetsCleanSuccessMeter =
         Optional.of(this.metricContext.meter(DatasetCleanerMetrics.DATASETS_CLEAN_SUCCESS));
   }
 }