Example usage for org.apache.commons.lang StringUtils repeat

List of usage examples for org.apache.commons.lang StringUtils repeat

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils repeat.

Prototype

public static String repeat(String str, int repeat) 

Source Link

Document

Repeat a String repeat times to form a new String.

Usage

From source file:com.axelor.studio.service.data.exporter.ExportAsciidoc.java

private void processMenu(String menu, String view) throws IOException {

    if (menu.contains("-form(")) {
        String[] menus = menu.split("-form\\(");
        String parent = menus[0] + "-form";
        if (countMap.containsKey(parent)) {
            menu = menus[menus.length - 1];
            Integer count = countMap.get(parent);
            header += "\n\n==" + StringUtils.repeat("=", count) + " " + menu.substring(0, menu.length() - 1);
            countMap.put(view, count + 1);
        }/*  w  ww  .  j a v  a 2s.  c  om*/
    } else {
        String[] menus = menu.split("/", 4);
        int count = -1;

        header = "";
        String checkMenu = "";
        for (String mn : menus) {
            count++;
            checkMenu += mn + "/";
            if (!Strings.isNullOrEmpty(checkMenu) && !processedMenus.contains(checkMenu)) {
                processedMenus.add(checkMenu);
                header += "\n\n==" + StringUtils.repeat("=", count) + " " + mn;
                countMap.put(view, count + 1);
            }
        }
    }

    if (imgDir != null && new File(imgDir, view + ".png").exists()) {
        header += "\nimage::" + view + ".png[" + menu + ", align=\"center\"]";
    }

}

From source file:au.id.hazelwood.sos.model.user.UserValidationTest.java

@Test
public void testLastName() throws Exception {
    assertValidation("lastName", "Hazelwood");
    assertValidation("lastName", "Hazel Wood");
    assertValidation("lastName", "O'Brien-O'Connor");
    assertValidation("lastName", "Connor Tomas O'Brien");
    assertValidation("lastName", "");
    assertValidation("lastName", null);
    assertValidation("lastName", StringUtils.repeat("a", 20));
    assertValidation("lastName", StringUtils.repeat("a", 21), "size must be between 0 and 20");
    assertValidation("lastName", " ", "not a well-formed name");
    assertValidation("lastName", "-", "not a well-formed name");
    assertValidation("lastName", "A- -B", "not a well-formed name");
}

From source file:com.evolveum.midpoint.util.histogram.Histogram.java

private Object column(int count, int maxCount, int columns) {
    int bars = (int) ((double) columns * (double) count / (double) maxCount);
    if (count > 0 && bars == 0) {
        bars = 1;/*from   w ww.  j a v  a  2 s  .c  o m*/
    }
    return StringUtils.repeat("#", bars) + StringUtils.repeat(" ", columns - bars);
}

From source file:gool.generator.common.CommonCodeGenerator.java

/**
 * <pre>//from   w  ww.jav  a  2s .  co  m
 * Produce indented code in a manner similar to printf but with custom conversions.
 * %%  a single "%"
 * %s  Print an argument as a string, without indentation or newlines added.
 *     Similar to the corresponding flag of <i>String.format</i>.
 * %<i>n</i>  (where <i>n</i> is a digit)
 *     Print an argument as a bloc indented <i>n</i> times from the current indentation level.
 *     Newlines are inserted before and after the bloc.
 * %-<i>n</i> (where <i>n</i> is a digit)
 *     <i>n</i> times the indentation string, does not consumes a argument.
 *     %-0 becomes a empty string (it does nothing but is still parsed)
 * 
 * @param format
 *            the format string
 * @param arguments
 *            the objects to format, each one corresponding to a % code
 * @return the formated string
 */
protected String formatIndented(String format, Object... arguments) {
    StringBuilder sb = new StringBuilder(format);
    int pos = sb.indexOf("%");
    int arg = 0;
    while (pos != -1) {
        if (sb.charAt(pos + 1) == '%') {
            sb = sb.replace(pos, pos + 2, "%");
        } else if (sb.charAt(pos + 1) == 's') {
            sb = sb.replace(pos, pos + 2, arguments[arg].toString());
            pos += arguments[arg].toString().length() - 1;
            arg++;
        } else if (Character.isDigit(sb.charAt(pos + 1))) {
            String replacement = ("\n" + arguments[arg].toString().replaceFirst("\\s*\\z", "")).replace("\n",
                    "\n" + StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 1), 10))) + "\n";
            sb = sb.replace(pos, pos + 2, replacement);
            pos += replacement.length() - 1;
            arg++;
        } else if (sb.charAt(pos + 1) == '-' && Character.isDigit(sb.charAt(pos + 2))) {
            String replacement = StringUtils.repeat(indentation, Character.digit(sb.charAt(pos + 2), 10));
            sb = sb.replace(pos, pos + 3, replacement);
            pos += replacement.length();
        }
        pos = sb.indexOf("%", pos);
    }
    return sb.toString();
}

From source file:com.google.code.rapid.queue.FileQueueTest.java

public void testPerformance2() {
    String string = StringUtils.repeat("a", 1024);

    offer(queue, count, string);

    poll(queue, count);

    assertEquals(0, queue.size());
}

From source file:ch.threema.apitool.ConsoleMain.java

private static void usage(boolean htmlOutput) {
    if (!htmlOutput) {
        System.out.println("version:" + ConsoleMain.class.getPackage().getImplementationVersion());

        System.out.println("usage:\n");

        System.out.println("General information");
        System.out.println("-------------------\n");

        System.out.println("Where a key needs to be specified, it can either be given directly as");
        System.out.println("a command line parameter (in hex with a prefix indicating the type;");
        System.out.println("not recommended on shared machines as other users may be able to see");
        System.out.println("the arguments), or as the path to a file that it should be read from");
        System.out.println("(file contents also in hex with the prefix).\n");
    }//from   w ww  .j  a  v  a  2s  .co  m

    String groupDescriptionTemplate = htmlOutput ? "<h3>%s</h3>\n"
            : "\n%s\n" + StringUtils.repeat("-", 80) + "\n\n";
    String commandTemplate = htmlOutput ? "<pre><code>java -jar threema-msgapi-tool.jar %s</code></pre>\n"
            : "%s\n";

    for (CommandGroup commandGroup : commands.commandGroups) {
        System.out.format(groupDescriptionTemplate, commandGroup.description);

        for (ArgumentCommand argumentCommand : commandGroup.argumentCommands) {
            StringBuilder command = new StringBuilder();
            for (int n = 0; n < argumentCommand.arguments.length; n++) {
                command.append(argumentCommand.arguments[n]).append(" ");
            }
            String argumentDescription = argumentCommand.command.getUsageArguments();
            if (htmlOutput) {
                System.out.format("<h4>%s</h4>\n", argumentCommand.command.getSubject());
                argumentDescription = StringEscapeUtils.escapeHtml(argumentDescription);
            }
            command.append(argumentDescription);

            System.out.format(commandTemplate, command.toString().trim());

            String description = argumentCommand.command.getUsageDescription();
            if (htmlOutput) {
                System.out.format("<p>%s</p>\n\n", description);
            } else {
                System.out.println("   " + WordUtils.wrap(description, 76, "\n   ", false));
                System.out.println("");
            }
        }
    }
}

From source file:net.polydawn.mdm.Plumbing.java

public static boolean fetch(Repository repo, MdmModuleDependency module) throws ConfigInvalidException,
        MdmRepositoryIOException, MdmRepositoryStateException, MdmException, IOException {
    switch (module.getStatus().getType()) {
    case MISSING:
        throw new MajorBug();
    case UNINITIALIZED:
        if (module.getRepo() == null)
            try {
                RepositoryBuilder builder = new RepositoryBuilder();
                builder.setWorkTree(new File(repo.getWorkTree() + "/" + module.getPath()));
                builder.setGitDir(new File(repo.getDirectory() + "/modules/" + module.getPath()));
                module.repo = builder.build();

                // we actually *might* not have to make the repo from zero.
                // this getRepo gets its effective data from SubmoduleWalk.getSubmoduleRepository...
                // which does its job by looking in the working tree of the parent repo.
                // meaning if it finds nothing, it certainly won't find any gitdir indirections.
                // so, even if this is null, we might well have a gitdir cached that we still have to go find.
                final FileBasedConfig cfg = (FileBasedConfig) module.repo.getConfig();
                if (!cfg.getFile().exists()) { // though seemly messy, this is the same question the jgit create() function asks, and it's not exposed to us, so.
                    module.repo.create(false);
                } else {
                    // do something crazy, because... i think the user's expectation after blowing away their submodule working tree is likely wanting a clean state of index and such here
                    try {
                        new Git(module.getRepo()).reset().setMode(ResetType.HARD).call();
                    } catch (CheckoutConflictException e) {
                        /* Can a hard reset even have a conflict? */
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    } catch (GitAPIException e) {
                        throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
                    }//from ww  w.  jav a 2 s  .  c o m
                }

                // set up a working tree which points to the gitdir in the parent repo:

                // handling paths in java, god forbid relative paths, is such an unbelievable backwater.  someday please make a whole library that actually disambiguates pathnames from filedescriptors properly
                int ups = StringUtils.countMatches(module.getPath(), "/");
                // look up the path between the `repo` and its possible git dir location.  if the gitdir is relocated, we have adjust our own relocations to compensate.
                String parentGitPointerStr = ".git/";
                String parentWorktreePointerStr = "../";
                // load it ourselves because we explicitly want the unresolved path, not what jgit would give us back from `repo.getDirectory().toString()`.
                File parentGitPointer = new File(repo.getWorkTree(), ".git");
                if (parentGitPointer.isFile()) {
                    // this shouldn't have to be recursive fortunately (that recursion is done implicitly by the chaining of each guy at each stage).
                    // this does however feel fairly fragile.  it's considerable that perhaps we should try to heuristically determine when paths are just to crazy to deal with.  but, on the off chance that check was overzealous, it would be very irritating, so let's not.
                    // frankly, if you're doing deeply nested submodules, or other advanced gitdir relocations, at some point you're taking it upon yourself to deal with the inevitably complex outcomes and edge case limitations.
                    parentGitPointerStr = IOForge.readFileAsString(parentGitPointer);
                    if (!"gitdir:".equals(parentGitPointerStr.substring(0, 7)))
                        throw new ConfigInvalidException(
                                "cannot understand location of parent project git directory");
                    parentGitPointerStr = parentGitPointerStr.substring(7).trim() + "/";
                    parentWorktreePointerStr = repo.getConfig().getString("core", null, "worktree") + "/";
                }
                // jgit does not appear to create the .git file correctly here :/
                // nor even consider it to be jgit's job to create the worktree yet, apparently, so do that
                module.repo.getWorkTree().mkdirs();
                // need modules/[module]/config to contain 'core.worktree' = appropriate
                String submoduleWorkTreeRelativeToGitDir = StringUtils.repeat("../", ups + 2)
                        + parentWorktreePointerStr + module.getPath();
                StoredConfig cnf = module.repo.getConfig();
                cnf.setString("core", null, "worktree", submoduleWorkTreeRelativeToGitDir);
                cnf.save();
                // need [module]/.git to contain 'gitdir: appropriate' (which appears to not be normal gitconfig)
                String submoduleGitDirRelativeToWorkTree = StringUtils.repeat("../", ups + 1)
                        + parentGitPointerStr + "modules/" + module.getPath();
                IOForge.saveFile("gitdir: " + submoduleGitDirRelativeToWorkTree + "\n",
                        new File(module.repo.getWorkTree(), ".git"));
            } catch (IOException e) {
                throw new MdmRepositoryIOException("create a new submodule", true, module.getHandle(), e);
            }

        try {
            if (initLocalConfig(repo, module))
                repo.getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true, "the local git configuration file", e);
        }
        try {
            setMdmRemote(module);
            module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }
    case INITIALIZED:
        if (module.getVersionName() == null || module.getVersionName().equals(module.getVersionActual()))
            return false;
    case REV_CHECKED_OUT:
        try {
            if (initModuleConfig(repo, module))
                module.getRepo().getConfig().save();
        } catch (IOException e) {
            throw new MdmRepositoryIOException("save changes", true,
                    "the git configuration file for submodule " + module.getHandle(), e);
        }

        final String versionBranchName = "refs/heads/mdm/release/" + module.getVersionName();
        final String versionTagName = "refs/tags/release/" + module.getVersionName();

        /* Fetch only the branch labelled with the version requested. */
        if (module.getRepo().getRef(versionBranchName) == null)
            try {
                RefSpec releaseBranchRef = new RefSpec().setForceUpdate(true).setSource(versionBranchName)
                        .setDestination(versionBranchName);
                RefSpec releaseTagRef = new RefSpec().setForceUpdate(true).setSource(versionTagName)
                        .setDestination(versionTagName);
                new Git(module.getRepo()).fetch().setRemote("origin")
                        .setRefSpecs(releaseBranchRef, releaseTagRef).setTagOpt(TagOpt.NO_TAGS).call();
            } catch (InvalidRemoteException e) {
                throw new MdmRepositoryStateException(
                        "find a valid remote origin in the config for the submodule", module.getHandle(), e);
            } catch (TransportException e) {
                URIish remote = null;
                try { //XXX: if we went through all the work to resolve the remote like the fetch command does, we could just as well do it and hand the resolved uri to fetch for better consistency.
                    remote = new RemoteConfig(module.getRepo().getConfig(), "origin").getURIs().get(0);
                } catch (URISyntaxException e1) {
                }
                throw new MdmRepositoryIOException("fetch from a remote", false, remote.toASCIIString(), e)
                        .setAdditionalMessage("check your connectivity and try again?");
            } catch (GitAPIException e) {
                throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
            }

        /* Drop the files into the working tree. */
        try {
            new Git(module.getRepo()).checkout().setName(versionBranchName).setForce(true).call();
        } catch (RefAlreadyExistsException e) {
            /* I'm not creating a new branch, so this exception wouldn't even make sense. */
            throw new MajorBug(e);
        } catch (RefNotFoundException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (InvalidRefNameException e) {
            /* I just got this branch, so we shouldn't have a problem here. */
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        } catch (CheckoutConflictException e) {
            // this one is just a perfectly reasonable message with a list of files in conflict; we'll take it.
            throw new MdmRepositoryStateException(module.getHandle(), e); // this currently gets translated to a :'( exception and it's probably more like a :(
        } catch (GitAPIException e) {
            throw new MajorBug("an unrecognized problem occurred.  please file a bug report.", e);
        }
        return true;
    default:
        throw new MajorBug();
    }
}

From source file:aldenjava.opticalmapping.data.data.OptMapDataWriter.java

@Override
public void write(DataNode data) throws IOException {
    if (data != null)
        switch (dformat) {
        case REF:
        case SILICO:
            bw.write(data.name + "\t" + Long.toString(data.size) + "\t" + Integer.toString(data.refp.length)
                    + "\n");
            for (int i = 0; i < data.refp.length - 1; i++)
                bw.write(Long.toString(data.refp[i]) + "\t");
            if (data.refp.length > 0)
                bw.write(Long.toString(data.refp[data.refp.length - 1]) + "\n");
            else/* ww w . j  a  v  a2s  . c  om*/
                bw.write("\n");
            break;
        case FA01:
            bw.write(">");
            bw.write(data.name);
            bw.write("\n");
            for (int i = 0; i < data.refp.length + 1; i++) {
                bw.write(StringUtils.repeat("0", (int) data.getRefl(i)));
                if (i != data.refp.length + 1 - 1)
                    bw.write("1");
            }

            bw.write("\n");
            break;
        case SPOTS:
            if (writtenSingleRefFile) {
                System.out.println("No more than one reference can be written on the same spot file.");
                return;
            }
            writtenSingleRefFile = true;
            bw.write("#\n");
            bw.write("#   Reference Size (Bp):   " + Long.toString(data.size) + "\n");
            bw.write("#   N Colors:   1\n");
            bw.write("NickID Color Location\n");

            long refp[] = data.refp;
            for (int i = 0; i < refp.length; i++) {
                bw.write(Integer.toString(i));
                bw.write(" 1 ");
                bw.write(Long.toString(refp[i]));
                bw.write("\n");
            }
            break;
        case OPT:
            if (writtenSingleRefFile) {
                System.out.println("No more than one reference can be written on the same opt file.");
                return;
            }
            writtenSingleRefFile = true;

            for (int i = 0; i < data.refp.length + 1; i++) {
                long r = data.getRefl(i);
                bw.write(String.format("%f\t%f\n", r / (double) 1000 + 0.001,
                        (r / (double) 1000) * 0.05 + 0.001));
            }
            break;
        case DATA:
            StringBuilder s2 = new StringBuilder();
            for (int i = 0; i < data.getTotalSegment(); i++) {
                s2.append(Long.toString(data.getRefl(i)));
                if (i != data.getTotalSegment() - 1)
                    s2.append(";");
            }

            bw.write(String.format("%s\t%d\t%d\t%s\n", data.name, data.length(), data.getTotalSegment(),
                    s2.toString()));
            break;
        case SDATA:
            String r = "";
            long start = -1;
            long stop = -1;
            int simuStrand = 0;

            if (data.hasSimulationInfo()) {
                r = data.simuInfo.simuRegion.ref;
                start = data.simuInfo.simuRegion.start;
                stop = data.simuInfo.simuRegion.stop;
                simuStrand = data.simuInfo.simuStrand;
            }
            StringBuilder s = new StringBuilder();
            for (int i = 0; i < data.getTotalSegment(); i++) {
                s.append(Long.toString(data.getRefl(i)));
                if (i != data.getTotalSegment() - 1)
                    s.append(";");
            }
            bw.write(String.format("%s\t%s\t%s\t%d\t%d\t%d\t%d\t%s\n", data.name, r,
                    simuStrand == 1 ? "+" : simuStrand == -1 ? "-" : "", start, stop, data.length(),
                    data.getTotalSegment(), s.toString()));
            break;
        case BNX:
            bw.write("0\t");
            bw.write(data.name);
            bw.write("\t");
            bw.write(Long.toString(data.length()));
            bw.write(".0");
            bw.write("\n");
            bw.write("1");
            for (int i = 0; i < data.refp.length; i++) {
                bw.write("\t");
                bw.write(Long.toString(data.refp[i]));
                bw.write(".0");
            }
            bw.write("\n");
            bw.write("QX01"); // Default as 10.0
            if (data instanceof BnxDataNode)
                for (int i = 0; i < data.refp.length; i++)
                    bw.write("\t" + Double.toString(((BnxDataNode) data).snr[i]));
            else
                for (int i = 0; i < data.refp.length; i++)
                    bw.write("\t10.0");
            bw.write("\n");
            bw.write("QX02"); // Default as 0.05
            if (data instanceof BnxDataNode)
                for (int i = 0; i < data.refp.length; i++)
                    bw.write("\t" + Double.toString(((BnxDataNode) data).intensity[i]));
            else
                for (int i = 0; i < data.refp.length; i++)
                    bw.write("\t0.05");
            bw.write("\n");
            break;
        case CMAP:

            String id = data.name;
            long size = data.size;
            int totalsites = data.getTotalSegment() - 1;
            // l[3] //site x
            int labelchannel = 1;
            double stddev = 0.0;
            int coverage = 1;
            int occurence = 1;

            for (int i = 0; i < data.refp.length + 1; i++) {
                long pos;
                if (i == data.refp.length) {
                    pos = size;
                    labelchannel = 0;
                } else
                    pos = data.refp[i];
                bw.write(String.format("%s\t%d\t%d\t%d\t%d\t%d\t%.1f\t%d\t%d\n", id, size, totalsites, i + 1,
                        labelchannel, pos, stddev, coverage, occurence));
            }
            break;
        default:
            assert false : "dformat unfound";
        }
}

From source file:de.Keyle.MyPet.MyPetPlugin.java

public void onEnable() {
    this.isReady = false;

    UpdateCheck.reset();/*from ww w  .  ja  v a  2s  .  c o m*/
    if (getConfig().getBoolean("MyPet.Update-Check", true)) {
        Optional<String> message = UpdateCheck.checkForUpdate("MyPet");
        if (message.isPresent()) {
            String m = "#  A new version is available: " + message.get() + "  #";
            MyPetApi.getLogger().info(StringUtils.repeat("#", m.length()));
            MyPetApi.getLogger().info(m);
            MyPetApi.getLogger().info("   https://mypet-plugin.de/download");
            MyPetApi.getLogger().info(StringUtils.repeat("#", m.length()));
        }
    }

    if (compatUtil.getInternalVersion() == null
            || !MyPetVersion.isValidBukkitPacket(compatUtil.getInternalVersion())) {
        getLogger().warning(ChatColor.RED + "This version of MyPet is not compatible with \""
                + compatUtil.getInternalVersion() + "\". Is MyPet up to date?");
        setEnabled(false);
        return;
    }

    serviceManager.activate(Load.State.OnEnable);
    pluginHookManager.enableHooks();
    serviceManager.activate(Load.State.AfterHooks);

    entityRegistry.registerEntityTypes();

    if (getLogger() instanceof MyPetLogger) {
        ((MyPetLogger) getLogger()).updateDebugLoggerLogLevel();
    }

    getLogger().info("Compat mode for " + compatUtil.getInternalVersion() + " loaded.");

    // register event listener
    PlayerListener playerListener = new PlayerListener();
    getServer().getPluginManager().registerEvents(playerListener, this);
    VehicleListener vehicleListener = new VehicleListener();
    getServer().getPluginManager().registerEvents(vehicleListener, this);
    EntityListener entityListener = new EntityListener();
    getServer().getPluginManager().registerEvents(entityListener, this);
    LevelUpListener levelupListener = new LevelUpListener();
    getServer().getPluginManager().registerEvents(levelupListener, this);
    WorldListener worldListener = new WorldListener();
    getServer().getPluginManager().registerEvents(worldListener, this);

    // register commands
    getCommand("petname").setExecutor(new CommandName());
    getCommand("petcall").setExecutor(new CommandCall());
    getCommand("petsendaway").setExecutor(new CommandSendAway());
    getCommand("petstop").setExecutor(new CommandStop());
    getCommand("petrelease").setExecutor(new CommandRelease());
    getCommand("mypet").setExecutor(new CommandHelp());
    getCommand("petinventory").setExecutor(new CommandInventory());
    getCommand("petpickup").setExecutor(new CommandPickup());
    getCommand("petbehavior").setExecutor(new CommandBehavior());
    getCommand("petinfo").setExecutor(new CommandInfo());
    getCommand("mypetadmin").setExecutor(new CommandAdmin());
    getCommand("petskill").setExecutor(new CommandSkill());
    getCommand("petskilltree").setExecutor(new CommandShowSkillTree());
    getCommand("petchooseskilltree").setExecutor(new CommandChooseSkilltree());
    getCommand("petbeacon").setExecutor(new CommandBeacon());
    getCommand("petrespawn").setExecutor(new CommandRespawn());
    getCommand("pettype").setExecutor(new CommandPetType());
    getCommand("petcapturehelper").setExecutor(new CommandCaptureHelper());
    getCommand("petoptions").setExecutor(new CommandOptions());
    getCommand("petswitch").setExecutor(new CommandSwitch());
    getCommand("petstore").setExecutor(new CommandStore());
    getCommand("petlist").setExecutor(new CommandList());

    // register skills
    registerSkillsInfo();
    registerSkills();

    // create folders
    File skilltreeFolder = new File(getDataFolder().getPath(), "skilltrees");
    getDataFolder().mkdirs();
    boolean createDefaultSkilltree = skilltreeFolder.mkdirs();
    new File(getDataFolder(), "locale").mkdirs();
    new File(getDataFolder(), "logs").mkdirs();

    if (createDefaultSkilltree) {
        platformHelper.copyResource(this, "skilltrees/default.st", new File(skilltreeFolder, "default.st"));
        getLogger().info("Default skilltree file created (default.st).");
    }

    // load skilltrees
    List<String> petTypes = new LinkedList<>();
    petTypes.add("default");
    for (MyPetType type : MyPetType.all()) {
        petTypes.add(type.name());
    }

    SkillTreeMobType.clearMobTypes();
    SkillTreeLoaderNBT.getSkilltreeLoader()
            .loadSkillTrees(getDataFolder().getPath() + File.separator + "skilltrees", petTypes);

    Set<String> skilltreeNames = new LinkedHashSet<>();
    for (MyPetType mobType : MyPetType.values()) {
        SkillTreeMobType skillTreeMobType = SkillTreeMobType.byPetType(mobType);
        SkillTreeLoader.addDefault(skillTreeMobType);
        SkillTreeLoader.manageInheritance(skillTreeMobType);
        skilltreeNames.addAll(skillTreeMobType.getSkillTreeNames());
    }
    // register skilltree permissions
    for (String skilltreeName : skilltreeNames) {
        try {
            Bukkit.getPluginManager().addPermission(new Permission("MyPet.skilltree." + skilltreeName));
        } catch (Exception ignored) {
        }
    }
    for (int i = 0; i < Configuration.Misc.MAX_STORED_PET_COUNT; i++) {
        try {
            Bukkit.getPluginManager().addPermission(new Permission("MyPet.petstorage.limit." + i));
        } catch (Exception ignored) {
        }
    }

    File translationReadme = new File(getDataFolder(), "locale" + File.separator + "readme.txt");
    if (!translationReadme.exists()) {
        platformHelper.copyResource(this, "locale-readme.txt", translationReadme);
    }
    Translation.init();

    // init repository
    repo = new SqLiteRepository();
    try {
        repo.init();
    } catch (RepositoryInitException ignored) {
        setEnabled(false);
        return;
    }

    File nbtFile = new File(MyPetApi.getPlugin().getDataFolder().getPath() + File.separator + "My.Pets");
    if (nbtFile.exists()) {
        Converter.convert();
    }

    if (repo instanceof Scheduler) {
        Timer.addTask((Scheduler) repo);
    }

    // load worldgroups
    loadGroups(new File(getDataFolder().getPath(), "worldgroups.yml"));
    Timer.startTimer();

    // init Metrics
    Metrics metrics = new Metrics(this);
    metrics.addCustomChart(new Metrics.SingleLineChart("active_pets") {
        @Override
        public int getValue() {
            return myPetManager.countActiveMyPets();
        }
    });
    metrics.addCustomChart(new Metrics.SimplePie("build") {
        @Override
        public String getValue() {
            return MyPetVersion.getBuild();
        }
    });

    getLogger().info("version " + MyPetVersion.getVersion() + "-b" + MyPetVersion.getBuild() + ChatColor.GREEN
            + " ENABLED");
    this.isReady = true;

    serviceManager.activate(Load.State.OnReady);

    // load pets for online players
    new BukkitRunnable() {
        @Override
        public void run() {
            for (final Player player : getServer().getOnlinePlayers()) {
                repo.getMyPetPlayer(player, new RepositoryCallback<MyPetPlayer>() {
                    @Override
                    public void callback(final MyPetPlayer p) {
                        if (p != null) {
                            final MyPetPlayerImpl onlinePlayer = (MyPetPlayerImpl) p;

                            onlinePlayer.setLastKnownName(player.getName());
                            if (!player.getUniqueId().equals(onlinePlayer.getOfflineUUID())) {
                                if (onlinePlayer.getMojangUUID() == null) {
                                    onlinePlayer.setMojangUUID(player.getUniqueId());
                                }
                                onlinePlayer.setOnlineMode(true);
                            }

                            playerManager.setOnline(onlinePlayer);

                            final WorldGroup joinGroup = WorldGroup
                                    .getGroupByWorld(player.getWorld().getName());
                            if (onlinePlayer.hasMyPet()) {
                                MyPet myPet = onlinePlayer.getMyPet();
                                if (!myPet.getWorldGroup().equals(joinGroup.getName())) {
                                    myPetManager.deactivateMyPet(onlinePlayer, true);
                                }
                            }

                            if (joinGroup != null && !onlinePlayer.hasMyPet()
                                    && onlinePlayer.hasMyPetInWorldGroup(joinGroup.getName())) {
                                final UUID petUUID = onlinePlayer.getMyPetForWorldGroup(joinGroup.getName());

                                MyPetApi.getRepository().getMyPet(petUUID,
                                        new RepositoryCallback<StoredMyPet>() {
                                            @Override
                                            public void callback(StoredMyPet storedMyPet) {
                                                myPetManager.activateMyPet(storedMyPet);

                                                if (onlinePlayer.hasMyPet()) {
                                                    final MyPet myPet = onlinePlayer.getMyPet();
                                                    final MyPetPlayer myPetPlayer = myPet.getOwner();
                                                    if (myPet.wantsToRespawn()) {
                                                        if (myPetPlayer.hasMyPet()) {
                                                            MyPet runMyPet = myPetPlayer.getMyPet();
                                                            switch (runMyPet.createEntity()) {
                                                            case Canceled:
                                                                runMyPet.getOwner()
                                                                        .sendMessage(Util.formatText(
                                                                                Translation.getString(
                                                                                        "Message.Spawn.Prevent",
                                                                                        myPet.getOwner()),
                                                                                runMyPet.getPetName()));
                                                                break;
                                                            case NoSpace:
                                                                runMyPet.getOwner()
                                                                        .sendMessage(Util.formatText(
                                                                                Translation.getString(
                                                                                        "Message.Spawn.NoSpace",
                                                                                        myPet.getOwner()),
                                                                                runMyPet.getPetName()));
                                                                break;
                                                            case NotAllowed:
                                                                runMyPet.getOwner().sendMessage(Util.formatText(
                                                                        Translation.getString(
                                                                                "Message.No.AllowedHere",
                                                                                myPet.getOwner()),
                                                                        myPet.getPetName()));
                                                                break;
                                                            case Dead:
                                                                runMyPet.getOwner().sendMessage(Util.formatText(
                                                                        Translation.getString(
                                                                                "Message.Spawn.Respawn.In",
                                                                                myPet.getOwner()),
                                                                        myPet.getPetName(),
                                                                        myPet.getRespawnTime()));
                                                                break;
                                                            case Flying:
                                                                runMyPet.getOwner()
                                                                        .sendMessage(Util.formatText(
                                                                                Translation.getString(
                                                                                        "Message.Spawn.Flying",
                                                                                        myPet.getOwner()),
                                                                                myPet.getPetName()));
                                                                break;
                                                            case Success:
                                                                runMyPet.getOwner().sendMessage(Util.formatText(
                                                                        Translation.getString(
                                                                                "Message.Command.Call.Success",
                                                                                myPet.getOwner()),
                                                                        runMyPet.getPetName()));
                                                                break;
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        });
                            }
                            onlinePlayer.checkForDonation();
                        }
                    }
                });
            }
        }
    }.runTaskLater(this, 0);
}

From source file:com.salsaberries.narchiver.HttpMessage.java

/**
 * Returns the message formatted nicely for logging.
 *
 * @return Nicely formatted header.//  w  w w. ja va2 s  . c o  m
 */
public String getFormattedMessage() {

    String firstString = "\n\n ========= " + getHttpType().toString() + ": " + getUrl() + " =========";
    String string = firstString;

    for (Header h : headers) {
        string = string + "\n " + h.getName() + ": " + h.getValue();
    }

    string = string + "\n \n" + " Content: " + getContent() + "\n";
    return string + StringUtils.repeat("=", firstString.length() - 3) + "\n \n";
}