Example usage for org.eclipse.jgit.lib Repository close

List of usage examples for org.eclipse.jgit.lib Repository close

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib Repository close.

Prototype

@Override
public void close() 

Source Link

Document

Decrement the use count, and maybe close resources.

Usage

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.services.impl.GitCloneServiceImpl.java

License:Apache License

public void download(String url, String moduleName) throws ModuleDownloaderException {
    // prepare a new folder for the cloned repository
    File localPath = new File(modulesCodeDownloadPath + moduleName);
    localPath.delete();/*from  w w w.j a  v a 2  s .  c  om*/

    try {
        FileUtils.deleteDirectory(localPath);
    } catch (IOException e) {
        throw new ModuleDownloaderException(e);
    }

    // then clone
    logger.debug("Cloning from " + url + " to " + localPath);
    try {
        Git.cloneRepository().setURI(url).setDirectory(localPath).call();
    } catch (InvalidRemoteException e) {
        throw new ModuleDownloaderException(e);
    } catch (TransportException e) {
        throw new ModuleDownloaderException(e);
    } catch (GitAPIException e) {
        throw new ModuleDownloaderException(e);
    }

    // now open the created repository
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repository;
    try {
        repository = builder.setGitDir(localPath).readEnvironment() // scan environment GIT_* variables
                .findGitDir() // scan up the file system tree
                .build();
    } catch (IOException e) {
        throw new ModuleDownloaderException(e);
    }

    logger.debug("Having repository: " + repository.getDirectory());

    repository.close();
}

From source file:com.uber.stream.kafka.mirrormaker.controller.core.GitBackUpHandler.java

License:Apache License

public void writeToFile(String fileName, String data) throws Exception {
    Repository backupRepo = null;
    BufferedWriter output = null;
    Git git = null;/* ww w  .  j  a  v  a2s  .co m*/
    Git result = null;
    try {
        try {
            FileUtils.deleteDirectory(new File(localPath));
        } catch (IOException e) {
            LOGGER.error("Error deleting exisiting backup directory");
            throw e;
        }

        try {
            result = Git.cloneRepository().setURI(remotePath).setDirectory(new File(localPath)).call();
        } catch (Exception e) {
            LOGGER.error("Error cloning backup git repo");
            throw e;
        }

        try {
            backupRepo = new FileRepository(localPath + "/.git");
        } catch (IOException e) {
            throw e;
        }

        git = new Git(backupRepo);
        File myfile = new File(localPath + "/" + fileName);

        try {
            output = new BufferedWriter(new FileWriter(myfile));
            output.write(data);
            output.flush();
        } catch (IOException e) {
            LOGGER.error("Error writing backup to the file with name " + fileName);
            throw e;
        }

        try {
            git.add().addFilepattern(".").call();
        } catch (GitAPIException e) {
            LOGGER.error("Error adding files to git");
            throw e;
        }

        try {
            git.commit().setMessage("Taking backup on " + new Date()).call();

        } catch (GitAPIException e) {
            LOGGER.error("Error commiting files to git");
            throw e;
        }

        try {
            git.push().call();
        } catch (GitAPIException e) {
            LOGGER.error("Error pushing files to git");
            throw e;
        }
    } catch (Exception e) {
        throw e;
    } finally {
        output.close();
        git.close();
        if (result != null)
            result.getRepository().close();
        backupRepo.close();
    }
}

From source file:de.blizzy.documentr.repository.RepositoryUtil.java

License:Open Source License

public static void closeQuietly(Repository repo) {
    if (repo != null) {
        try {/*  ww w.j a  va  2  s .co  m*/
            repo.close();
        } catch (RuntimeException e) {
            // ignore
        }
    }
}

From source file:de.unihalle.informatik.Alida.version.ALDVersionProviderGit.java

License:Open Source License

/**
 * Returns information about current commit.
 * <p>//from  w  w w  .j  ava2 s.co  m
 * If no git repository is found, the method checks for a file 
 * "revision.txt" as it is present in Alida jar files. 
 * If the file does not exist or is empty, a dummy string is returned.
 * 
 * @return    Info string.
 */
private static String getRepositoryInfo() {

    ALDVersionProviderGit.localVersion = "Unknown";
    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    try {
        Repository repo = null;
        try {
            repo = builder.readEnvironment().build();
        } catch (IllegalArgumentException e) {
            // problem accessing environment... fall back to default
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // check if GIT_DIR is set
        if (!builder.getGitDir().isDirectory()) {
            if (repo != null)
                repo.close();
            return ALDVersionProviderGit.localVersion;
        }

        // extract the active branch
        String activeBranch = repo.getBranch();

        // extract last commit 
        Ref HEAD = repo.findRef(activeBranch);

        // safety check if everything is alright with repository
        if (HEAD == null) {
            repo.close();
            throw new IOException();
        }

        // extract state of repository
        String state = repo.getRepositoryState().toString();

        ALDVersionProviderGit.localVersion = activeBranch + " : " + HEAD.toString() + " ( " + state + " ) ";

        // clean-up
        repo.close();
    } catch (IOException e) {
        // accessing the Git repository failed, search for file
        InputStream is = null;
        BufferedReader br = null;
        String vLine = null;

        // initialize file reader and extract version information
        try {
            System.out.print("Searching for local revision file...");
            is = ALDVersionProviderGit.class.getResourceAsStream("/" + ALDVersionProviderGit.revFile);
            br = new BufferedReader(new InputStreamReader(is));
            vLine = br.readLine();
            if (vLine == null) {
                System.err.println("ALDVersionProviderGit: " + "revision file is empty...!?");
                br.close();
                is.close();
                return ALDVersionProviderGit.localVersion;
            }
            ALDVersionProviderGit.localVersion = vLine;
            br.close();
            is.close();
            return vLine;
        } catch (Exception ex) {
            try {
                if (br != null)
                    br.close();
                if (is != null)
                    is.close();
            } catch (IOException eo) {
                // nothing to do here
            }
            return ALDVersionProviderGit.localVersion;
        }
    }
    return ALDVersionProviderGit.localVersion;
}

From source file:divconq.tool.release.Main.java

@Override
public void run(Scanner scan, ApiSession api) {
    Path relpath = null;/*  w w w.ja  v  a  2s . c  o m*/
    Path gitpath = null;
    Path wikigitpath = null;

    XElement fldset = Hub.instance.getConfig().selectFirst("CommandLine/Settings");

    if (fldset != null) {
        relpath = Paths.get(fldset.getAttribute("ReleasePath"));
        gitpath = Paths.get(fldset.getAttribute("GitPath"));
        wikigitpath = Paths.get(fldset.getAttribute("WikiGitPath"));
    }

    boolean running = true;

    while (running) {
        try {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("   Release Builder Menu");
            System.out.println("-----------------------------------------------");
            System.out.println("0)  Exit");

            if (relpath != null)
                System.out.println("1)  Build release package from Settings File");

            System.out.println("2)  Build custom release package [under construction]");

            System.out.println("4)  Pack the .jar files");

            if (gitpath != null)
                System.out.println("5)  Copy Source to GitHub folder");

            System.out.println("6)  Update AWWW");

            String opt = scan.nextLine();

            Long mopt = StringUtil.parseInt(opt);

            if (mopt == null)
                continue;

            switch (mopt.intValue()) {
            case 0:
                running = false;
                break;

            case 1: {
                ReleasesHelper releases = new ReleasesHelper();

                if (!releases.init(relpath))
                    break;

                System.out.println("Select a release to build");
                System.out.println("0) None");

                List<String> rnames = releases.names();

                for (int i = 0; i < rnames.size(); i++)
                    System.out.println((i + 1) + ") " + rnames.get(i));

                System.out.println("Option #: ");
                opt = scan.nextLine();

                mopt = StringUtil.parseInt(opt);

                if ((mopt == null) || (mopt == 0))
                    break;

                XElement relchoice = releases.get(mopt.intValue() - 1);

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                XElement prindesc = availpackages.get(inst.prinpackage);

                XElement prininst = prindesc.find("Install");

                if (prininst == null) {
                    System.out.println("Principle package: " + inst.prinpackagenm
                            + " cannot be released directly, it must be part of another package.");
                    break;
                }

                String relvers = prindesc.getAttribute("Version");

                System.out.println("Building release version " + relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    System.out.println("Previous release version " + prindesc.getAttribute("LastVersion"));

                String rname = relchoice.getAttribute("Name");
                Path destpath = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.exists(destpath)) {
                    System.out.println("Version " + relvers + " already exists, overwrite? (y/n): ");
                    if (!scan.nextLine().toLowerCase().startsWith("y"))
                        break;

                    Files.delete(destpath);
                }

                System.out.println("Preparing zip files");

                AtomicBoolean errored = new AtomicBoolean();
                Path tempfolder = FileUtil.allocateTempFolder2();

                ListStruct ignorepaths = new ListStruct();
                Set<String> nolongerdepends = new HashSet<>();
                Set<String> dependson = new HashSet<>();

                // put all the release files into a temp folder
                inst.instpkgs.forEach(pname -> {
                    availpackages.get(pname).selectAll("DependsOn").stream()
                            .filter(doel -> !doel.hasAttribute("Option")
                                    || inst.relopts.contains(doel.getAttribute("Option")))
                            .forEach(doel -> {
                                // copy all libraries we rely on
                                doel.selectAll("Library").forEach(libel -> {
                                    dependson.add(libel.getAttribute("File"));

                                    Path src = Paths.get("./lib/" + libel.getAttribute("File"));
                                    Path dest = tempfolder.resolve("lib/" + libel.getAttribute("File"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all files we rely on
                                doel.selectAll("File").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());

                                        if (Files.notExists(dest))
                                            Files.copy(src, dest, StandardCopyOption.COPY_ATTRIBUTES);
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }
                                });

                                // copy all folders we rely on
                                doel.selectAll("Folder").forEach(libel -> {
                                    Path src = Paths.get("./" + libel.getAttribute("Path"));
                                    Path dest = tempfolder.resolve(libel.getAttribute("Path"));

                                    try {
                                        Files.createDirectories(dest.getParent());
                                    } catch (Exception x) {
                                        errored.set(true);
                                        System.out.println("Unable to copy file: " + src);
                                    }

                                    OperationResult cres = FileUtil.copyFileTree(src, dest);

                                    if (cres.hasErrors())
                                        errored.set(true);
                                });
                            });

                    availpackages.get(pname).selectAll("IgnorePaths/Ignore")
                            .forEach(doel -> ignorepaths.addItem(doel.getAttribute("Path")));

                    // NoLongerDependsOn functionally currently only applies to libraries
                    availpackages.get(pname).selectAll("NoLongerDependsOn/Library")
                            .forEach(doel -> nolongerdepends.add(doel.getAttribute("File")));

                    // copy the released packages folders
                    Path src = Paths.get("./packages/" + pname);
                    Path dest = tempfolder.resolve("packages/" + pname);

                    try {
                        Files.createDirectories(dest.getParent());
                    } catch (Exception x) {
                        errored.set(true);
                        System.out.println("Unable to copy file: " + src);
                    }

                    // we may wish to enhance filter to allow .JAR sometimes, but this is meant to prevent copying of packages/pname/lib/abc.lib.jar files 
                    OperationResult cres = FileUtil.copyFileTree(src, dest,
                            path -> !path.toString().endsWith(".jar"));

                    if (cres.hasErrors())
                        errored.set(true);

                    // copy the released packages libraries
                    Path libsrc = Paths.get("./packages/" + pname + "/lib");
                    Path libdest = tempfolder.resolve("lib");

                    if (Files.exists(libsrc)) {
                        cres = FileUtil.copyFileTree(libsrc, libdest);

                        if (cres.hasErrors())
                            errored.set(true);
                    }
                });

                if (errored.get()) {
                    System.out.println("Error with assembling package");
                    break;
                }

                // copy the principle config
                Path csrc = Paths.get("./packages/" + inst.prinpackage + "/config");
                Path cdest = tempfolder.resolve("config/" + inst.prinpackagenm);

                if (Files.exists(csrc)) {
                    Files.createDirectories(cdest);

                    OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                    if (cres.hasErrors()) {
                        System.out.println("Error with prepping config");
                        break;
                    }
                }

                boolean configpassed = true;

                // copy packages with config = true
                for (XElement pkg : relchoice.selectAll("Package")) {
                    if (!"true".equals(pkg.getAttribute("Config")))
                        break;

                    String pname = pkg.getAttribute("Name");

                    int pspos = pname.lastIndexOf('/');
                    String pnm = (pspos != -1) ? pname.substring(pspos + 1) : pname;

                    csrc = Paths.get("./packages/" + pname + "/config");
                    cdest = tempfolder.resolve("config/" + pnm);

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping extra config");
                            configpassed = false;
                            break;
                        }
                    }
                }

                if (!configpassed)
                    break;

                // also copy installer config if being used
                if (inst.includeinstaller) {
                    csrc = Paths.get("./packages/dc/dcInstall/config");
                    cdest = tempfolder.resolve("config/dcInstall");

                    if (Files.exists(csrc)) {
                        Files.createDirectories(cdest);

                        OperationResult cres = FileUtil.copyFileTree(csrc, cdest);

                        if (cres.hasErrors()) {
                            System.out.println("Error with prepping install config");
                            break;
                        }
                    }
                }

                // write out the deployed file
                RecordStruct deployed = new RecordStruct();

                deployed.setField("Version", relvers);
                deployed.setField("PackageFolder", relpath.resolve(rname));
                deployed.setField("PackagePrefix", rname);

                OperationResult d1res = IOUtil.saveEntireFile(tempfolder.resolve("config/deployed.json"),
                        deployed.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployed");
                    break;
                }

                RecordStruct deployment = new RecordStruct();

                deployment.setField("Version", relvers);

                if (prindesc.hasAttribute("LastVersion"))
                    deployment.setField("DependsOn", prindesc.getAttribute("LastVersion"));

                deployment.setField("UpdateMessage",
                        "This update is complete, you may accept this update as runnable.");

                nolongerdepends.removeAll(dependson);

                ListStruct deletefiles = new ListStruct();

                nolongerdepends.forEach(fname -> deletefiles.addItem("lib/" + fname));

                deployment.setField("DeleteFiles", deletefiles);
                deployment.setField("IgnorePaths", ignorepaths);

                d1res = IOUtil.saveEntireFile(tempfolder.resolve("deployment.json"),
                        deployment.toPrettyString());

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping deployment");
                    break;
                }

                // write env file
                d1res = IOUtil.saveEntireFile(tempfolder.resolve("env.bat"), "set mem="
                        + relchoice.getAttribute("Memory", "2048") + "\r\n" + "SET project="
                        + inst.prinpackagenm + "\r\n" + "SET service="
                        + relchoice.getAttribute("Service", inst.prinpackagenm) + "\r\n" + "SET servicename="
                        + relchoice.getAttribute("ServiceName", inst.prinpackagenm + " Service") + "\r\n");

                if (d1res.hasErrors()) {
                    System.out.println("Error with prepping env");
                    break;
                }

                System.out.println("Packing Release file.");

                Path relbin = relpath.resolve(rname + "/" + rname + "-" + relvers + "-bin.zip");

                if (Files.notExists(relbin.getParent()))
                    Files.createDirectories(relbin.getParent());

                ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                try {
                    Files.walkFileTree(tempfolder, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                            new SimpleFileVisitor<Path>() {
                                @Override
                                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                        throws IOException {
                                    ZipArchiveEntry entry = new ZipArchiveEntry(
                                            tempfolder.relativize(file).toString());
                                    entry.setSize(Files.size(file));
                                    zipout.putArchiveEntry(entry);
                                    zipout.write(Files.readAllBytes(file));
                                    zipout.closeArchiveEntry();

                                    return FileVisitResult.CONTINUE;
                                }
                            });
                } catch (IOException x) {
                    System.out.println("Error building zip: " + x);
                }

                zipout.close();

                System.out.println("Release file written");

                FileUtil.deleteDirectory(tempfolder);

                break;
            } // end case 1

            case 3: {
                System.out.println("Note these utilities are only good from the main console,");
                System.out.println("if you are using a remote connection then the encryption will");
                System.out.println("not work as expected.  [we do not have access the master keys]");
                System.out.println();

                Foreground.utilityMenu(scan);

                break;
            }

            case 4: {
                System.out.println("Packing jar library files.");

                String[] packlist = new String[] { "divconq.core", "divconq.interchange", "divconq.web",
                        "divconq.tasks", "divconq.tasks.api", "ncc.uploader.api", "ncc.uploader.core",
                        "ncc.workflow", "sd.core" };

                String[] packnames = new String[] { "dcCore", "dcInterchange", "dcWeb", "dcTasks", "dcTasksApi",
                        "nccUploaderApi", "nccUploader", "nccWorkflow", "sd/sdBackend" };

                for (int i = 0; i < packlist.length; i++) {
                    String lib = packlist[i];
                    String pname = packnames[i];

                    Path relbin = Paths.get("./ext/" + lib + ".jar");
                    Path srcbin = Paths.get("./" + lib + "/bin");
                    Path packbin = Paths.get("./packages/" + pname + "/lib/" + lib + ".jar");

                    if (Files.notExists(relbin.getParent()))
                        Files.createDirectories(relbin.getParent());

                    Files.deleteIfExists(relbin);

                    ZipArchiveOutputStream zipout = new ZipArchiveOutputStream(relbin.toFile());

                    try {
                        Files.walkFileTree(srcbin, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                                new SimpleFileVisitor<Path>() {
                                    @Override
                                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                            throws IOException {
                                        ZipArchiveEntry entry = new ZipArchiveEntry(
                                                srcbin.relativize(file).toString());
                                        entry.setSize(Files.size(file));
                                        zipout.putArchiveEntry(entry);
                                        zipout.write(Files.readAllBytes(file));
                                        zipout.closeArchiveEntry();

                                        return FileVisitResult.CONTINUE;
                                    }
                                });
                    } catch (IOException x) {
                        System.out.println("Error building zip: " + x);
                    }

                    zipout.close();

                    Files.copy(relbin, packbin, StandardCopyOption.REPLACE_EXISTING);
                }

                System.out.println("Done");

                break;
            }

            case 5: {
                System.out.println("Copying Source Files");

                System.out.println("Cleaning folders");

                OperationResult or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.core/src/main/resources"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectory(gitpath.resolve("packages"));

                if (or.hasErrors()) {
                    System.out.println("Error deleting files");
                    break;
                }

                or = FileUtil.deleteDirectoryContent(wikigitpath, ".git");

                if (or.hasErrors()) {
                    System.out.println("Error deleting wiki files");
                    break;
                }

                System.out.println("Copying folders");

                System.out.println("Copy tree ./divconq.core/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/divconq"),
                        gitpath.resolve("divconq.core/src/main/java/divconq"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/org"),
                        gitpath.resolve("divconq.core/src/main/java/org"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".java");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                or = FileUtil.copyFileTree(Paths.get("./divconq.core/src/localize"),
                        gitpath.resolve("divconq.core/src/main/resources/localize"), new Predicate<Path>() {
                            @Override
                            public boolean test(Path file) {
                                return file.getFileName().toString().endsWith(".xml");
                            }
                        });

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.interchange/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.interchange/src"),
                        gitpath.resolve("divconq.interchange/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks/src"),
                        gitpath.resolve("divconq.tasks/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.tasks.api/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.tasks.api/src"),
                        gitpath.resolve("divconq.tasks.api/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.web/src");

                or = FileUtil.copyFileTree(Paths.get("./divconq.web/src"),
                        gitpath.resolve("divconq.web/src/main/java"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCore");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCore"), gitpath.resolve("packages/dcCore"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcCorePublic");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcCorePublic"),
                        gitpath.resolve("packages/dcCorePublic"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcInterchange");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcInterchange"),
                        gitpath.resolve("packages/dcInterchange"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasks");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasks"),
                        gitpath.resolve("packages/dcTasks"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksApi");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksApi"),
                        gitpath.resolve("packages/dcTasksApi"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTasksWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTasksWeb"),
                        gitpath.resolve("packages/dcTasksWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcTest");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcTest"), gitpath.resolve("packages/dcTest"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./packages/dcWeb");

                or = FileUtil.copyFileTree(Paths.get("./packages/dcWeb"), gitpath.resolve("packages/dcWeb"));

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copy tree ./divconq.wiki/public");

                or = FileUtil.copyFileTree(Paths.get("./divconq.wiki/public"), wikigitpath);

                if (or.hasErrors()) {
                    System.out.println("Error copying files");
                    break;
                }

                System.out.println("Copying files");

                Files.copy(Paths.get("./README.md"), gitpath.resolve("README.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./RELEASE_NOTES.md"), gitpath.resolve("RELEASE_NOTES.md"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./NOTICE.txt"), gitpath.resolve("NOTICE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
                Files.copy(Paths.get("./LICENSE.txt"), gitpath.resolve("LICENSE.txt"),
                        StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

                System.out.println("Done");

                break;
            }
            case 6: {
                System.out.println("Are you sure you want to update AWWW Server? (y/n): ");
                if (!scan.nextLine().toLowerCase().startsWith("y"))
                    break;

                ReleasesHelper releases = new ReleasesHelper();
                if (!releases.init(relpath))
                    break;

                XElement relchoice = releases.get("AWWWServer");

                if (relchoice == null) {
                    System.out.println("Invalid option");
                    break;
                }

                PackagesHelper availpackages = new PackagesHelper();
                availpackages.init();

                InstallHelper inst = new InstallHelper();
                if (!inst.init(availpackages, relchoice))
                    break;

                ServerHelper ssh = new ServerHelper();
                if (!ssh.init(relchoice.find("SSH")))
                    break;

                ChannelSftp sftp = null;

                try {
                    Channel channel = ssh.session().openChannel("sftp");
                    channel.connect();
                    sftp = (ChannelSftp) channel;

                    // go to routines folder
                    sftp.cd("/usr/local/bin/dc/AWWWServer");

                    FileRepositoryBuilder builder = new FileRepositoryBuilder();

                    Repository repository = builder.setGitDir(new File(".git")).findGitDir() // scan up the file system tree
                            .build();

                    String lastsync = releases.getData("AWWWServer").getFieldAsString("LastCommitSync");

                    RevWalk rw = new RevWalk(repository);
                    ObjectId head1 = repository.resolve(Constants.HEAD);
                    RevCommit commit1 = rw.parseCommit(head1);

                    releases.getData("AWWWServer").setField("LastCommitSync", head1.name());

                    ObjectId rev2 = repository.resolve(lastsync);
                    RevCommit parent = rw.parseCommit(rev2);
                    //RevCommit parent2 = rw.parseCommit(parent.getParent(0).getId());

                    DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE);
                    df.setRepository(repository);
                    df.setDiffComparator(RawTextComparator.DEFAULT);
                    df.setDetectRenames(true);

                    // list oldest first or change types are all wrong!!
                    List<DiffEntry> diffs = df.scan(parent.getTree(), commit1.getTree());

                    for (DiffEntry diff : diffs) {
                        String gnpath = diff.getNewPath();
                        String gopath = diff.getOldPath();

                        Path npath = Paths.get("./" + gnpath);
                        Path opath = Paths.get("./" + gopath);

                        if (diff.getChangeType() == ChangeType.DELETE) {
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if ((diff.getChangeType() == ChangeType.ADD)
                                || (diff.getChangeType() == ChangeType.MODIFY)
                                || (diff.getChangeType() == ChangeType.COPY)) {
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else if (diff.getChangeType() == ChangeType.RENAME) {
                            // remove the old
                            if (inst.containsPathExtended(opath)) {
                                System.out.println("- " + diff.getChangeType().name() + " - " + opath);

                                try {
                                    sftp.rm(opath.toString());
                                    System.out.println("deleted!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("/ " + diff.getChangeType().name() + " - " + gopath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }

                            // add the new path
                            if (inst.containsPathExtended(npath)) {
                                System.out.println("+ " + diff.getChangeType().name() + " - " + npath);

                                try {
                                    ssh.makeDirSftp(sftp, npath.getParent());

                                    sftp.put(npath.toString(), npath.toString(), ChannelSftp.OVERWRITE);
                                    sftp.chmod(npath.endsWith(".sh") ? 484 : 420, npath.toString()); // 644 octal = 420 dec, 744 octal = 484 dec
                                    System.out.println("uploaded!!");
                                } catch (SftpException x) {
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                    System.out.println("Sftp Error: " + x);
                                    System.out.println(
                                            " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
                                }
                            } else {
                                System.out.println("> " + diff.getChangeType().name() + " - " + gnpath
                                        + " !!!!!!!!!!!!!!!!!!!!!!!!!");
                            }
                        } else {
                            System.out.println("??????????????????????????????????????????????????????????");
                            System.out.println(": " + diff.getChangeType().name() + " - " + gnpath
                                    + " ?????????????????????????");
                            System.out.println("??????????????????????????????????????????????????????????");
                        }
                    }

                    rw.dispose();

                    repository.close();

                    releases.saveData();
                } catch (JSchException x) {
                    System.out.println("Sftp Error: " + x);
                } finally {
                    if (sftp.isConnected())
                        sftp.exit();

                    ssh.close();
                }

                break;
            }

            case 7: {
                Path sfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly");
                Path dfolder = Paths.get("/Work/Projects/awww-current/dairy-graze/poly-js");

                Files.list(sfolder).forEach(file -> {
                    String fname = file.getFileName().toString();

                    if (!fname.endsWith(".xml"))
                        return;

                    FuncResult<XElement> lres = XmlReader.loadFile(file, false);

                    if (lres.isEmptyResult()) {
                        System.out.println("Unable to parse: " + file);
                        return;
                    }

                    String zc = fname.substring(5, 8);
                    String code = "zipsData['" + zc + "'] = ";
                    XElement root = lres.getResult();

                    /*
                    <polyline1 lng="-90.620897" lat="45.377447"/>
                    <polyline1 lng="-90.619327" lat="45.3805"/>
                            
                                   [-71.196845,41.67757],[-71.120168,41.496831],[-71.317338,41.474923],[-71.196845,41.67757]
                     */
                    ListStruct center = new ListStruct();
                    ListStruct cords = new ListStruct();
                    ListStruct currentPoly = null;
                    //String currentName = null;

                    for (XElement child : root.selectAll("*")) {
                        String cname = child.getName();

                        if (cname.startsWith("marker")) {
                            // not always accurate
                            if (center.isEmpty())
                                center.addItem(Struct.objectToDecimal(child.getAttribute("lng")),
                                        Struct.objectToDecimal(child.getAttribute("lat")));

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));

                            continue;
                        }

                        /*
                        if (cname.startsWith("info")) {
                           System.out.println("areas: " + child.getAttribute("areas"));
                           continue;
                        }
                        */

                        if (!cname.startsWith("polyline"))
                            continue;

                        if (currentPoly == null) {
                            //if (!cname.equals(currentName)) {
                            //if (currentName == null) {
                            //   currentName = cname;

                            //   System.out.println("new poly: " + cname);

                            currentPoly = new ListStruct();
                            cords.addItem(new ListStruct(currentPoly));
                        }

                        currentPoly.addItem(new ListStruct(Struct.objectToDecimal(child.getAttribute("lng")),
                                Struct.objectToDecimal(child.getAttribute("lat"))));
                    }

                    RecordStruct feat = new RecordStruct().withField("type", "Feature")
                            .withField("id", "zip" + zc)
                            .withField("properties",
                                    new RecordStruct().withField("name", "Prefix " + zc).withField("alias", zc))
                            .withField("geometry", new RecordStruct().withField("type", "MultiPolygon")
                                    .withField("coordinates", cords));

                    RecordStruct entry = new RecordStruct().withField("code", zc).withField("geo", feat)
                            .withField("center", center);

                    IOUtil.saveEntireFile2(dfolder.resolve("us-zips-" + zc + ".js"),
                            code + entry.toPrettyString() + ";");
                });

                break;
            }

            }
        } catch (Exception x) {
            System.out.println("CLI error: " + x);
        }
    }
}

From source file:eu.trentorise.opendata.josman.test.GitTest.java

@Test
public void testWalkRepo() throws IOException {
    File repoFile = createJosmanSampleRepo();

    FileRepositoryBuilder builder = new FileRepositoryBuilder();
    Repository repo = builder.setGitDir(repoFile).readEnvironment() // scan environment GIT_* variables
            .findGitDir() // scan up the file system tree
            .build();/*w  ww  . j av  a2 s .com*/

    //printFile(repo, tree, "*a.*");
    printDirectory(repo, "master", "src");

    // there is also FileMode.SYMLINK for symbolic links, but this is not handled here yet
    repo.close();
}

From source file:eu.trentorise.opendata.josman.test.GitTest.java

/**
 * Creates a sample josman repo/* ww  w .j ava2 s.c o  m*/
 *
 *
 * @return
 * @throws IOException
 * @throws GitAPIException
 */
private static File createJosmanSampleRepo() {
    Repository repository;
    try {
        repository = CookbookHelper.createNewRepository();

        LOG.log(Level.INFO, "Temporary repository at {0}", repository.getDirectory());

        createFiles(repository, "docs/README.md", "docs/CHANGES.md", "docs/img/a.jpg", "src/main/java/a.java",
                "src/main/java/b.java", "README.md", "LICENSE.txt");

        // and then commit the changes
        new Git(repository).commit().setMessage("Added test files").call();

        File dir = repository.getDirectory();

        repository.close();

        return dir;
    } catch (Exception ex) {
        throw new RuntimeException("Error while creating new repo!", ex);
    }

}

From source file:eu.trentorise.opendata.josman.test.GitTest.java

private static File createSampleGitRepo() throws IOException, GitAPIException {
    Repository repository = CookbookHelper.createNewRepository();

    System.out.println("Temporary repository at " + repository.getDirectory());

    // create the file
    File myfile = new File(repository.getDirectory().getParent(), "testfile");
    myfile.createNewFile();/*from w  ww  .  j  a v  a2 s  .  c o m*/

    // run the add-call
    new Git(repository).add().addFilepattern("testfile").call();

    // and then commit the changes
    new Git(repository).commit().setMessage("Added testfile").call();

    LOG.info("Added file " + myfile + " to repository at " + repository.getDirectory());

    File dir = repository.getDirectory();

    repository.close();

    return dir;

}

From source file:git_manager.tool.GitOperations.java

License:Open Source License

void printDiffWithHead() {
    Repository repository = git.getRepository();
    ObjectId oldHead;/*from   www.  j  a v  a  2 s .co  m*/
    try {
        oldHead = repository.resolve("HEAD~1^{tree}");
        ObjectId head = repository.resolve("HEAD^{tree}");

        System.out.println("Printing diff between tree: " + oldHead + " and " + head);

        // prepare the two iterators to compute the diff between
        ObjectReader reader = repository.newObjectReader();
        CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
        oldTreeIter.reset(reader, oldHead);
        CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
        newTreeIter.reset(reader, head);

        // finally get the list of changed files
        List<DiffEntry> diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
        for (DiffEntry entry : diffs) {
            System.out.println("Entry: " + entry);
        }
        System.out.println("----------------------");

        DiffFormatter df = new DiffFormatter(new ByteArrayOutputStream());
        df.setRepository(git.getRepository());
        List<DiffEntry> entries = df.scan(oldTreeIter, newTreeIter);

        for (DiffEntry entry : entries) {
            System.out.println(entry);
        }

        System.out.println("Done");

        repository.close();
    } catch (RevisionSyntaxException e) {
        e.printStackTrace();
    } catch (AmbiguousObjectException e) {
        e.printStackTrace();
    } catch (IncorrectObjectTypeException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GitAPIException e) {
        e.printStackTrace();
    }
}

From source file:i5.las2peer.services.codeGenerationService.generators.MicroserviceGenerator.java

/**
 * /*from   www.  j ava  2 s  .  co m*/
 * Creates source code from a CAE microservice model and pushes it to GitHub.
 * 
 * @param microservice the microservice model
 * @param templateRepositoryName the name of the template repository on GitHub
 * @param gitHubOrganization the organization that is used in the CAE
 * @param gitHubUser the CAE user
 * @param gitHubUserMail the mail of the CAE user
 * @param gitHubPassword the password of the CAE user
 * 
 * @throws GitHubException thrown if anything goes wrong during this process. Wraps around all
 *         other exceptions and prints their message.
 * 
 */
public static void createSourceCode(Microservice microservice, String templateRepositoryName,
        String gitHubOrganization, String gitHubUser, String gitHubUserMail, String gitHubPassword)
        throws GitHubException {

    // variables to be closed in the final block
    Repository microserviceRepository = null;
    TreeWalk treeWalk = null;

    // helper variables
    String packageName = microservice.getResourceName().substring(0, 1).toLowerCase()
            + microservice.getResourceName().substring(1);
    // get the port: skip first 6 characters for search (http: / https:)
    String port = microservice.getPath().substring(microservice.getPath().indexOf(":", 6) + 1,
            microservice.getPath().indexOf("/", microservice.getPath().indexOf(":", 6)));

    // variables holding content to be modified and added to repository later
    String projectFile = null;
    BufferedImage logo = null;
    String readMe = null;
    String license = null;
    String buildFile = null;
    String startScriptWindows = null;
    String startScriptUnix = null;
    String userAgentGeneratorWindows = null;
    String userAgentGeneratorUnix = null;
    String nodeInfo = null;
    String antServiceProperties = null;
    String antUserProperties = null;
    String ivy = null;
    String ivySettings = null;
    String serviceProperties = null;
    String webConnectorConfig = null;
    String gitignore = null;
    String classpath = null;
    String databaseManager = null;
    String serviceClass = null;
    String serviceTest = null;
    String genericHttpMethod = null;
    String genericApiResponse = null;
    String genericHttpResponse = null;
    String genericTestCase = null;
    String databaseConfig = null;
    String databaseInstantiation = null;
    String serviceInvocation = null;
    String databaseScript = null;
    String genericTable = null;

    try {
        PersonIdent caeUser = new PersonIdent(gitHubUser, gitHubUserMail);
        String repositoryName = "microservice-" + microservice.getName().replace(" ", "-");
        microserviceRepository = generateNewRepository(repositoryName, gitHubOrganization, gitHubUser,
                gitHubPassword);

        try {
            // now load the TreeWalk containing the template repository content
            treeWalk = getTemplateRepositoryContent(templateRepositoryName, gitHubOrganization);
            treeWalk.setFilter(PathFilter.create("backend/"));
            ObjectReader reader = treeWalk.getObjectReader();
            // walk through the tree and retrieve the needed templates
            while (treeWalk.next()) {
                ObjectId objectId = treeWalk.getObjectId(0);
                ObjectLoader loader = reader.open(objectId);

                switch (treeWalk.getNameString()) {
                // start with the "easy" replacements, and store the other template files for later
                case ".project":
                    projectFile = new String(loader.getBytes(), "UTF-8");
                    projectFile = projectFile.replace("$Microservice_Name$", microservice.getName());
                    break;
                case "logo_services.png":
                    logo = ImageIO.read(loader.openStream());
                    break;
                case "README.md":
                    readMe = new String(loader.getBytes(), "UTF-8");
                    readMe = readMe.replace("$Repository_Name$", repositoryName);
                    readMe = readMe.replace("$Organization_Name$", gitHubOrganization);
                    readMe = readMe.replace("$Microservice_Name$", microservice.getName());
                    break;
                case "LICENSE.txt":
                    license = new String(loader.getBytes(), "UTF-8");
                    break;
                case "build.xml":
                    buildFile = new String(loader.getBytes(), "UTF-8");
                    buildFile = buildFile.replace("$Microservice_Name$", microservice.getName());
                    break;
                case "start_network.bat":
                    startScriptWindows = new String(loader.getBytes(), "UTF-8");
                    startScriptWindows = startScriptWindows.replace("$Resource_Name$",
                            microservice.getResourceName());
                    startScriptWindows = startScriptWindows.replace("$Lower_Resource_Name$", packageName);
                    startScriptWindows = startScriptWindows.replace("$Microservice_Version$",
                            microservice.getVersion() + "");
                    break;
                case "start_network.sh":
                    startScriptUnix = new String(loader.getBytes(), "UTF-8");
                    startScriptUnix = startScriptUnix.replace("$Resource_Name$",
                            microservice.getResourceName());
                    startScriptUnix = startScriptUnix.replace("$Lower_Resource_Name$", packageName);
                    startScriptUnix = startScriptUnix.replace("$Microservice_Version$",
                            microservice.getVersion() + "");
                    break;
                case "start_UserAgentGenerator.bat":
                    userAgentGeneratorWindows = new String(loader.getBytes(), "UTF-8");
                    break;
                case "start_UserAgentGenerator.sh":
                    userAgentGeneratorUnix = new String(loader.getBytes(), "UTF-8");
                    break;
                case "nodeInfo.xml":
                    nodeInfo = new String(loader.getBytes(), "UTF-8");
                    nodeInfo = nodeInfo.replace("$Developer$", microservice.getDeveloper());
                    nodeInfo = nodeInfo.replace("$Resource_Name$", microservice.getResourceName());
                    break;
                case "service.properties":
                    antServiceProperties = new String(loader.getBytes(), "UTF-8");
                    antServiceProperties = antServiceProperties.replace("$Microservice_Version$",
                            microservice.getVersion() + "");
                    antServiceProperties = antServiceProperties.replace("$Lower_Resource_Name$", packageName);
                    antServiceProperties = antServiceProperties.replace("$Resource_Name$",
                            microservice.getResourceName());
                    antServiceProperties = antServiceProperties.replace("$Microservice_Version$",
                            microservice.getVersion() + "");
                    break;
                case "user.properties":
                    antUserProperties = new String(loader.getBytes(), "UTF-8");
                    break;
                case "ivy.xml":
                    ivy = new String(loader.getBytes(), "UTF-8");
                    // add mysql dependency only if a database exists
                    if (microservice.getDatabase() != null) {
                        ivy = ivy.replace("$MySQL_Dependencies$",
                                "<dependency org=\"mysql\" name=\"mysql-connector-java\" rev=\"5.1.6\" />\n"
                                        + "    <dependency org=\"org.apache.commons\" name=\"commons-pool2\" rev=\"2.2\" />\n"
                                        + "    <dependency org=\"org.apache.commons\" name=\"commons-dbcp2\" rev=\"2.0\" />");
                    } else {
                        ivy = ivy.replace("    $MySQL_Dependencies$\n", "");
                    }
                    break;
                case "ivysettings.xml":
                    ivySettings = new String(loader.getBytes(), "UTF-8");
                    break;
                case "i5.las2peer.services.servicePackage.ServiceClass.properties":
                    serviceProperties = new String(loader.getBytes(), "UTF-8");
                    // if database does not exist, clear the file
                    if (microservice.getDatabase() == null) {
                        serviceProperties = "";
                    } else {
                        serviceProperties = serviceProperties.replace("$Database_Address$",
                                microservice.getDatabase().getAddress());
                        serviceProperties = serviceProperties.replace("$Database_Schema$",
                                microservice.getDatabase().getSchema());
                        serviceProperties = serviceProperties.replace("$Database_User$",
                                microservice.getDatabase().getLoginName());
                        serviceProperties = serviceProperties.replace("$Database_Password$",
                                microservice.getDatabase().getLoginPassword());
                    }
                case "i5.las2peer.webConnector.WebConnector.properties":
                    webConnectorConfig = new String(loader.getBytes(), "UTF-8");
                    webConnectorConfig = webConnectorConfig.replace("$HTTP_Port$", port);
                    break;
                case ".gitignore":
                    gitignore = new String(loader.getBytes(), "UTF-8");
                    break;
                case ".classpath":
                    classpath = new String(loader.getBytes(), "UTF-8");
                    if (microservice.getDatabase() != null) {
                        classpath = classpath.replace("$Database_Libraries$",
                                "<classpathentry kind=\"lib\" path=\"lib/mysql-connector-java-5.1.6.jar\"/>\n"
                                        + "  <classpathentry kind=\"lib\" path=\"lib/commons-dbcp2-2.0.jar\"/>");
                    } else {
                        classpath = classpath.replace("$Database_Libraries$\n", "");
                    }
                    break;
                case "DatabaseManager.java":
                    if (microservice.getDatabase() != null) {
                        databaseManager = new String(loader.getBytes(), "UTF-8");
                        databaseManager = databaseManager.replace("$Lower_Resource_Name$", packageName);
                    }
                    break;
                case "ServiceClass.java":
                    serviceClass = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericHTTPMethod.txt":
                    genericHttpMethod = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericHTTPResponse.txt":
                    genericHttpResponse = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericApiResponse.txt":
                    genericApiResponse = new String(loader.getBytes(), "UTF-8");
                    break;
                case "ServiceTest.java":
                    serviceTest = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericTestMethod.txt":
                    genericTestCase = new String(loader.getBytes(), "UTF-8");
                    break;
                case "databaseConfig.txt":
                    databaseConfig = new String(loader.getBytes(), "UTF-8");
                    break;
                case "databaseInstantiation.txt":
                    databaseInstantiation = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericServiceInvocation.txt":
                    serviceInvocation = new String(loader.getBytes(), "UTF-8");
                    break;
                case "database.sql":
                    databaseScript = new String(loader.getBytes(), "UTF-8");
                    break;
                case "genericTable.txt":
                    genericTable = new String(loader.getBytes(), "UTF-8");
                    break;
                }
            }
        } catch (Exception e) {
            logger.printStackTrace(e);
            throw new GitHubException(e.getMessage());
        }

        // generate service class and test
        String repositoryLocation = "https://github.com/" + gitHubOrganization + "/" + repositoryName;
        serviceClass = generateNewServiceClass(serviceClass, microservice, repositoryLocation,
                genericHttpMethod, genericApiResponse, genericHttpResponse, databaseConfig,
                databaseInstantiation, serviceInvocation);
        serviceTest = generateNewServiceTest(serviceTest, microservice, genericTestCase);
        if (microservice.getDatabase() != null) {
            databaseScript = generateDatabaseScript(databaseScript, genericTable, microservice);
        }
        // add files to new repository
        // configuration and build stuff
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ivy/", "ivy.xml", ivy);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ivy/",
                "ivysettings.xml", ivySettings);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", "build.xml", buildFile);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ant_configuration/",
                "user.properties", antUserProperties);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/ant_configuration/",
                "service.properties", antServiceProperties);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/", "nodeInfo.xml",
                nodeInfo);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".project",
                projectFile);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".gitignore",
                gitignore);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", ".classpath",
                classpath);
        // property files
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/",
                "i5.las2peer.services." + packageName + "." + microservice.getResourceName() + ".properties",
                serviceProperties);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "etc/",
                "i5.las2peer.webConnector.WebConnector.properties", webConnectorConfig);
        // scripts
        microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_network.bat",
                startScriptWindows);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/", "start_network.sh",
                startScriptUnix);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/",
                "start_UserAgentGenerator.bat", userAgentGeneratorWindows);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "bin/",
                "start_UserAgentGenerator.sh", userAgentGeneratorUnix);
        // doc
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", "README.md", readMe);
        microserviceRepository = createTextFileInRepository(microserviceRepository, "", "LICENSE.txt", license);
        microserviceRepository = createImageFileInRepository(microserviceRepository, "img/", "logo.png", logo);
        // source code
        if (databaseManager != null) {
            microserviceRepository = createTextFileInRepository(microserviceRepository,
                    "src/main/i5/las2peer/services/" + packageName + "/database/", "DatabaseManager.java",
                    databaseManager);
            // database script (replace spaces in filename for better usability later on)
            microserviceRepository = createTextFileInRepository(microserviceRepository, "db/",
                    microservice.getName().replace(" ", "_") + "_create_tables.sql", databaseScript);
        }
        microserviceRepository = createTextFileInRepository(microserviceRepository,
                "src/main/i5/las2peer/services/" + packageName + "/", microservice.getResourceName() + ".java",
                serviceClass);
        microserviceRepository = createTextFileInRepository(microserviceRepository,
                "src/test/i5/las2peer/services/" + packageName + "/",
                microservice.getResourceName() + "Test.java", serviceTest);
        // commit files
        try {
            Git.wrap(microserviceRepository).commit()
                    .setMessage("Generated microservice version " + microservice.getVersion())
                    .setCommitter(caeUser).call();
        } catch (Exception e) {
            logger.printStackTrace(e);
            throw new GitHubException(e.getMessage());
        }

        // push (local) repository content to GitHub repository
        try {
            pushToRemoteRepository(microserviceRepository, gitHubUser, gitHubPassword);
        } catch (Exception e) {
            logger.printStackTrace(e);
            throw new GitHubException(e.getMessage());
        }

        // close all open resources
    } finally {
        microserviceRepository.close();
        treeWalk.close();
    }
}