Example usage for org.eclipse.jgit.transport UsernamePasswordCredentialsProvider UsernamePasswordCredentialsProvider

List of usage examples for org.eclipse.jgit.transport UsernamePasswordCredentialsProvider UsernamePasswordCredentialsProvider

Introduction

In this page you can find the example usage for org.eclipse.jgit.transport UsernamePasswordCredentialsProvider UsernamePasswordCredentialsProvider.

Prototype

public UsernamePasswordCredentialsProvider(String username, char[] password) 

Source Link

Document

Initialize the provider with a single username and password.

Usage

From source file:am.ik.categolj3.api.git.GitProperties.java

License:Apache License

public Optional<UsernamePasswordCredentialsProvider> credentialsProvider() {
    if (username == null || password == null) {
        return Optional.empty();
    }//from   w w  w.  jav  a  2s . c  om
    return Optional.of(new UsernamePasswordCredentialsProvider(username, password));
}

From source file:bluej.groupwork.git.GitProvider.java

License:Open Source License

@Override
public TeamworkCommandResult checkConnection(TeamSettings settings) {

    try {/* w ww  .  jav  a 2s .c o m*/
        String gitUrl = makeGitUrl(settings);

        //perform a lsRemote on the remote git repo.
        LsRemoteCommand lsRemoteCommand = Git.lsRemoteRepository();
        UsernamePasswordCredentialsProvider cp = new UsernamePasswordCredentialsProvider(settings.getUserName(),
                settings.getPassword()); // set a configuration with username and password.
        lsRemoteCommand.setRemote(gitUrl); //configure remote repository address.
        lsRemoteCommand.setCredentialsProvider(cp); //associate the repository to the username and password.
        lsRemoteCommand.setTags(false); //disable refs/tags in reference results
        lsRemoteCommand.setHeads(false); //disable refs/heads in reference results

        //It seems that ssh host fingerprint check is not working properly. 
        //Disable it in a ssh connection.
        if (gitUrl.startsWith("ssh")) {
            SshSessionFactory sshSessionFactory = new JschConfigSessionFactory() {
                @Override
                protected void configure(OpenSshConfig.Host host, Session sn) {
                    java.util.Properties config = new java.util.Properties();
                    config.put("StrictHostKeyChecking", "no");
                    sn.setConfig(config);
                }

                @Override
                protected JSch createDefaultJSch(FS fs) throws JSchException {
                    return super.createDefaultJSch(fs);
                }
            };

            lsRemoteCommand.setTransportConfigCallback((Transport t) -> {
                SshTransport sshTransport = (SshTransport) t;
                sshTransport.setSshSessionFactory(sshSessionFactory);
            });
        }

        lsRemoteCommand.call(); //executes the lsRemote commnand.
    } catch (GitAPIException ex) {
        return new TeamworkCommandError(ex.getMessage(), ex.getLocalizedMessage());
    } catch (UnsupportedSettingException ex) {
        return new TeamworkCommandUnsupportedSetting(ex.getMessage());
    }
    //if we got here, it means the command was successful.
    return new TeamworkCommandResult();
}

From source file:bluej.groupwork.git.GitRepository.java

License:Open Source License

public UsernamePasswordCredentialsProvider getCredentialsProvider() {
    UsernamePasswordCredentialsProvider cp = new UsernamePasswordCredentialsProvider(userName, password); // set a configuration with username and password.
    return cp;/*from www .  ja v a2 s  . c om*/
}

From source file:br.com.raffs.rundeck.plugin.Deployment.java

License:Apache License

/**
 * Execute a step on Node/*  w  ww .jav  a2  s  . c  o m*/
 */
public void executeStep(final PluginStepContext context, final Map<String, Object> configuration)
        throws StepException {

    // gitlab_repo is a required parameters.
    if (gitlab_repo == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_repo variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_branch == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_branch variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_username == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_username variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // gitlab_repo is a required parameters.
    if (gitlab_password == null)
        throw new StepException(
                "Configuration failed, missing the gitlab_password variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // openshift_Server is a required parameters.
    if (openshift_server == null)
        throw new StepException(
                "Configuration failed, missing the openshift_server variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // openshift_apiversion is a required parameters.
    if (openshift_apiversion == null)
        throw new StepException(
                "Configuration failed, missing the openshift_apiversion variables on Rundeck Framework properties",
                StepFailureReason.ConfigurationFailure);

    // One of the two authentication is need
    if (openshift_username == null && openshift_password == null && openshift_token == null)
        throw new StepException(
                "Configuration failed, missing username/password and token variable which drive the "
                        + "Openshift Authentication on Rundeck framework properties configuration file. ",
                StepFailureReason.ConfigurationFailure);

    // Define the temporary directory.
    String temp_dir = String.format("/tmp/ocdepl-%s", Long.toString(System.nanoTime()));
    String repo_dir = String.format("%s/%s", temp_dir, gitlab_deployment_directory);

    // Trying to Download the Deployment definition
    try {

        // Download the files from the Gitlab, when it's the Service Definition.
        System.out.println("Downloading repository: " + gitlab_repo + " ...");
        Git.cloneRepository().setURI(gitlab_repo).setDirectory(new File(temp_dir)).setBranch(gitlab_branch)
                .setCredentialsProvider(
                        new UsernamePasswordCredentialsProvider(gitlab_username, gitlab_password))
                .call();

        // Looking for the file on the plugins.
        String varsPath = null;
        for (String format : EXTENSION_SUPORTED) {
            String path = String.format("%s/%s/%s.%s", repo_dir, gitlab_variables_dir,
                    gitlab_deployment_environment, format);

            if (new File(path).exists()) {
                varsPath = path;
                break;
            }
        }

        // Looking for the deploymet variable
        String deploymentPath = null;
        for (String format : EXTENSION_SUPORTED) {
            String path = String.format("%s/%s.%s", repo_dir, gitlab_deployment_file, format);

            if (new File(path).exists()) {
                deploymentPath = path;
                break;
            }
        }

        // Proper way to handle errors
        if (deploymentPath == null) {
            String files = "";
            for (String format : EXTENSION_SUPORTED) {
                files = files + String.format("%s/%s.%s,", repo_dir, gitlab_deployment_file, format);
            }

            throw new StepException(
                    String.format("Not able to found any of the file list: %s on %s", files, gitlab_repo),
                    StepFailureReason.ConfigurationFailure);
        }

        // Instance the rundeck vars object mapping
        // allocating the plugin parameters to usage.
        JSONObject rundeckVars = new JSONObject() {
            {
                put("plugin", new JSONObject() {
                    {
                        put("gitlab_repo", gitlab_repo);
                        put("gitlab_branch", gitlab_branch);
                        put("gitlab_username", gitlab_username);
                        put("gitlab_deployment_file", gitlab_deployment_file);
                        put("gitlab_variable_file", gitlab_deployment_environment);

                        put("openshift_server", openshift_server);
                        put("openshift_apiversion", openshift_apiversion);
                        put("openshift_project", openshift_project);
                        put("openshift_service", openshift_service);
                        put("openshift_username", openshift_username);
                    }
                });
            }
        };

        // Read the rundeck job parameters from the JOB Context
        HashMap<String, Map<String, String>> jobContext = (HashMap<String, Map<String, String>>) context
                .getDataContext();

        if (jobContext.get("option") != null) {
            rundeckVars.put("option", jobContext.get("option"));
        }

        // Read the environment variables into map of variables.
        Object vars = null;
        if (varsPath != null) {
            YamlReader varsReader = new YamlReader(new FileReader(varsPath));
            vars = varsReader.read();
        }

        //  Read the Deployment file using template-engine to validate the blocks and dynamic content
        JtwigTemplate template = JtwigTemplate.fileTemplate(new File(deploymentPath));
        JtwigModel model = JtwigModel.newModel().with("vars", vars).with("rundeck", rundeckVars);
        String deploymentFile = template.render(model);

        // Return the Deployment Configuration from the YAML file.
        Map deployment = (Map) new YamlReader(deploymentFile).read();
        JSONObject deployConfig = new JSONObject(deployment);

        // connect to the Openshift client
        System.out.print(String.format("Connecting to Openshift server: %s ...", openshift_server));

        // Define the Openshift
        OpenshiftClient oc = new OpenshiftClient().withProject(openshift_project).withService(openshift_service)
                .withServerUrl(openshift_server).withApiVersion(openshift_apiversion)
                .withTimeout(network_timeout).withToken(openshift_token).withUsername(openshift_username)
                .withPassword(openshift_password)

                .build();

        // Validate the service status
        int serverStatus;
        if ((serverStatus = oc.getServerStatus()) != 200) {
            throw new Exception(
                    String.format("[%d] Receive when trying to return server status", serverStatus));
        } else
            System.out.println("[OK]");

        // Validate whether the project exists.
        if (!oc.checkProject(openshift_project)) {
            throw new Exception(String.format(
                    "Appears that project does not exists, or access ir forbidden, %s", openshift_project));
        }

        // Create the project whether exists
        JSONObject newReleaseResponse;
        if (!oc.checkService(openshift_service)) {
            throw new StepException(
                    String.format("Unable to found the project: %s/%s !", openshift_project, openshift_service),
                    StepFailureReason.ConfigurationFailure);

        } else {

            // Update an already existed Deployment Configuration.
            JSONObject currentDeploy = oc.getDeploymentConfig();
            if (currentDeploy != null) {
                deployConfig.put("metadata", currentDeploy.getJSONObject("metadata"));

                int latestVersion = currentDeploy.getJSONObject("status").getInt("latestVersion");
                deployConfig.getJSONObject("status").put("latestVersion", ++latestVersion);

                if (deployConfig.has("statusCode"))
                    deployConfig.remove("statusCode");
                if (deployConfig.getJSONObject("spec").getJSONObject("template").getJSONObject("metadata")
                        .has("creationTimestamp")) {

                    deployConfig.getJSONObject("spec").getJSONObject("template").getJSONObject("metadata")
                            .remove("creationTimestamp");
                }

                newReleaseResponse = oc.setDeploymentConfig(deployConfig);
            } else {
                throw new Exception("Error on try to get the Deployment Configuration");
            }

        }

        // Watch the deployment
        if (newReleaseResponse.has("status")) {
            if (newReleaseResponse.getJSONObject("status").has("latestVersion")) {
                System.out.println(String.format("Deployment #%d running, this could take some while...",
                        newReleaseResponse.getJSONObject("status").getInt("latestVersion")));
            }
        }

        // Watching the Deployment of the Services.
        int attempts = 0;
        while (oc.notReady()) {
            if (attempts >= network_max_count_attemps) {
                throw new StepException("Openshift deployment took to long to finished. ",
                        StepFailureReason.PluginFailed);
            } else
                Thread.sleep(network_attempts_time_interval * 1000);

            attempts += 1;
        }

        dumpStatus(oc.getDeploymentConfig());
    } catch (Exception ex) {
        throw new StepException(
                "Error on trying automate Openshift Deployment & Provision\nError msg: " + ex.getMessage(),
                StepFailureReason.PluginFailed);
    } finally {

        // House cleaning when need.
        try {
            FileUtils.deleteDir(new File(repo_dir));
        } catch (Exception ex) {
            /* Do NOTHING */ }
    }
}

From source file:ch.sbb.releasetrain.git.GitRepoImpl.java

License:Apache License

private CredentialsProvider credentialsProvider() {
    return new UsernamePasswordCredentialsProvider(user, password);
}

From source file:com.athomas.androidkickstartr.util.GitHubber.java

License:Apache License

public Repository createCommit(File srcFolder, String applicationName) throws IOException, GitAPIException {
    Repository repository = repositoryService.createRepository(new Repository().setName(applicationName));

    String cloneUrl = repository.getCloneUrl();

    InitCommand init = new InitCommand();
    init.setDirectory(srcFolder);/* w w w . ja  va  2 s.  co m*/
    init.setBare(false);
    Git git = init.call();

    StoredConfig config = git.getRepository().getConfig();
    config.setString("remote", "origin", "url", cloneUrl);
    config.save();

    UsernamePasswordCredentialsProvider user = new UsernamePasswordCredentialsProvider(accessToken, "");
    git.add().addFilepattern(".").call();
    git.commit().setMessage(COMMIT_MESSAGE).call();
    git.push().setCredentialsProvider(user).call();

    return repository;
}

From source file:com.centurylink.mdw.dataaccess.file.VersionControlGit.java

License:Apache License

public void connect(String repositoryUrl, String user, String password, File localDir) throws IOException {

    if (repositoryUrl != null && !repositoryUrl.isEmpty()) {
        if (user == null) {
            this.repositoryUrl = repositoryUrl;
        } else {//w w  w . j ava  2  s  .c  o m
            int slashSlash = repositoryUrl.indexOf("//");
            this.repositoryUrl = repositoryUrl.substring(0, slashSlash + 2) + user + ":" + password + "@"
                    + repositoryUrl.substring(slashSlash + 2);
        }
    }

    this.localDir = localDir;
    localRepo = new FileRepository(new File(localDir + "/.git"));
    git = new Git(localRepo);
    if (credentialsProvider == null) {
        if (user != null && password != null)
            credentialsProvider = new UsernamePasswordCredentialsProvider(user, password);
    }

    file2id = new HashMap<File, Long>();
    id2file = new HashMap<Long, File>();
    pkg2versions = new HashMap<>();

    String idLengthProp = System.getProperty("com.centurylink.mdw.abbreviated.id.length");
    if (idLengthProp != null)
        ABBREVIATED_ID_LENGTH = Integer.parseInt(idLengthProp);
}

From source file:com.centurylink.mdw.service.rest.GitVcs.java

License:Apache License

/**
 * Authorization is performed based on the MDW user credentials.
 * Parameter is required: gitAction=pull
 * For pulling all assets, request path must match "*" (and only this options supports switching branches).
 * Git (read-only) credentials must be known to the server.  TODO: encrypt in prop file
 *///w w  w . java2s .c  om
@Override
@Path("/{gitPath}")
public JSONObject post(String path, JSONObject content, Map<String, String> headers)
        throws ServiceException, JSONException {

    String subpath = getSub(path);
    if (subpath == null)
        throw new ServiceException(HTTP_400_BAD_REQUEST, "Missing path segment: {path}");
    Query query = getQuery(path, headers);
    String action = query.getFilter("gitAction");
    if (action == null)
        throw new ServiceException(HTTP_400_BAD_REQUEST, "Missing parameter: gitAction");
    try {
        vcGit = getVersionControl();
        String requestPath = URLDecoder.decode(subpath, "UTF-8");
        assetPath = vcGit.getRelativePath(new File(getRequiredProperty(PropertyNames.MDW_ASSET_LOCATION)));
        branch = getRequiredProperty(PropertyNames.MDW_GIT_BRANCH);
        gitRoot = new File(getRequiredProperty(PropertyNames.MDW_GIT_LOCAL_PATH));
        logger.info("Git VCS branch: " + branch);

        int lastSlash = requestPath.lastIndexOf('/');
        String pkgName = null;
        String assetName = null;
        if (lastSlash > 0) {
            pkgName = requestPath.substring(0, lastSlash);
            assetName = requestPath.substring(lastSlash + 1);
        }

        if ("pull".equals(action)) {
            if (requestPath.equals("*")) {
                // importing all assets
                if (content.has("gitHard"))
                    hard = content.getBoolean("gitHard");

                GitVcs importer = this;
                thread = new Thread() {
                    @Override
                    public void run() {
                        this.setName("GitVcsAssetImporter-thread");
                        importer.importAssets();
                    }
                };
                thread.start();
            } else {
                if (pkgName != null) {
                    String pullPath = assetPath + "/" + pkgName.replace('.', '/');
                    if (assetName != null) {
                        pullPath = pullPath + "/" + assetName;
                        // TODO: implement asset pull
                        throw new ServiceException(ServiceException.NOT_IMPLEMENTED,
                                "Asset pull not implemented: " + pullPath);
                    } else {
                        // probably won't implement this
                        throw new ServiceException(ServiceException.NOT_IMPLEMENTED,
                                "Package pull not implemented: " + pullPath);
                    }
                } else {
                    throw new ServiceException(ServiceException.BAD_REQUEST, "Bad path: " + path);
                }
            }
        } else if ("push".equals(action)) {
            if (pkgName != null) {
                String pkgPath = assetPath + "/" + pkgName.replace('.', '/');
                if (assetName != null) {
                    if (!content.has("comment"))
                        throw new ServiceException(ServiceException.BAD_REQUEST, "Missing comment");
                    String comment = content.getString("comment");
                    if (content.has("user")) {
                        vcGit.setCredentialsProvider(new UsernamePasswordCredentialsProvider(
                                content.getString("user"), content.getString("password")));
                    }
                    vcGit.pull(branch);
                    List<String> commitPaths = new ArrayList<>();
                    commitPaths.add(pkgPath + "/" + assetName);
                    if (query.getBooleanFilter("includeMeta")) {
                        String metaPath = pkgPath + "/.mdw";
                        commitPaths.add(metaPath + "/versions");
                        commitPaths.add(metaPath + "/package.yaml");
                    }
                    vcGit.add(commitPaths);
                    vcGit.commit(commitPaths, comment);
                    vcGit.push();

                    // Update ASSET_REF with new commit (will trigger automatic import in other instances)
                    try (DbAccess dbAccess = new DbAccess()) {
                        Checkpoint cp = new Checkpoint(ApplicationContext.getAssetRoot(), vcGit,
                                vcGit.getCommit(), dbAccess.getConnection());
                        cp.updateRefs();
                    }
                } else {
                    // probably won't implement this
                    throw new ServiceException(ServiceException.NOT_IMPLEMENTED,
                            "Package push not implemented: " + pkgPath);
                }
            } else {
                throw new ServiceException(ServiceException.BAD_REQUEST, "Bad path: " + path);
            }
        }

        return null;
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ServiceException.INTERNAL_ERROR, ex.getMessage(), ex);
    }
}

From source file:com.chungkwong.jgitgui.RemoteTreeItem.java

License:Open Source License

private void gitPush() {
    ProgressDialog progressDialog = new ProgressDialog(
            java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PUSHING"));
    PushCommand command = ((Git) getParent().getValue()).push().setRemote(((RemoteConfig) getValue()).getName())
            .setProgressMonitor(progressDialog);
    TextField user = new TextField();
    PasswordField pass = new PasswordField();
    GridPane auth = new GridPane();
    auth.addRow(0,//ww  w  . ja v a2s.c om
            new Label(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("USER")),
            user);
    auth.addRow(1,
            new Label(java.util.ResourceBundle.getBundle("com/chungkwong/jgitgui/text").getString("PASSWORD")),
            pass);
    Dialog dialog = new Dialog();
    dialog.getDialogPane().setContent(auth);
    dialog.getDialogPane().getButtonTypes().addAll(ButtonType.CLOSE, ButtonType.APPLY);
    dialog.showAndWait();
    if (true) {
        command.setCredentialsProvider(new UsernamePasswordCredentialsProvider(user.getText(), pass.getText()));
    }
    new Thread(() -> {
        try {
            command.call();
        } catch (Exception ex) {
            Logger.getLogger(GitTreeItem.class.getName()).log(Level.SEVERE, null, ex);
            Platform.runLater(() -> {
                progressDialog.hide();
                Util.informUser(ex);
            });
        }
    }).start();
}

From source file:com.cloudbees.eclipse.dev.scm.egit.ForgeEGitSync.java

License:Open Source License

public static boolean internalSync(final ForgeInstance instance, final IProgressMonitor monitor) {

    if (!ForgeInstance.TYPE.GIT.equals(instance.type)) {
        return false;
    }/*w w w . j  a  v a2 s . com*/

    String u = instance.url;

    if (u == null) {
        throw new IllegalArgumentException("url not provided!");
    }

    final String url = reformatGitUrlToCurrent(u);

    try {
        monitor.beginTask("Cloning EGit repository '" + url + "'", 10);

        PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
            @Override
            public void run() {
                monitor.subTask("Checking already cloned local repositories");
                monitor.worked(2);

                if (isAlreadyCloned(url)) {
                    monitor.worked(8);
                    instance.status = ForgeInstance.STATUS.SYNCED;
                    return;
                }

                monitor.subTask("Cloning remote repository");
                monitor.worked(1);

                //Clipboard clippy = new Clipboard(Display.getCurrent());

                String clipurl = url;

                GitConnectionType type = CloudBeesUIPlugin.getDefault().getGitConnectionType();

                final GitRepositoryInfo repoInfo = new GitRepositoryInfo(clipurl);
                IRepositorySearchResult repoSearch = new IRepositorySearchResult() {
                    public GitRepositoryInfo getGitRepositoryInfo() throws NoRepositoryInfoException {
                        return repoInfo;
                    }
                };

                if (type.equals(GitConnectionType.HTTPS)) {

                    try {

                        String username = CloudBeesUIPlugin.getDefault().getPreferenceStore()
                                .getString(PreferenceConstants.P_EMAIL);
                        String password = CloudBeesUIPlugin.getDefault().readP();

                        CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider(
                                username, password);
                        UserPasswordCredentials credentials = new UserPasswordCredentials(username, password);

                        repoInfo.setShouldSaveCredentialsInSecureStore(true);
                        repoInfo.setCredentials(username, password);

                    } catch (StorageException e) {
                        e.printStackTrace();
                    }

                }

                GitImportWizard cloneWizard = new GitImportWizard(repoSearch);

                WizardDialog dlg = new WizardDialog(
                        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), cloneWizard);
                dlg.setHelpAvailable(true);
                int res = dlg.open();
                if (res == Window.OK) {
                    //         cloneWizard.runCloneOperation(getContainer());
                }

                //          int timeout = Activator.getDefault().getPreferenceStore().getInt(
                //              UIPreferences.REMOTE_CONNECTION_TIMEOUT);
                //      CloneOperation clone = Utils.createInstance(CloneOperation.class, new Class[] { URIish.class, Boolean.TYPE,
                //          Collection.class, File.class, String.class, String.class, Integer.TYPE }, new Object[] { new URIish(url),
                //          true, Collections.EMPTY_LIST, new File(""), null, "origin", 5000 });
                //      if (clone == null) {
                //        // old constructor didn't have timeout at the end
                //        clone = Utils.createInstance(CloneOperation.class, new Class[] { URIish.class, Boolean.TYPE, Collection.class,
                //            File.class, String.class, String.class }, new Object[] { new URIish(url), true, Collections.EMPTY_LIST,
                //            new File(""), null, "origin" });
                //      }

                monitor.worked(2);

                //      clone.run(monitor);
                //
                //      if (clone == null) {
                //        throw new CloudBeesException("Failed to create EGit clone operation");
                //      }

                monitor.worked(5);

                //    } catch (URISyntaxException e) {
                //      throw new CloudBeesException(e);
                //    } catch (InvocationTargetException e) {
                //      throw new CloudBeesException(e);
                //    } catch (InterruptedException e) {
                //      throw new CloudBeesException(e);

                /*          if (res == Window.OK) {
                            instance.status = ForgeInstance.STATUS.SYNCED;
                          } else {
                            instance.status = ForgeInstance.STATUS.SKIPPED;
                          }
                */
                // CHECK IF THE REPO NOW EXISTS. Even if it was cancelled at the final import, the repo might still exist

                if (isAlreadyCloned(url)) {
                    instance.status = ForgeInstance.STATUS.SYNCED;
                } else {
                    instance.status = ForgeInstance.STATUS.SKIPPED;
                }
                /*
                if (res == Window.OK) {
                          
                } else {
                          
                }*/

            }
        });

    } finally {
        monitor.worked(10);
        monitor.done();
    }

    if (instance != null && instance.status.equals(ForgeInstance.STATUS.SYNCED)) {
        return true;
    }
    return false;

}