Example usage for java.util.concurrent RecursiveTask RecursiveTask

List of usage examples for java.util.concurrent RecursiveTask RecursiveTask

Introduction

In this page you can find the example usage for java.util.concurrent RecursiveTask RecursiveTask.

Prototype

RecursiveTask

Source Link

Usage

From source file:com.kegare.caveworld.world.WorldProviderDeepCaveworld.java

public static void regenerate(final boolean backup) {
    final File dir = getDimDir();
    final String name = dir.getName().substring(4);
    final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    Set<EntityPlayerMP> target = Sets.newHashSet();

    for (Object obj : server.getConfigurationManager().playerEntityList.toArray()) {
        if (obj != null && ((EntityPlayerMP) obj).dimension == CaveworldAPI.getDeepDimension()) {
            target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0));
        }// w  ww  .j av a  2s. c  om
    }

    boolean result = new ForkJoinPool().invoke(new RecursiveTask<Boolean>() {
        @Override
        protected Boolean compute() {
            IChatComponent component;

            try {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerating", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                if (server.isSinglePlayer()) {
                    Caveworld.network.sendToAll(new RegenerateMessage(backup));
                }

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(0));

                CaveBlocks.caveworld_portal.portalDisabled = true;

                int dim = CaveworldAPI.getDeepDimension();
                WorldServer world = DimensionManager.getWorld(dim);

                if (world != null) {
                    world.saveAllChunks(true, null);
                    world.flush();

                    MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(world));

                    DimensionManager.setWorld(dim, null);
                }

                if (dir != null) {
                    if (backup) {
                        File parent = dir.getParentFile();
                        final Pattern pattern = Pattern.compile("^" + dir.getName() + "_bak-..*\\.zip$");
                        File[] files = parent.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                return pattern.matcher(name).matches();
                            }
                        });

                        if (files != null && files.length >= 5) {
                            Arrays.sort(files, new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    int i = CaveUtils.compareWithNull(o1, o2);

                                    if (i == 0 && o1 != null && o2 != null) {
                                        try {
                                            i = Files.getLastModifiedTime(o1.toPath())
                                                    .compareTo(Files.getLastModifiedTime(o2.toPath()));
                                        } catch (IOException e) {
                                        }
                                    }

                                    return i;
                                }
                            });

                            FileUtils.forceDelete(files[0]);
                        }

                        Calendar calendar = Calendar.getInstance();
                        String year = Integer.toString(calendar.get(Calendar.YEAR));
                        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
                        String day = String.format("%02d", calendar.get(Calendar.DATE));
                        String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
                        String minute = String.format("%02d", calendar.get(Calendar.MINUTE));
                        String second = String.format("%02d", calendar.get(Calendar.SECOND));
                        File bak = new File(parent,
                                dir.getName() + "_bak-" + Joiner.on("").join(year, month, day) + "-"
                                        + Joiner.on("").join(hour, minute, second) + ".zip");

                        if (bak.exists()) {
                            FileUtils.deleteQuietly(bak);
                        }

                        component = new ChatComponentText(StatCollector
                                .translateToLocalFormatted("caveworld.regenerate.backingup", name));
                        component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                        server.getConfigurationManager().sendChatMsg(component);

                        Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(1));

                        if (CaveUtils.archiveDirZip(dir, bak)) {
                            ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_FILE,
                                    FilenameUtils.normalize(bak.getParentFile().getPath()));

                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backedup", name));
                            component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true)
                                    .setChatClickEvent(click);
                            server.getConfigurationManager().sendChatMsg(component);
                        } else {
                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backup.failed", name));
                            component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                            server.getConfigurationManager().sendChatMsg(component);
                        }
                    }

                    FileUtils.deleteDirectory(dir);
                }

                if (DimensionManager.shouldLoadSpawn(dim)) {
                    DimensionManager.initDimension(dim);

                    world = DimensionManager.getWorld(dim);

                    if (world != null) {
                        world.saveAllChunks(true, null);
                        world.flush();
                    }
                }

                CaveBlocks.caveworld_portal.portalDisabled = false;

                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerated", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(2));

                return true;
            } catch (Exception e) {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.failed", name));
                component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(3));

                CaveLog.log(Level.ERROR, e, component.getUnformattedText());
            }

            return false;
        }
    });

    if (result && (Config.hardcore || Config.caveborn)) {
        for (EntityPlayerMP player : target) {
            if (!CaveworldAPI.isEntityInCaveworld(player)) {
                CaveUtils.forceTeleport(player, CaveworldAPI.getDeepDimension());
            }
        }
    }
}

From source file:com.oembedler.moon.graphql.engine.execute.GraphQLExecutorServiceRxExecutionStrategy.java

public ExecutionResult doExecute(ExecutionContext executionContext, GraphQLObjectType parentType, Object source,
        Map<String, List<Field>> fields) {

    Map<String, RecursiveTask<ExecutionResult>> recursiveTaskMap = new LinkedHashMap<String, RecursiveTask<ExecutionResult>>();
    for (String fieldName : fields.keySet()) {
        final List<Field> fieldList = fields.get(fieldName);
        RecursiveTask<ExecutionResult> resolveField = new RecursiveTask<ExecutionResult>() {
            @Override//from   w w  w  .  j  ava  2s .c om
            protected ExecutionResult compute() {
                return resolveField(executionContext, parentType, source, fieldList);
            }
        };
        resolveField.fork();
        recursiveTaskMap.put(fieldName, resolveField);
    }

    List<Observable<Pair<String, Object>>> observablesResult = new ArrayList<>();
    List<Observable<Double>> observablesComplexity = new ArrayList<>();

    for (String fieldName : recursiveTaskMap.keySet()) {
        List<Field> fieldList = fields.get(fieldName);
        ExecutionResult executionResult = recursiveTaskMap.get(fieldName).join();

        observablesResult.add(unwrapExecutionResult(fieldName, executionResult));
        observablesComplexity.add(calculateFieldComplexity(executionContext, parentType, fieldList,
                executionResult != null ? ((GraphQLRxExecutionResult) executionResult).getComplexityObservable()
                        : Observable.just(0.0)));

    }

    Observable<Map<String, Object>> result = Observable.merge(observablesResult).toMap(Pair::getLeft,
            Pair::getRight);

    GraphQLRxExecutionResult graphQLRxExecutionResult = new GraphQLRxExecutionResult(result,
            Observable.just(executionContext.getErrors()),
            MathObservable.sumDouble(Observable.merge(observablesComplexity)));
    return graphQLRxExecutionResult;
}

From source file:io.kamax.mxisd.lookup.provider.DnsLookupProvider.java

@Override
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
    Map<String, List<ThreePidMapping>> domains = new HashMap<>();

    for (ThreePidMapping mapping : mappings) {
        if (!ThreePidMedium.Email.is(mapping.getMedium())) {
            log.info("Skipping unsupported type {} for {}", mapping.getMedium(), mapping.getValue());
            continue;
        }/*from   w  w  w  . ja  v  a 2  s. c o  m*/

        Optional<String> domainOpt = getDomain(mapping.getValue());
        if (!domainOpt.isPresent()) {
            log.warn("No domain for 3PID {}", mapping.getValue());
            continue;
        }

        String domain = domainOpt.get();
        List<ThreePidMapping> domainMappings = domains.computeIfAbsent(domain, s -> new ArrayList<>());
        domainMappings.add(mapping);
    }

    log.info("Looking mappings across {} domains", domains.keySet().size());
    ForkJoinPool pool = ForkJoinPool.commonPool();
    RecursiveTask<List<ThreePidMapping>> task = new RecursiveTask<List<ThreePidMapping>>() {

        @Override
        protected List<ThreePidMapping> compute() {
            List<ThreePidMapping> mappingsFound = new ArrayList<>();
            List<DomainBulkLookupTask> tasks = new ArrayList<>();

            for (String domain : domains.keySet()) {
                DomainBulkLookupTask domainTask = new DomainBulkLookupTask(domain, domains.get(domain));
                domainTask.fork();
                tasks.add(domainTask);
            }

            for (DomainBulkLookupTask task : tasks) {
                mappingsFound.addAll(task.join());
            }

            return mappingsFound;
        }
    };
    pool.submit(task);
    pool.shutdown();

    List<ThreePidMapping> mappingsFound = task.join();
    log.info("Found {} mappings overall", mappingsFound.size());
    return mappingsFound;
}

From source file:com.kegare.caveworld.world.WorldProviderCaveworld.java

public static void regenerate(final boolean backup) {
    final File dir = getDimDir();
    final String name = dir.getName().substring(4);
    final MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
    Set<EntityPlayerMP> target = Sets.newHashSet();

    for (Object obj : server.getConfigurationManager().playerEntityList.toArray()) {
        if (obj != null && ((EntityPlayerMP) obj).dimension == CaveworldAPI.getDimension()) {
            target.add(CaveUtils.respawnPlayer((EntityPlayerMP) obj, 0));
        }/*w w w .ja  v  a  2 s .  co  m*/
    }

    boolean result = new ForkJoinPool().invoke(new RecursiveTask<Boolean>() {
        @Override
        protected Boolean compute() {
            IChatComponent component;

            try {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerating", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                if (server.isSinglePlayer()) {
                    Caveworld.network.sendToAll(new RegenerateMessage(backup));
                }

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(0));

                CaveBlocks.caveworld_portal.portalDisabled = true;

                int dim = CaveworldAPI.getDimension();
                WorldServer world = DimensionManager.getWorld(dim);

                if (world != null) {
                    world.saveAllChunks(true, null);
                    world.flush();

                    MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(world));

                    DimensionManager.setWorld(dim, null);
                }

                if (dir != null) {
                    if (backup) {
                        File parent = dir.getParentFile();
                        final Pattern pattern = Pattern.compile("^" + dir.getName() + "_bak-..*\\.zip$");
                        File[] files = parent.listFiles(new FilenameFilter() {
                            @Override
                            public boolean accept(File dir, String name) {
                                return pattern.matcher(name).matches();
                            }
                        });

                        if (files != null && files.length >= 5) {
                            Arrays.sort(files, new Comparator<File>() {
                                @Override
                                public int compare(File o1, File o2) {
                                    int i = CaveUtils.compareWithNull(o1, o2);

                                    if (i == 0 && o1 != null && o2 != null) {
                                        try {
                                            i = Files.getLastModifiedTime(o1.toPath())
                                                    .compareTo(Files.getLastModifiedTime(o2.toPath()));
                                        } catch (IOException e) {
                                        }
                                    }

                                    return i;
                                }
                            });

                            FileUtils.forceDelete(files[0]);
                        }

                        Calendar calendar = Calendar.getInstance();
                        String year = Integer.toString(calendar.get(Calendar.YEAR));
                        String month = String.format("%02d", calendar.get(Calendar.MONTH) + 1);
                        String day = String.format("%02d", calendar.get(Calendar.DATE));
                        String hour = String.format("%02d", calendar.get(Calendar.HOUR_OF_DAY));
                        String minute = String.format("%02d", calendar.get(Calendar.MINUTE));
                        String second = String.format("%02d", calendar.get(Calendar.SECOND));
                        File bak = new File(parent,
                                dir.getName() + "_bak-" + Joiner.on("").join(year, month, day) + "-"
                                        + Joiner.on("").join(hour, minute, second) + ".zip");

                        if (bak.exists()) {
                            FileUtils.deleteQuietly(bak);
                        }

                        component = new ChatComponentText(StatCollector
                                .translateToLocalFormatted("caveworld.regenerate.backingup", name));
                        component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                        server.getConfigurationManager().sendChatMsg(component);

                        Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(1));

                        if (CaveUtils.archiveDirZip(dir, bak)) {
                            ClickEvent click = new ClickEvent(ClickEvent.Action.OPEN_FILE,
                                    FilenameUtils.normalize(bak.getParentFile().getPath()));

                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backedup", name));
                            component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true)
                                    .setChatClickEvent(click);
                            server.getConfigurationManager().sendChatMsg(component);
                        } else {
                            component = new ChatComponentText(StatCollector
                                    .translateToLocalFormatted("caveworld.regenerate.backup.failed", name));
                            component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                            server.getConfigurationManager().sendChatMsg(component);
                        }
                    }

                    FileUtils.deleteDirectory(dir);
                }

                if (DimensionManager.shouldLoadSpawn(dim)) {
                    DimensionManager.initDimension(dim);

                    world = DimensionManager.getWorld(dim);

                    if (world != null) {
                        world.saveAllChunks(true, null);
                        world.flush();
                    }
                }

                CaveBlocks.caveworld_portal.portalDisabled = false;

                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.regenerated", name));
                component.getChatStyle().setColor(EnumChatFormatting.GRAY).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(2));

                return true;
            } catch (Exception e) {
                component = new ChatComponentText(
                        StatCollector.translateToLocalFormatted("caveworld.regenerate.failed", name));
                component.getChatStyle().setColor(EnumChatFormatting.RED).setItalic(true);
                server.getConfigurationManager().sendChatMsg(component);

                Caveworld.network.sendToAll(new RegenerateMessage.ProgressNotify(3));

                CaveLog.log(Level.ERROR, e, component.getUnformattedText());
            }

            return false;
        }
    });

    if (result && (Config.hardcore || Config.caveborn)) {
        for (EntityPlayerMP player : target) {
            if (!CaveworldAPI.isEntityInCaveworld(player)) {
                CaveUtils.forceTeleport(player, CaveworldAPI.getDimension());
            }
        }
    }
}