Search in sources :

Example 36 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project camel by apache.

the class GitProducer method doPull.

protected void doPull(Exchange exchange, String operation) throws Exception {
    PullResult result = null;
    try {
        if (ObjectHelper.isEmpty(endpoint.getRemoteName())) {
            throw new IllegalArgumentException("Remote name must be specified to execute " + operation);
        }
        if (ObjectHelper.isNotEmpty(endpoint.getBranchName())) {
            git.checkout().setCreateBranch(false).setName(endpoint.getBranchName()).call();
        }
        if (ObjectHelper.isNotEmpty(endpoint.getUsername()) && ObjectHelper.isNotEmpty(endpoint.getPassword())) {
            UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(endpoint.getUsername(), endpoint.getPassword());
            result = git.pull().setCredentialsProvider(credentials).setRemote(endpoint.getRemoteName()).call();
        } else {
            result = git.pull().setRemote(endpoint.getRemoteName()).call();
        }
    } catch (Exception e) {
        LOG.error("There was an error in Git " + operation + " operation");
        throw e;
    }
    updateExchange(exchange, result);
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) PullResult(org.eclipse.jgit.api.PullResult) IOException(java.io.IOException)

Example 37 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project camel by apache.

the class GitProducer method doClone.

protected void doClone(Exchange exchange, String operation) throws Exception {
    Git result = null;
    if (ObjectHelper.isEmpty(endpoint.getLocalPath())) {
        throw new IllegalArgumentException("Local path must specified to execute " + operation);
    }
    try {
        File localRepo = new File(endpoint.getLocalPath(), "");
        if (!localRepo.exists()) {
            if (ObjectHelper.isNotEmpty(endpoint.getUsername()) && ObjectHelper.isNotEmpty(endpoint.getPassword())) {
                UsernamePasswordCredentialsProvider credentials = new UsernamePasswordCredentialsProvider(endpoint.getUsername(), endpoint.getPassword());
                result = Git.cloneRepository().setCredentialsProvider(credentials).setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), "")).call();
            } else {
                result = Git.cloneRepository().setURI(endpoint.getRemotePath()).setDirectory(new File(endpoint.getLocalPath(), "")).call();
            }
        } else {
            throw new IllegalArgumentException("The local repository directory already exists");
        }
    } catch (Exception e) {
        LOG.error("There was an error in Git " + operation + " operation");
        throw e;
    } finally {
        if (ObjectHelper.isNotEmpty(result)) {
            result.close();
        }
    }
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) File(java.io.File) IOException(java.io.IOException)

Example 38 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project searchcode-server by boyter.

the class IndexGitRepoJob method updateGitRepository.

/**
     * Update a git repository and return if it has changed and the differences
     */
public RepositoryChanged updateGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean changed = false;
    List<String> changedFiles = new ArrayList<>();
    List<String> deletedFiles = new ArrayList<>();
    Singleton.getLogger().info("Attempting to pull latest from " + repoRemoteLocation + " for " + repoName);
    Repository localRepository = null;
    Git git = null;
    try {
        localRepository = new FileRepository(new File(repoLocations + "/" + repoName + "/.git"));
        Ref head = localRepository.getRef("HEAD");
        git = new Git(localRepository);
        git.reset();
        git.clean();
        PullCommand pullCmd = git.pull();
        if (useCredentials) {
            pullCmd.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }
        pullCmd.call();
        Ref newHEAD = localRepository.getRef("HEAD");
        if (!head.toString().equals(newHEAD.toString())) {
            changed = true;
            // Get the differences between the the heads which we updated at
            // and use these to just update the differences between them
            ObjectId oldHead = localRepository.resolve(head.getObjectId().getName() + "^{tree}");
            ObjectId newHead = localRepository.resolve(newHEAD.getObjectId().getName() + "^{tree}");
            ObjectReader reader = localRepository.newObjectReader();
            CanonicalTreeParser oldTreeIter = new CanonicalTreeParser();
            oldTreeIter.reset(reader, oldHead);
            CanonicalTreeParser newTreeIter = new CanonicalTreeParser();
            newTreeIter.reset(reader, newHead);
            List<DiffEntry> entries = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call();
            for (DiffEntry entry : entries) {
                if ("DELETE".equals(entry.getChangeType().name())) {
                    deletedFiles.add(FilenameUtils.separatorsToUnix(entry.getOldPath()));
                } else {
                    changedFiles.add(FilenameUtils.separatorsToUnix(entry.getNewPath()));
                }
            }
        }
    } catch (IOException | GitAPIException | InvalidPathException ex) {
        changed = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(localRepository);
        Singleton.getHelpers().closeQuietly(git);
    }
    return new RepositoryChanged(changed, changedFiles, deletedFiles);
}
Also used : FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) PullCommand(org.eclipse.jgit.api.PullCommand) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) ArrayList(java.util.ArrayList) CanonicalTreeParser(org.eclipse.jgit.treewalk.CanonicalTreeParser) InvalidPathException(java.nio.file.InvalidPathException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) FileRepository(org.eclipse.jgit.internal.storage.file.FileRepository) Git(org.eclipse.jgit.api.Git) DiffEntry(org.eclipse.jgit.diff.DiffEntry)

Example 39 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project searchcode-server by boyter.

the class IndexGitRepoJob method cloneGitRepository.

/**
     * Clones the repository from scratch
     */
public RepositoryChanged cloneGitRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, String branch, boolean useCredentials) {
    boolean successful = false;
    Singleton.getLogger().info("Attempting to clone " + repoRemoteLocation);
    Git call = null;
    try {
        CloneCommand cloneCommand = Git.cloneRepository();
        cloneCommand.setURI(repoRemoteLocation);
        cloneCommand.setDirectory(new File(repoLocations + "/" + repoName + "/"));
        cloneCommand.setCloneAllBranches(true);
        cloneCommand.setBranch(branch);
        if (useCredentials) {
            cloneCommand.setCredentialsProvider(new UsernamePasswordCredentialsProvider(repoUserName, repoPassword));
        }
        call = cloneCommand.call();
        successful = true;
    } catch (GitAPIException | InvalidPathException ex) {
        successful = false;
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " cloneGitRepository for " + repoName + "\n with message: " + ex.getMessage());
    } finally {
        Singleton.getHelpers().closeQuietly(call);
    }
    RepositoryChanged repositoryChanged = new RepositoryChanged(successful);
    repositoryChanged.setClone(true);
    return repositoryChanged;
}
Also used : CloneCommand(org.eclipse.jgit.api.CloneCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) RepositoryChanged(com.searchcode.app.dto.RepositoryChanged) UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) InvalidPathException(java.nio.file.InvalidPathException)

Example 40 with UsernamePasswordCredentialsProvider

use of org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider in project azure-sdk-for-java by Azure.

the class ManageLinuxWebAppSourceControl method runSample.

/**
     * Main function which runs the actual sample.
     * @param azure instance of the azure client
     * @return true if sample runs successfully
     */
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix = ".azurewebsites.net";
    final String app1Name = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name = SdkContext.randomResourceName("webapp2-", 20);
    final String app3Name = SdkContext.randomResourceName("webapp3-", 20);
    final String app4Name = SdkContext.randomResourceName("webapp4-", 20);
    final String app1Url = app1Name + suffix;
    final String app2Url = app2Name + suffix;
    final String app3Url = app3Name + suffix;
    final String app4Url = app4Name + suffix;
    final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24);
    try {
        //============================================================
        // Create a web app with a new app service plan
        System.out.println("Creating web app " + app1Name + " in resource group " + rgName + "...");
        WebApp app1 = azure.webApps().define(app1Name).withRegion(Region.US_WEST).withNewResourceGroup(rgName).withNewLinuxPlan(PricingTier.STANDARD_S1).withPublicDockerHubImage("tomcat:8-jre8").withStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"").withAppSetting("PORT", "8080").create();
        System.out.println("Created web app " + app1.name());
        Utils.print(app1);
        //============================================================
        // Deploy to app 1 through FTP
        System.out.println("Deploying helloworld.war to " + app1Name + " through FTP...");
        Utils.uploadFileToFtp(app1.getPublishingProfile(), "helloworld.war", ManageLinuxWebAppSourceControl.class.getResourceAsStream("/helloworld.war"));
        System.out.println("Deployment helloworld.war to web app " + app1.name() + " completed");
        Utils.print(app1);
        // warm up
        System.out.println("Warming up " + app1Url + "/helloworld...");
        curl("http://" + app1Url + "/helloworld");
        Thread.sleep(5000);
        System.out.println("CURLing " + app1Url + "/helloworld...");
        System.out.println(curl("http://" + app1Url + "/helloworld"));
        //============================================================
        // Create a second web app with local git source control
        System.out.println("Creating another web app " + app2Name + " in resource group " + rgName + "...");
        AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId());
        WebApp app2 = azure.webApps().define(app2Name).withExistingLinuxPlan(plan).withExistingResourceGroup(rgName).withPublicDockerHubImage("tomcat:8-jre8").withStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"").withAppSetting("PORT", "8080").withLocalGitSourceControl().create();
        System.out.println("Created web app " + app2.name());
        Utils.print(app2);
        //============================================================
        // Deploy to app 2 through local Git
        System.out.println("Deploying a local Tomcat source to " + app2Name + " through Git...");
        PublishingProfile profile = app2.getPublishingProfile();
        Git git = Git.init().setDirectory(new File(ManageLinuxWebAppSourceControl.class.getResource("/azure-samples-appservice-helloworld/").getPath())).call();
        git.add().addFilepattern(".").call();
        git.commit().setMessage("Initial commit").call();
        PushCommand command = git.push();
        command.setRemote(profile.gitUrl());
        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(profile.gitUsername(), profile.gitPassword()));
        command.setRefSpecs(new RefSpec("master:master"));
        command.setForce(true);
        command.call();
        System.out.println("Deployment to web app " + app2.name() + " completed");
        Utils.print(app2);
        // warm up
        System.out.println("Warming up " + app2Url + "/helloworld...");
        curl("http://" + app2Url + "/helloworld");
        Thread.sleep(5000);
        System.out.println("CURLing " + app2Url + "/helloworld...");
        System.out.println(curl("http://" + app2Url + "/helloworld"));
        //============================================================
        // Create a 3rd web app with a public GitHub repo in Azure-Samples
        System.out.println("Creating another web app " + app3Name + "...");
        WebApp app3 = azure.webApps().define(app3Name).withExistingLinuxPlan(plan).withNewResourceGroup(rgName).withPublicDockerHubImage("tomcat:8-jre8").withStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"").withAppSetting("PORT", "8080").defineSourceControl().withPublicGitRepository("https://github.com/azure-appservice-samples/java-get-started").withBranch("master").attach().create();
        System.out.println("Created web app " + app3.name());
        Utils.print(app3);
        // warm up
        System.out.println("Warming up " + app3Url + "...");
        curl("http://" + app3Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app3Url + "...");
        System.out.println(curl("http://" + app3Url));
        //============================================================
        // Create a 4th web app with a personal GitHub repo and turn on continuous integration
        System.out.println("Creating another web app " + app4Name + "...");
        WebApp app4 = azure.webApps().define(app4Name).withExistingLinuxPlan(plan).withExistingResourceGroup(rgName).withPublicDockerHubImage("tomcat:8-jre8").withStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"").withAppSetting("PORT", "8080").create();
        System.out.println("Created web app " + app4.name());
        Utils.print(app4);
        // warm up
        System.out.println("Warming up " + app4Url + "...");
        curl("http://" + app4Url);
        Thread.sleep(5000);
        System.out.println("CURLing " + app4Url + "...");
        System.out.println(curl("http://" + app4Url));
        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            System.out.println("Deleted Resource Group: " + rgName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
Also used : UsernamePasswordCredentialsProvider(org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider) Git(org.eclipse.jgit.api.Git) RefSpec(org.eclipse.jgit.transport.RefSpec) PublishingProfile(com.microsoft.azure.management.appservice.PublishingProfile) File(java.io.File) PushCommand(org.eclipse.jgit.api.PushCommand) IOException(java.io.IOException) WebApp(com.microsoft.azure.management.appservice.WebApp) AppServicePlan(com.microsoft.azure.management.appservice.AppServicePlan)

Aggregations

UsernamePasswordCredentialsProvider (org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider)76 Git (org.eclipse.jgit.api.Git)47 File (java.io.File)34 CredentialsProvider (org.eclipse.jgit.transport.CredentialsProvider)23 IOException (java.io.IOException)19 Test (org.junit.Test)18 CloneCommand (org.eclipse.jgit.api.CloneCommand)17 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)15 RepositoryModel (com.gitblit.models.RepositoryModel)12 PushResult (org.eclipse.jgit.transport.PushResult)12 RemoteRefUpdate (org.eclipse.jgit.transport.RemoteRefUpdate)9 FileOutputStream (java.io.FileOutputStream)8 PushCommand (org.eclipse.jgit.api.PushCommand)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 BufferedWriter (java.io.BufferedWriter)7 OutputStreamWriter (java.io.OutputStreamWriter)7 Date (java.util.Date)7 Ref (org.eclipse.jgit.lib.Ref)7 Repository (org.eclipse.jgit.lib.Repository)7 URIish (org.eclipse.jgit.transport.URIish)7