Search in sources :

Example 56 with ImmutableList

use of com.google.common.collect.ImmutableList in project auto by google.

the class BuilderMethodClassifier method copyOfMethods.

/**
   * Returns {@code copyOf} methods from the given type. These are static methods called
   * {@code copyOf} with a single parameter. All of Guava's concrete immutable collection types have
   * at least one such method, but we will also accept other classes with an appropriate method,
   * such as {@link java.util.EnumSet}.
   */
private ImmutableList<ExecutableElement> copyOfMethods(TypeMirror targetType) {
    if (!targetType.getKind().equals(TypeKind.DECLARED)) {
        return ImmutableList.of();
    }
    String copyOf = Optionalish.isOptional(targetType) ? "of" : "copyOf";
    TypeElement immutableTargetType = MoreElements.asType(typeUtils.asElement(targetType));
    ImmutableList.Builder<ExecutableElement> copyOfMethods = ImmutableList.builder();
    for (ExecutableElement method : ElementFilter.methodsIn(immutableTargetType.getEnclosedElements())) {
        if (method.getSimpleName().contentEquals(copyOf) && method.getParameters().size() == 1 && method.getModifiers().contains(Modifier.STATIC)) {
            copyOfMethods.add(method);
        }
    }
    return copyOfMethods.build();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) ImmutableList(com.google.common.collect.ImmutableList) ExecutableElement(javax.lang.model.element.ExecutableElement)

Example 57 with ImmutableList

use of com.google.common.collect.ImmutableList in project auto by google.

the class Reparser method removeSpaceBeforeSet.

/**
   * Returns a copy of the given list where spaces have been moved where appropriate after {@code
   * #set}. This hack is needed to match what appears to be special treatment in Apache Velocity of
   * spaces before {@code #set} directives. If you have <i>thing</i> <i>whitespace</i> {@code #set},
   * then the whitespace is deleted if the <i>thing</i> is a comment ({@code ##...\n}); a reference
   * ({@code $x} or {@code $x.foo} etc); a macro definition; or another {@code #set}.
   */
private static ImmutableList<Node> removeSpaceBeforeSet(ImmutableList<Node> nodes) {
    assert Iterables.getLast(nodes) instanceof EofNode;
    // Since the last node is EofNode, the i + 1 and i + 2 accesses below are safe.
    ImmutableList.Builder<Node> newNodes = ImmutableList.builder();
    for (int i = 0; i < nodes.size(); i++) {
        Node nodeI = nodes.get(i);
        newNodes.add(nodeI);
        if (shouldDeleteSpaceBetweenThisAndSet(nodeI) && isWhitespaceLiteral(nodes.get(i + 1)) && nodes.get(i + 2) instanceof SetNode) {
            // Skip the space.
            i++;
        }
    }
    return newNodes.build();
}
Also used : SetNode(com.google.auto.value.processor.escapevelocity.DirectiveNode.SetNode) EofNode(com.google.auto.value.processor.escapevelocity.TokenNode.EofNode) ImmutableList(com.google.common.collect.ImmutableList) ForEachNode(com.google.auto.value.processor.escapevelocity.DirectiveNode.ForEachNode) IfNode(com.google.auto.value.processor.escapevelocity.DirectiveNode.IfNode) MacroCallNode(com.google.auto.value.processor.escapevelocity.DirectiveNode.MacroCallNode) ForEachTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.ForEachTokenNode) ElseIfTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.ElseIfTokenNode) SetNode(com.google.auto.value.processor.escapevelocity.DirectiveNode.SetNode) Node.emptyNode(com.google.auto.value.processor.escapevelocity.Node.emptyNode) EndTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.EndTokenNode) EofNode(com.google.auto.value.processor.escapevelocity.TokenNode.EofNode) CommentTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.CommentTokenNode) IfTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.IfTokenNode) ElseTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.ElseTokenNode) IfOrElseIfTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.IfOrElseIfTokenNode) MacroDefinitionTokenNode(com.google.auto.value.processor.escapevelocity.TokenNode.MacroDefinitionTokenNode)

Example 58 with ImmutableList

use of com.google.common.collect.ImmutableList in project buck by facebook.

the class OfflineScribeLoggerTest method unsentLinesStoredForOffline.

@Test
public void unsentLinesStoredForOffline() throws Exception {
    final String whitelistedCategory = "whitelisted_category";
    final String whitelistedCategory2 = "whitelisted_category_2";
    final String blacklistedCategory = "blacklisted_category";
    final ImmutableList<String> blacklistCategories = ImmutableList.of(blacklistedCategory);
    final int maxScribeOfflineLogsKB = 7;
    final ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot());
    final Path logDir = filesystem.getBuckPaths().getOfflineLogDir();
    final ObjectMapper objectMapper = ObjectMappers.newDefaultInstance();
    String[] ids = { "test1", "test2", "test3", "test4" };
    char[] longLineBytes = new char[1000];
    Arrays.fill(longLineBytes, 'A');
    String longLine = new String(longLineBytes);
    char[] tooLongLineBytes = new char[6000];
    Arrays.fill(longLineBytes, 'A');
    String tooLongLine = new String(tooLongLineBytes);
    // As we set max space for logs to 7KB, then we expect storing data with 2 'longLine' (which,
    // given UTF-8 is used, will be ~ 2 * 1KB) to succeed. We then expect subsequent attempt to
    // store data with 'tooLongLine' (~6KB) to fail. We also expect that logfile created by first
    // fakeLogger ('test1' id) will be removed as otherwise data from last logger would not fit.
    //
    // Note that code sending already stored offline logs will be triggered by the first log() as
    // it succeeds, but further failing log() (and initiating storing) will stop sending. Hence, no
    // logs will be deleted due to the sending routine.
    FakeFailingOfflineScribeLogger fakeLogger = null;
    for (String id : ids) {
        fakeLogger = new FakeFailingOfflineScribeLogger(blacklistCategories, maxScribeOfflineLogsKB, filesystem, logDir, objectMapper, new BuildId(id));
        // Simulate network issues occurring for some of sending attempts (all after first one).
        // Logging succeeds.
        fakeLogger.log(whitelistedCategory, ImmutableList.of("hello world 1", "hello world 2"));
        // Logging fails.
        fakeLogger.log(whitelistedCategory, ImmutableList.of("hello world 3", "hello world 4"));
        // Event with blacklisted category for offline logging.
        fakeLogger.log(blacklistedCategory, ImmutableList.of("hello world 5", "hello world 6"));
        // Logging fails.
        fakeLogger.log(whitelistedCategory2, ImmutableList.of(longLine, longLine));
        // Logging fails, but offline logging rejects data as well - too big.
        fakeLogger.log(whitelistedCategory2, ImmutableList.of(tooLongLine));
        fakeLogger.close();
    }
    // Check correct logs are in the directory (1st log removed).
    Path[] expectedLogPaths = FluentIterable.from(ImmutableList.copyOf(ids)).transform(id -> filesystem.resolve(logDir.resolve(LOGFILE_PREFIX + id + LOGFILE_SUFFIX))).toArray(Path.class);
    ImmutableSortedSet<Path> logs = filesystem.getMtimeSortedMatchingDirectoryContents(logDir, LOGFILE_PATTERN);
    assertThat(logs, Matchers.allOf(hasItem(expectedLogPaths[1]), hasItem(expectedLogPaths[2]), hasItem(expectedLogPaths[3]), IsIterableWithSize.<Path>iterableWithSize(3)));
    // Check that last logger logged correct data.
    assertEquals(3, fakeLogger.getAttemptStoringCategoriesWithLinesCount());
    InputStream logFile = fakeLogger.getStoredLog();
    String[] whitelistedCategories = { whitelistedCategory, whitelistedCategory2 };
    String[][] whitelistedLines = { { "hello world 3", "hello world 4" }, { longLine, longLine } };
    Iterator<ScribeData> it = null;
    try {
        it = new ObjectMapper().readValues(new JsonFactory().createParser(logFile), ScribeData.class);
    } catch (Exception e) {
        fail("Obtaining iterator for reading the log failed.");
    }
    int dataNum = 0;
    try {
        while (it.hasNext()) {
            assertTrue(dataNum < 2);
            ScribeData data = it.next();
            assertThat(data.getCategory(), is(whitelistedCategories[dataNum]));
            assertThat(data.getLines(), Matchers.allOf(hasItem(whitelistedLines[dataNum][0]), hasItem(whitelistedLines[dataNum][1]), IsIterableWithSize.<String>iterableWithSize(2)));
            dataNum++;
        }
    } catch (Exception e) {
        fail("Reading stored offline log failed.");
    }
    logFile.close();
    assertEquals(2, dataNum);
}
Also used : Path(java.nio.file.Path) LOGFILE_PREFIX(com.facebook.buck.util.network.offline.OfflineScribeLogger.LOGFILE_PREFIX) Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ObjectMappers(com.facebook.buck.util.ObjectMappers) LOGFILE_SUFFIX(com.facebook.buck.util.network.offline.OfflineScribeLogger.LOGFILE_SUFFIX) TemporaryPaths(com.facebook.buck.testutil.integration.TemporaryPaths) BuckEventBusFactory(com.facebook.buck.event.BuckEventBusFactory) Matchers.arrayContainingInAnyOrder(org.hamcrest.Matchers.arrayContainingInAnyOrder) BufferedOutputStream(java.io.BufferedOutputStream) ArrayList(java.util.ArrayList) Assert.assertThat(org.junit.Assert.assertThat) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) Matchers.everyItem(org.hamcrest.Matchers.everyItem) ImmutableList(com.google.common.collect.ImmutableList) BuildId(com.facebook.buck.model.BuildId) FluentIterable(com.google.common.collect.FluentIterable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Is.is(org.hamcrest.core.Is.is) ScribeLogger(com.facebook.buck.util.network.ScribeLogger) Assert.fail(org.junit.Assert.fail) LOGFILE_PATTERN(com.facebook.buck.util.network.offline.OfflineScribeLogger.LOGFILE_PATTERN) Pair(com.facebook.buck.model.Pair) Path(java.nio.file.Path) ImmutableSortedSet(com.google.common.collect.ImmutableSortedSet) Charsets(com.google.common.base.Charsets) ObjectArrays(com.google.common.collect.ObjectArrays) Iterator(java.util.Iterator) FakeFailingScribeLogger(com.facebook.buck.util.network.FakeFailingScribeLogger) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Assert.assertTrue(org.junit.Assert.assertTrue) Matchers(org.hamcrest.Matchers) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Futures(com.google.common.util.concurrent.Futures) List(java.util.List) Matchers.hasItem(org.hamcrest.Matchers.hasItem) JsonFactory(com.fasterxml.jackson.core.JsonFactory) Rule(org.junit.Rule) IsIterableWithSize(org.hamcrest.collection.IsIterableWithSize) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) JsonFactory(com.fasterxml.jackson.core.JsonFactory) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BuildId(com.facebook.buck.model.BuildId) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 59 with ImmutableList

use of com.google.common.collect.ImmutableList in project buck by facebook.

the class SrcZipAwareFileBundlerTest method bundleFiles.

public void bundleFiles(ImmutableSortedSet<SourcePath> immutableSortedSet) throws IOException {
    ImmutableList.Builder<Step> immutableStepList = ImmutableList.builder();
    new File(subDirectoryFile1.toString()).getParentFile().mkdirs();
    new File(subDirectoryFile2.toString()).getParentFile().mkdirs();
    new File(subDirectoryFile3.toString()).getParentFile().mkdirs();
    Files.createFile(subDirectoryFile1);
    Files.createFile(subDirectoryFile2);
    Files.createFile(subDirectoryFile3);
    SrcZipAwareFileBundler bundler = new SrcZipAwareFileBundler(basePath);
    bundler.copy(filesystem, new SourcePathResolver(new SourcePathRuleFinder(new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer()))), immutableStepList, dest, immutableSortedSet);
    ImmutableList<Step> builtStepList = immutableStepList.build();
    for (Step step : builtStepList) {
        try {
            step.execute(TestExecutionContext.newInstance());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Also used : ImmutableList(com.google.common.collect.ImmutableList) Step(com.facebook.buck.step.Step) DefaultTargetNodeToBuildRuleTransformer(com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer) File(java.io.File) SourcePathResolver(com.facebook.buck.rules.SourcePathResolver) SourcePathRuleFinder(com.facebook.buck.rules.SourcePathRuleFinder) BuildRuleResolver(com.facebook.buck.rules.BuildRuleResolver)

Example 60 with ImmutableList

use of com.google.common.collect.ImmutableList in project buck by facebook.

the class TypesTest method shouldReturnFirstNonOptionalTypeOfAField.

@Test
public void shouldReturnFirstNonOptionalTypeOfAField() throws NoSuchFieldException {
    @SuppressWarnings("unused")
    class Contained {

        public Optional<ImmutableList<? extends String>> wildCardList;

        public Optional<ImmutableList<String>> list;

        public Optional<String> raw;

        public ImmutableList<? extends String> expectedWildCardType;

        public ImmutableList<String> expectedListType;
    }
    Field field = Contained.class.getField("wildCardList");
    Field expected = Contained.class.getField("expectedWildCardType");
    assertEquals(expected.getGenericType(), Types.getFirstNonOptionalType(field));
    field = Contained.class.getField("list");
    expected = Contained.class.getField("expectedListType");
    assertEquals(expected.getGenericType(), Types.getFirstNonOptionalType(field));
    field = Contained.class.getField("raw");
    assertEquals(String.class, Types.getFirstNonOptionalType(field));
}
Also used : Field(java.lang.reflect.Field) Optional(java.util.Optional) ImmutableList(com.google.common.collect.ImmutableList) Test(org.junit.Test)

Aggregations

ImmutableList (com.google.common.collect.ImmutableList)552 Path (java.nio.file.Path)130 List (java.util.List)112 SourcePath (com.facebook.buck.rules.SourcePath)91 Test (org.junit.Test)78 Step (com.facebook.buck.step.Step)76 ImmutableMap (com.google.common.collect.ImmutableMap)69 IOException (java.io.IOException)64 ArrayList (java.util.ArrayList)63 Map (java.util.Map)62 ExplicitBuildTargetSourcePath (com.facebook.buck.rules.ExplicitBuildTargetSourcePath)52 MakeCleanDirectoryStep (com.facebook.buck.step.fs.MakeCleanDirectoryStep)52 BuildTarget (com.facebook.buck.model.BuildTarget)47 ImmutableSet (com.google.common.collect.ImmutableSet)44 MkdirStep (com.facebook.buck.step.fs.MkdirStep)39 Arguments (com.spectralogic.ds3autogen.api.models.Arguments)38 Optional (java.util.Optional)38 SourcePathResolver (com.facebook.buck.rules.SourcePathResolver)36 HumanReadableException (com.facebook.buck.util.HumanReadableException)36 HashMap (java.util.HashMap)35