Search in sources :

Example 41 with Stream

use of java.util.stream.Stream in project L42 by ElvisResearchGroup.

the class Desugar method visit.

public Expression visit(ClassB s) {
    Position pos = s.getP();
    assert !(s.getH() instanceof ConcreteHeader);
    if (!s.getFields().isEmpty()) {
        List<Member> ms = s.getFields().stream().flatMap(f -> Desugar.field(pos, f)).collect(Collectors.toList());
        ms.addAll(s.getMs());
        s = s.withMs(ms).withH(new Ast.TraitHeader());
    }
    Set<String> oldUsedVars = this.usedVars;
    HashMap<String, Type> oldVarEnv = this.varEnv;
    try {
        s = (ClassB) super.visit(s);
        s = FlatFirstLevelLocalNestedClasses.of(s, this);
        s = DesugarCatchDefault.of(s);
        return s;
    } finally {
        this.usedVars = oldUsedVars;
        this.varEnv = oldVarEnv;
    }
}
Also used : Stage(ast.Ast.Stage) VarDecXE(ast.Ast.VarDecXE) X(ast.Expression.X) Ast(ast.Ast) FieldDec(ast.Ast.FieldDec) Parameters(ast.Ast.Parameters) Catch1(ast.Expression.Catch1) Catch(ast.Expression.Catch) SquareWithCall(ast.Expression.SquareWithCall) ErrorMessage(ast.ErrorMessage) Type(ast.Ast.Type) Configuration(facade.Configuration) FCall(ast.Expression.FCall) SquareCall(ast.Expression.SquareCall) ConcreteHeader(ast.Ast.ConcreteHeader) MethodWithType(ast.Expression.ClassB.MethodWithType) MethodSelector(ast.Ast.MethodSelector) Visitor(coreVisitors.Visitor) BinOp(ast.Expression.BinOp) InjectionOnSugar(coreVisitors.InjectionOnSugar) Op(ast.Ast.Op) SignalKind(ast.Ast.SignalKind) Loop(ast.Expression.Loop) OnLineCode(platformSpecific.fakeInternet.OnLineCode) RoundBlock(ast.Expression.RoundBlock) TypeManipulation(newTypeSystem.TypeManipulation) Set(java.util.Set) MethodSelectorX(ast.Ast.MethodSelectorX) With(ast.Expression.With) Collectors(java.util.stream.Collectors) List(java.util.List) Stream(java.util.stream.Stream) UseSquare(ast.Expression.UseSquare) While(ast.Expression.While) ClassReuse(ast.Expression.ClassReuse) VarDecCE(ast.Ast.VarDecCE) EncodingHelper(auxiliaryGrammar.EncodingHelper) Optional(java.util.Optional) Timer(profiling.Timer) L42(facade.L42) Expression._void(ast.Expression._void) Program(programReduction.Program) Header(ast.Ast.Header) Using(ast.Expression.Using) Member(ast.Expression.ClassB.Member) HashMap(java.util.HashMap) Assertions(tools.Assertions) MethodType(ast.Ast.MethodType) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) PathMxMx(ast.Util.PathMxMx) RefreshUniqueNames(privateMangling.RefreshUniqueNames) MCall(ast.Expression.MCall) If(ast.Expression.If) Literal(ast.Expression.Literal) UnOp(ast.Expression.UnOp) IsCompiled(coreVisitors.IsCompiled) Mdf(ast.Ast.Mdf) VarDec(ast.Ast.VarDec) Path(ast.Ast.Path) DocE(ast.Expression.DocE) Doc(ast.Ast.Doc) VarDecE(ast.Ast.VarDecE) ExpCore(ast.ExpCore) Expression(ast.Expression) ClassB(ast.Expression.ClassB) Functions(auxiliaryGrammar.Functions) CatchMany(ast.Expression.CatchMany) CurlyBlock(ast.Expression.CurlyBlock) Position(ast.Ast.Position) MethodImplemented(ast.Expression.ClassB.MethodImplemented) PathAux(ast.PathAux) Collections(java.util.Collections) NestedClass(ast.Expression.ClassB.NestedClass) Type(ast.Ast.Type) MethodWithType(ast.Expression.ClassB.MethodWithType) MethodType(ast.Ast.MethodType) Position(ast.Ast.Position) Member(ast.Expression.ClassB.Member) ConcreteHeader(ast.Ast.ConcreteHeader)

Example 42 with Stream

use of java.util.stream.Stream in project jdk8u_jdk by JetBrains.

the class StreamZipEntriesTest method testClosedZipFile.

@Test
public void testClosedZipFile() throws IOException {
    ZipFile zf = new ZipFile(new File(System.getProperty("test.src", "."), "input.zip"));
    zf.close();
    try {
        Stream s = zf.stream();
        fail("Should have thrown IllegalStateException");
    } catch (IllegalStateException e) {
    // expected;
    }
}
Also used : ZipFile(java.util.zip.ZipFile) Stream(java.util.stream.Stream) JarFile(java.util.jar.JarFile) File(java.io.File) ZipFile(java.util.zip.ZipFile) Test(org.testng.annotations.Test)

Example 43 with Stream

use of java.util.stream.Stream in project jdk8u_jdk by JetBrains.

the class ConcurrentAssociateTest method testOnce.

private static void testOnce(String desc, BiConsumer<ConcurrentMap<Object, Object>, Object> associator) {
    ConcurrentHashMap<Object, Object> m = new ConcurrentHashMap<>();
    CountDownLatch s = new CountDownLatch(1);
    Supplier<Runnable> sr = () -> () -> {
        try {
            s.await();
        } catch (InterruptedException e) {
        }
        for (int i = 0; i < N; i++) {
            Object o = new X();
            associator.accept(m, o);
            if (!m.containsKey(o)) {
                throw new AssociationFailure(desc + " failed: entry does not exist");
            }
        }
    };
    int ps = Runtime.getRuntime().availableProcessors();
    Stream<CompletableFuture> runners = IntStream.range(0, ps).mapToObj(i -> sr.get()).map(CompletableFuture::runAsync);
    CompletableFuture all = CompletableFuture.allOf(runners.toArray(CompletableFuture[]::new));
    // Trigger the runners to start associating
    s.countDown();
    try {
        all.join();
    } catch (CompletionException e) {
        Throwable t = e.getCause();
        if (t instanceof AssociationFailure) {
            throw (AssociationFailure) t;
        } else {
            throw e;
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Test(org.testng.annotations.Test) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) Supplier(java.util.function.Supplier) ConcurrentMap(java.util.concurrent.ConcurrentMap) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) BiConsumer(java.util.function.BiConsumer) CountDownLatch(java.util.concurrent.CountDownLatch) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 44 with Stream

use of java.util.stream.Stream in project jdk8u_jdk by JetBrains.

the class CountTest method testOps.

@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOps(String name, TestData.OfRef<Integer> data) {
    AtomicLong expectedCount = new AtomicLong();
    data.stream().forEach(e -> expectedCount.incrementAndGet());
    withData(data).terminal(Stream::count).expectedResult(expectedCount.get()).exercise();
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) IntStream(java.util.stream.IntStream) LongStream(java.util.stream.LongStream) Stream(java.util.stream.Stream) DoubleStream(java.util.stream.DoubleStream) Test(org.testng.annotations.Test)

Example 45 with Stream

use of java.util.stream.Stream in project MantaroBot by Mantaro.

the class PollLobby method startPoll.

public void startPoll() {
    try {
        if (!isCompilant) {
            getChannel().sendMessage(EmoteReference.WARNING + "This poll cannot build. " + "**Remember that the maximum amount of options are 9, the minimum is 2 and that the maximum timeout is 10m and the minimum timeout is 30s.**\n" + "Options are separated with a comma, for example `1,2,3`. For spaced stuff use commas at the start and end of the sentence.").queue();
            getRunningPolls().remove(getChannel());
            return;
        }
        if (isPollAlreadyRunning(getChannel())) {
            getChannel().sendMessage(EmoteReference.WARNING + "There seems to be another poll running here...").queue();
            return;
        }
        if (!event.getGuild().getSelfMember().hasPermission(getChannel(), Permission.MESSAGE_ADD_REACTION)) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Seems like I cannot add reactions here...").queue();
            getRunningPolls().remove(getChannel());
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData data = dbGuild.getData();
        AtomicInteger at = new AtomicInteger();
        data.setRanPolls(data.getRanPolls() + 1L);
        dbGuild.save();
        String toShow = Stream.of(options).map(opt -> String.format("#%01d.- %s", at.incrementAndGet(), opt)).collect(Collectors.joining("\n"));
        EmbedBuilder builder = new EmbedBuilder().setAuthor(String.format("Poll #%1d created by %s", data.getRanPolls(), event.getAuthor().getName()), null, event.getAuthor().getAvatarUrl()).setDescription("**Poll started. React to the number to vote.**\n*" + name + "*").addField("Options", "```md\n" + toShow + "```", false).setColor(event.getMember().getColor()).setThumbnail("https://cdn.pixabay.com/photo/2012/04/14/16/26/question-34499_960_720.png").setFooter("You have " + Utils.getDurationMinutes(timeout) + " minutes to vote.", event.getAuthor().getAvatarUrl());
        getChannel().sendMessage(builder.build()).queue(message -> ReactionOperations.create(message, TimeUnit.MILLISECONDS.toSeconds(timeout), new ReactionOperation() {

            @Override
            public boolean run(MessageReactionAddEvent e) {
                int i = e.getReactionEmote().getName().charAt(0) - '0';
                if (i < 1 || i > options.length)
                    return false;
                return false;
            }

            @Override
            public void onExpire() {
                EmbedBuilder embedBuilder = new EmbedBuilder().setTitle("Poll results").setDescription("**Showing results for the poll started by " + event.getAuthor().getName() + "** with name: *" + name + "*").setFooter("Thanks for your vote", null);
                AtomicInteger react = new AtomicInteger(0);
                AtomicInteger counter = new AtomicInteger(0);
                String votes = new ArrayList<>(getChannel().getMessageById(message.getIdLong()).complete().getReactions()).stream().filter(r -> react.getAndIncrement() <= options.length).map(r -> "+Registered " + (r.getCount() - 1) + " votes for option " + options[counter.getAndIncrement()]).collect(Collectors.joining("\n"));
                embedBuilder.addField("Results", "```diff\n" + votes + "```", false);
                event.getChannel().sendMessage(embedBuilder.build()).queue();
            }
        }, reactions(options.length)));
    } catch (Exception e) {
        getChannel().sendMessage(EmoteReference.ERROR + "An unknown error has occurred while setting up a poll. Maybe try again?").queue();
    }
}
Also used : MessageReactionAddEvent(net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Utils(net.kodehawa.mantarobot.utils.Utils) HashMap(java.util.HashMap) Collectors(java.util.stream.Collectors) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Lobby(net.kodehawa.mantarobot.commands.interaction.Lobby) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Stream(java.util.stream.Stream) Permission(net.dv8tion.jda.core.Permission) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Map(java.util.Map) ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperation) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Assert(org.junit.Assert) ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperation) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageReactionAddEvent(net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList)

Aggregations

Stream (java.util.stream.Stream)161 Collectors (java.util.stream.Collectors)98 List (java.util.List)89 ArrayList (java.util.ArrayList)66 Map (java.util.Map)66 Set (java.util.Set)59 IOException (java.io.IOException)58 Optional (java.util.Optional)45 Collections (java.util.Collections)43 HashMap (java.util.HashMap)43 Arrays (java.util.Arrays)33 HashSet (java.util.HashSet)33 File (java.io.File)32 Path (java.nio.file.Path)32 Function (java.util.function.Function)28 Logger (org.slf4j.Logger)26 LoggerFactory (org.slf4j.LoggerFactory)26 java.util (java.util)25 Predicate (java.util.function.Predicate)23 Objects (java.util.Objects)22