Search in sources :

Example 1 with UTF_8

use of com.google.common.base.Charsets.UTF_8 in project buck by facebook.

the class ParserTest method resolveTargetSpecsPreservesOrder.

@Test
public void resolveTargetSpecsPreservesOrder() throws Exception {
    BuildTarget foo = BuildTargetFactory.newInstance(filesystem, "//foo:foo");
    Path buckFile = cellRoot.resolve("foo/BUCK");
    Files.createDirectories(buckFile.getParent());
    Files.write(buckFile, "genrule(name='foo', out='foo', cmd='foo')".getBytes(UTF_8));
    BuildTarget bar = BuildTargetFactory.newInstance(filesystem, "//bar:bar");
    buckFile = cellRoot.resolve("bar/BUCK");
    Files.createDirectories(buckFile.getParent());
    Files.write(buckFile, "genrule(name='bar', out='bar', cmd='bar')".getBytes(UTF_8));
    ImmutableList<ImmutableSet<BuildTarget>> targets = parser.resolveTargetSpecs(eventBus, cell, false, executorService, ImmutableList.of(TargetNodePredicateSpec.of(x -> true, BuildFileSpec.fromRecursivePath(Paths.get("bar"), cell.getRoot())), TargetNodePredicateSpec.of(x -> true, BuildFileSpec.fromRecursivePath(Paths.get("foo"), cell.getRoot()))), SpeculativeParsing.of(true), ParserConfig.ApplyDefaultFlavorsMode.ENABLED);
    assertThat(targets, equalTo(ImmutableList.of(ImmutableSet.of(bar), ImmutableSet.of(foo))));
    targets = parser.resolveTargetSpecs(eventBus, cell, false, executorService, ImmutableList.of(TargetNodePredicateSpec.of(x -> true, BuildFileSpec.fromRecursivePath(Paths.get("foo"), cell.getRoot())), TargetNodePredicateSpec.of(x -> true, BuildFileSpec.fromRecursivePath(Paths.get("bar"), cell.getRoot()))), SpeculativeParsing.of(true), ParserConfig.ApplyDefaultFlavorsMode.ENABLED);
    assertThat(targets, equalTo(ImmutableList.of(ImmutableSet.of(foo), ImmutableSet.of(bar))));
}
Also used : Path(java.nio.file.Path) PathSourcePath(com.facebook.buck.rules.PathSourcePath) BroadcastEventListener(com.facebook.buck.event.listener.BroadcastEventListener) GenruleDescription(com.facebook.buck.shell.GenruleDescription) Arrays(java.util.Arrays) ObjectMappers(com.facebook.buck.util.ObjectMappers) TestDataHelper(com.facebook.buck.testutil.integration.TestDataHelper) InternalFlavor(com.facebook.buck.model.InternalFlavor) JavaLibrary(com.facebook.buck.jvm.java.JavaLibrary) Matchers.hasItems(org.hamcrest.Matchers.hasItems) Assert.assertThat(org.junit.Assert.assertThat) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) BuckConfig(com.facebook.buck.cli.BuckConfig) FluentIterable(com.google.common.collect.FluentIterable) After(org.junit.After) Map(java.util.Map) DefaultTypeCoercerFactory(com.facebook.buck.rules.coercer.DefaultTypeCoercerFactory) ParseBuckFileEvent(com.facebook.buck.json.ParseBuckFileEvent) Cell(com.facebook.buck.rules.Cell) Path(java.nio.file.Path) Parameterized(org.junit.runners.Parameterized) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) TargetGraph(com.facebook.buck.rules.TargetGraph) Collection(java.util.Collection) BuildTargetException(com.facebook.buck.model.BuildTargetException) Platform(com.facebook.buck.util.environment.Platform) BuildTarget(com.facebook.buck.model.BuildTarget) Executors(java.util.concurrent.Executors) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ConstructorArgMarshaller(com.facebook.buck.rules.ConstructorArgMarshaller) Predicate(com.google.common.base.Predicate) Matchers.equalTo(org.hamcrest.Matchers.equalTo) PathSourcePath(com.facebook.buck.rules.PathSourcePath) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) Assume.assumeTrue(org.junit.Assume.assumeTrue) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver) Matchers.containsString(org.hamcrest.Matchers.containsString) SortedMap(java.util.SortedMap) Joiner(com.google.common.base.Joiner) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) BuckEventBus(com.facebook.buck.event.BuckEventBus) UnflavoredBuildTarget(com.facebook.buck.model.UnflavoredBuildTarget) Iterables(com.google.common.collect.Iterables) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) RunWith(org.junit.runner.RunWith) WatchEventsForTests(com.facebook.buck.testutil.WatchEventsForTests) UTF_8(com.google.common.base.Charsets.UTF_8) TemporaryPaths(com.facebook.buck.testutil.integration.TemporaryPaths) BuckEventBusFactory(com.facebook.buck.event.BuckEventBusFactory) BuildRule(com.facebook.buck.rules.BuildRule) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) ImmutableList(com.google.common.collect.ImmutableList) BuildTargetFactory(com.facebook.buck.model.BuildTargetFactory) Subscribe(com.google.common.eventbus.Subscribe) BuildFileParseException(com.facebook.buck.json.BuildFileParseException) ExpectedException(org.junit.rules.ExpectedException) ActionGraphCache(com.facebook.buck.rules.ActionGraphCache) MoreCollectors(com.facebook.buck.util.MoreCollectors) Before(org.junit.Before) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) DEFAULT_BUILD_FILE_NAME(com.facebook.buck.parser.ParserConfig.DEFAULT_BUILD_FILE_NAME) Files(java.nio.file.Files) Assert.assertNotNull(org.junit.Assert.assertNotNull) HashCode(com.google.common.hash.HashCode) TargetNode(com.facebook.buck.rules.TargetNode) WatchEvent(java.nio.file.WatchEvent) WatchEventsForTests.createPathEvent(com.facebook.buck.testutil.WatchEventsForTests.createPathEvent) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) FakeBuckConfig(com.facebook.buck.cli.FakeBuckConfig) FakeBuckEventListener(com.facebook.buck.event.FakeBuckEventListener) MorePaths(com.facebook.buck.io.MorePaths) Rule(org.junit.Rule) Paths(java.nio.file.Paths) TestCellBuilder(com.facebook.buck.rules.TestCellBuilder) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Assert(org.junit.Assert) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ImmutableSet(com.google.common.collect.ImmutableSet) BuildTarget(com.facebook.buck.model.BuildTarget) UnflavoredBuildTarget(com.facebook.buck.model.UnflavoredBuildTarget) Test(org.junit.Test)

Example 2 with UTF_8

use of com.google.common.base.Charsets.UTF_8 in project nakadi by zalando.

the class AbstractZkSubscriptionClient method commitOffsets.

@Override
public List<Boolean> commitOffsets(final List<SubscriptionCursorWithoutToken> cursors, final Comparator<SubscriptionCursorWithoutToken> comparator) {
    final Map<EventTypePartition, List<SubscriptionCursorWithoutToken>> grouped = cursors.stream().collect(Collectors.groupingBy(SubscriptionCursorWithoutToken::getEventTypePartition));
    try {
        final Map<EventTypePartition, Iterator<Boolean>> committedOverall = new HashMap<>();
        for (final Map.Entry<EventTypePartition, List<SubscriptionCursorWithoutToken>> entry : grouped.entrySet()) {
            final String offsetPath = getOffsetPath(entry.getKey());
            final List<Boolean> committed;
            committed = executeWithRetry(() -> {
                final Stat stat = new Stat();
                final byte[] currentOffsetData = getCurator().getData().storingStatIn(stat).forPath(offsetPath);
                final String currentMaxOffset = new String(currentOffsetData, UTF_8);
                SubscriptionCursorWithoutToken currentMaxCursor = new SubscriptionCursorWithoutToken(entry.getKey().getEventType(), entry.getKey().getPartition(), currentMaxOffset);
                final List<Boolean> commits = Lists.newArrayList();
                for (final SubscriptionCursorWithoutToken cursor : entry.getValue()) {
                    if (comparator.compare(cursor, currentMaxCursor) > 0) {
                        currentMaxCursor = cursor;
                        commits.add(true);
                    } else {
                        commits.add(false);
                    }
                }
                if (!currentMaxCursor.getOffset().equals(currentMaxOffset)) {
                    getLog().info("Committing {} to {}", currentMaxCursor.getOffset(), offsetPath);
                    getCurator().setData().withVersion(stat.getVersion()).forPath(offsetPath, currentMaxCursor.getOffset().getBytes(Charsets.UTF_8));
                }
                return commits;
            }, new RetryForSpecifiedCountStrategy<List<Boolean>>(COMMIT_CONFLICT_RETRY_TIMES).withExceptionsThatForceRetry(KeeperException.BadVersionException.class));
            committedOverall.put(entry.getKey(), Optional.ofNullable(committed).orElse(Collections.nCopies(entry.getValue().size(), false)).iterator());
        }
        return cursors.stream().map(cursor -> committedOverall.get(cursor.getEventTypePartition()).next()).collect(Collectors.toList());
    } catch (final Exception ex) {
        throw new NakadiRuntimeException(ex);
    }
}
Also used : CreateMode(org.apache.zookeeper.CreateMode) RequestInProgressException(org.zalando.nakadi.exceptions.runtime.RequestInProgressException) Arrays(java.util.Arrays) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Session(org.zalando.nakadi.service.subscription.model.Session) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) NodeCache(org.apache.curator.framework.recipes.cache.NodeCache) InterProcessSemaphoreMutex(org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex) Stat(org.apache.zookeeper.data.Stat) MyNakadiRuntimeException1(org.zalando.nakadi.exceptions.runtime.MyNakadiRuntimeException1) UTF_8(com.google.common.base.Charsets.UTF_8) Function(java.util.function.Function) Retryer.executeWithRetry(org.echocat.jomon.runtime.concurrent.Retryer.executeWithRetry) RetryForSpecifiedCountStrategy(org.echocat.jomon.runtime.concurrent.RetryForSpecifiedCountStrategy) UnableProcessException(org.zalando.nakadi.exceptions.UnableProcessException) Lists(com.google.common.collect.Lists) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) Map(java.util.Map) OperationInterruptedException(org.zalando.nakadi.exceptions.runtime.OperationInterruptedException) Charsets(com.google.common.base.Charsets) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) Iterator(java.util.Iterator) Collection(java.util.Collection) IOException(java.io.IOException) OperationTimeoutException(org.zalando.nakadi.exceptions.runtime.OperationTimeoutException) ZookeeperException(org.zalando.nakadi.exceptions.runtime.ZookeeperException) Collectors(java.util.stream.Collectors) TimeUnit(java.util.concurrent.TimeUnit) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) Closeable(java.io.Closeable) Optional(java.util.Optional) Comparator(java.util.Comparator) Collections(java.util.Collections) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) HashMap(java.util.HashMap) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) RequestInProgressException(org.zalando.nakadi.exceptions.runtime.RequestInProgressException) UnableProcessException(org.zalando.nakadi.exceptions.UnableProcessException) ServiceUnavailableException(org.zalando.nakadi.exceptions.ServiceUnavailableException) OperationInterruptedException(org.zalando.nakadi.exceptions.runtime.OperationInterruptedException) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) OperationTimeoutException(org.zalando.nakadi.exceptions.runtime.OperationTimeoutException) ZookeeperException(org.zalando.nakadi.exceptions.runtime.ZookeeperException) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) Stat(org.apache.zookeeper.data.Stat) Iterator(java.util.Iterator) List(java.util.List) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Map(java.util.Map) KeeperException(org.apache.zookeeper.KeeperException)

Example 3 with UTF_8

use of com.google.common.base.Charsets.UTF_8 in project bookkeeper by apache.

the class BookieShellTest method setup.

@Before
public void setup() throws Exception {
    // setup the required mocks before constructing bookie shell.
    this.mockLastMarkCommand = mock(LastMarkCommand.class);
    whenNew(LastMarkCommand.class).withNoArguments().thenReturn(mockLastMarkCommand);
    this.mockSimpleTestCommand = spy(new SimpleTestCommand());
    doNothing().when(mockSimpleTestCommand).run(any(ServerConfiguration.class));
    whenNew(SimpleTestCommand.class).withNoArguments().thenReturn(mockSimpleTestCommand);
    this.mockListBookiesCommand = spy(new ListBookiesCommand());
    doNothing().when(mockListBookiesCommand).run(any(ServerConfiguration.class));
    whenNew(ListBookiesCommand.class).withNoArguments().thenReturn(mockListBookiesCommand);
    // construct the bookie shell.
    this.shell = new BookieShell(LedgerIdFormatter.LONG_LEDGERID_FORMATTER, EntryFormatter.STRING_FORMATTER);
    this.admin = PowerMockito.mock(BookKeeperAdmin.class);
    whenNew(BookKeeperAdmin.class).withParameterTypes(ClientConfiguration.class).withArguments(any(ClientConfiguration.class)).thenReturn(admin);
    this.clientConf = new ClientConfiguration();
    this.clientConf.setMetadataServiceUri("zk://127.0.0.1/path/to/ledgers");
    when(admin.getConf()).thenReturn(this.clientConf);
    this.rm = PowerMockito.mock(RegistrationManager.class);
    this.cookie = Cookie.newBuilder().setBookieHost("127.0.0.1:3181").setInstanceId("xyz").setJournalDirs("/path/to/journal/dir").setLedgerDirs("/path/to/journal/dir").setLayoutVersion(Cookie.CURRENT_COOKIE_LAYOUT_VERSION).build();
    this.version = new LongVersion(1L);
    when(rm.readCookie(anyString())).thenReturn(new Versioned<>(cookie.toString().getBytes(UTF_8), version));
    this.driver = mock(MetadataBookieDriver.class);
    when(driver.getRegistrationManager()).thenReturn(rm);
    PowerMockito.mockStatic(MetadataDrivers.class);
    PowerMockito.doAnswer(invocationOnMock -> {
        Function<RegistrationManager, Object> function = invocationOnMock.getArgument(1);
        function.apply(rm);
        return null;
    }).when(MetadataDrivers.class, "runFunctionWithRegistrationManager", any(ServerConfiguration.class), any(Function.class));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) LongVersion(org.apache.bookkeeper.versioning.LongVersion) EntryFormatter(org.apache.bookkeeper.util.EntryFormatter) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) RunWith(org.junit.runner.RunWith) LedgerMetadata(org.apache.bookkeeper.client.LedgerMetadata) UTF_8(com.google.common.base.Charsets.UTF_8) PowerMockito.verifyNew(org.powermock.api.mockito.PowerMockito.verifyNew) RecoverCmd(org.apache.bookkeeper.bookie.BookieShell.RecoverCmd) MetadataDrivers(org.apache.bookkeeper.meta.MetadataDrivers) Function(java.util.function.Function) RegistrationManager(org.apache.bookkeeper.discover.RegistrationManager) ListBookiesCommand(org.apache.bookkeeper.tools.cli.commands.cluster.ListBookiesCommand) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) BasicParser(org.apache.commons.cli.BasicParser) Versioned(org.apache.bookkeeper.versioning.Versioned) CommandLine(org.apache.commons.cli.CommandLine) Assert.fail(org.junit.Assert.fail) PowerMockito.whenNew(org.powermock.api.mockito.PowerMockito.whenNew) PowerMockRunner(org.powermock.modules.junit4.PowerMockRunner) PowerMockito(org.powermock.api.mockito.PowerMockito) Before(org.junit.Before) Set(java.util.Set) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.doNothing(org.mockito.Mockito.doNothing) Mockito.when(org.mockito.Mockito.when) Maps(com.google.common.collect.Maps) ServerConfiguration(org.apache.bookkeeper.conf.ServerConfiguration) Mockito.verify(org.mockito.Mockito.verify) Mockito.never(org.mockito.Mockito.never) LastMarkCommand(org.apache.bookkeeper.tools.cli.commands.bookie.LastMarkCommand) SimpleTestCommand(org.apache.bookkeeper.tools.cli.commands.client.SimpleTestCommand) PowerMockito.spy(org.powermock.api.mockito.PowerMockito.spy) MyCommand(org.apache.bookkeeper.bookie.BookieShell.MyCommand) ParseException(org.apache.commons.cli.ParseException) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) BookKeeperAdmin(org.apache.bookkeeper.client.BookKeeperAdmin) LedgerIdFormatter(org.apache.bookkeeper.util.LedgerIdFormatter) Assert.assertEquals(org.junit.Assert.assertEquals) SortedMap(java.util.SortedMap) MetadataBookieDriver(org.apache.bookkeeper.meta.MetadataBookieDriver) Version(org.apache.bookkeeper.versioning.Version) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ArgumentMatchers.same(org.mockito.ArgumentMatchers.same) Mockito.mock(org.mockito.Mockito.mock) MissingArgumentException(org.apache.commons.cli.MissingArgumentException) RegistrationManager(org.apache.bookkeeper.discover.RegistrationManager) SimpleTestCommand(org.apache.bookkeeper.tools.cli.commands.client.SimpleTestCommand) ServerConfiguration(org.apache.bookkeeper.conf.ServerConfiguration) MetadataBookieDriver(org.apache.bookkeeper.meta.MetadataBookieDriver) Function(java.util.function.Function) LastMarkCommand(org.apache.bookkeeper.tools.cli.commands.bookie.LastMarkCommand) ListBookiesCommand(org.apache.bookkeeper.tools.cli.commands.cluster.ListBookiesCommand) LongVersion(org.apache.bookkeeper.versioning.LongVersion) BookKeeperAdmin(org.apache.bookkeeper.client.BookKeeperAdmin) ClientConfiguration(org.apache.bookkeeper.conf.ClientConfiguration) Before(org.junit.Before)

Example 4 with UTF_8

use of com.google.common.base.Charsets.UTF_8 in project nakadi by zalando.

the class NewZkSubscriptionClient method createTopologyAndOffsets.

@Override
protected byte[] createTopologyAndOffsets(final Collection<SubscriptionCursorWithoutToken> cursors) throws Exception {
    for (final SubscriptionCursorWithoutToken cursor : cursors) {
        getCurator().create().creatingParentsIfNeeded().forPath(getOffsetPath(cursor.getEventTypePartition()), cursor.getOffset().getBytes(UTF_8));
    }
    final Partition[] partitions = cursors.stream().map(cursor -> new Partition(cursor.getEventType(), cursor.getPartition(), null, null, Partition.State.UNASSIGNED)).toArray(Partition[]::new);
    final Topology topology = new Topology(partitions, "", 0);
    getLog().info("Generating topology {}", topology);
    return objectMapper.writeValueAsBytes(topology);
}
Also used : KeeperException(org.apache.zookeeper.KeeperException) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Session(org.zalando.nakadi.service.subscription.model.Session) Collection(java.util.Collection) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) UTF_8(com.google.common.base.Charsets.UTF_8) ArrayList(java.util.ArrayList) Partition(org.zalando.nakadi.service.subscription.model.Partition) NakadiRuntimeException(org.zalando.nakadi.exceptions.NakadiRuntimeException) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Stream(java.util.stream.Stream) ImmutableList(com.google.common.collect.ImmutableList) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) ServiceTemporarilyUnavailableException(org.zalando.nakadi.exceptions.runtime.ServiceTemporarilyUnavailableException) Map(java.util.Map) SubscriptionCursorWithoutToken(org.zalando.nakadi.view.SubscriptionCursorWithoutToken) EventTypePartition(org.zalando.nakadi.domain.EventTypePartition) Partition(org.zalando.nakadi.service.subscription.model.Partition)

Aggregations

UTF_8 (com.google.common.base.Charsets.UTF_8)4 IOException (java.io.IOException)3 Collection (java.util.Collection)3 Map (java.util.Map)3 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 BuckConfig (com.facebook.buck.cli.BuckConfig)1 FakeBuckConfig (com.facebook.buck.cli.FakeBuckConfig)1 BuckEventBus (com.facebook.buck.event.BuckEventBus)1 BuckEventBusFactory (com.facebook.buck.event.BuckEventBusFactory)1 FakeBuckEventListener (com.facebook.buck.event.FakeBuckEventListener)1 BroadcastEventListener (com.facebook.buck.event.listener.BroadcastEventListener)1 MorePaths (com.facebook.buck.io.MorePaths)1 ProjectFilesystem (com.facebook.buck.io.ProjectFilesystem)1 BuildFileParseException (com.facebook.buck.json.BuildFileParseException)1 ParseBuckFileEvent (com.facebook.buck.json.ParseBuckFileEvent)1 JavaLibrary (com.facebook.buck.jvm.java.JavaLibrary)1 BuildTarget (com.facebook.buck.model.BuildTarget)1 BuildTargetException (com.facebook.buck.model.BuildTargetException)1