當前位置: 首頁>>代碼示例>>Java>>正文


Java ACL.impersonate方法代碼示例

本文整理匯總了Java中hudson.security.ACL.impersonate方法的典型用法代碼示例。如果您正苦於以下問題:Java ACL.impersonate方法的具體用法?Java ACL.impersonate怎麽用?Java ACL.impersonate使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在hudson.security.ACL的用法示例。


在下文中一共展示了ACL.impersonate方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getRun

import hudson.security.ACL; //導入方法依賴的package包/類
@CheckForNull
public Run<?, ?> getRun() {
    if (StringUtils.isBlank(buildId)) {
        return null;
    }
    final Job<?, ?> job = getJob();
    if (job != null) {
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            return job.getBuild(buildId);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unable to retrieve run " + jobName + ":" + buildId, e);
        } finally {
            SecurityContextHolder.setContext(old);
        }
    }
    return null;
}
 
開發者ID:jenkinsci,項目名稱:dockerhub-notification-plugin,代碼行數:19,代碼來源:TriggerStore.java

示例2: abortShouldNotRetry

import hudson.security.ACL; //導入方法依賴的package包/類
@Issue("JENKINS-41276")
@Test
public void abortShouldNotRetry() throws Exception {
    r.jenkins.setSecurityRealm(r.createDummySecurityRealm());
    WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "int count = 0; retry(3) { echo 'trying '+(count++); semaphore 'start'; echo 'NotHere' } echo 'NotHere'", true));
    final WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    SemaphoreStep.waitForStart("start/1", b);
    ACL.impersonate(User.get("dev").impersonate(), new Runnable() {
        @Override public void run() {
            b.getExecutor().doStop();
        }
    });
    r.assertBuildStatus(Result.ABORTED, r.waitForCompletion(b));
    r.assertLogContains("trying 0", b);
    r.assertLogContains("Aborted by dev", b);
    r.assertLogNotContains("trying 1", b);
    r.assertLogNotContains("trying 2", b);
    r.assertLogNotContains("NotHere", b);

}
 
開發者ID:10000TB,項目名稱:Jenkins-Plugin-Examples,代碼行數:23,代碼來源:RetryStepTest.java

示例3: terminateRun

import hudson.security.ACL; //導入方法依賴的package包/類
private static void terminateRun(final WorkflowRun run) {
	ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Void, RuntimeException>() {
		@Override
		public Void call() throws RuntimeException {
			run.doTerm();
			Timer.get().schedule(new SafeTimerTask() {
				@Override
				public void doRun() {
					ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Void, RuntimeException>() {
						@Override
						public Void call() throws RuntimeException {
							run.doKill();
							return null;
						}
					});
				}
			}, 5, TimeUnit.SECONDS);
			return null;
		}
	});
}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:22,代碼來源:JenkinsUtils.java

示例4: cancelQueuedBuild

import hudson.security.ACL; //導入方法依賴的package包/類
@SuppressFBWarnings("SE_BAD_FIELD")
public static boolean cancelQueuedBuild(WorkflowJob job, Build build) {
	String buildUid = build.getMetadata().getUid();
	final Queue buildQueue = Jenkins.getActiveInstance().getQueue();
	for (final Queue.Item item : buildQueue.getItems()) {
		for (Cause cause : item.getCauses()) {
			if (cause instanceof BuildCause && ((BuildCause) cause).getUid().equals(buildUid)) {
				return ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Boolean, RuntimeException>() {
					@Override
					public Boolean call() throws RuntimeException {
						buildQueue.cancel(item);
						return true;
					}
				});
			}
		}
	}
	return cancelNotYetStartedBuild(job, build);
}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:20,代碼來源:JenkinsUtils.java

示例5: innerDeleteEventToJenkinsJobRun

import hudson.security.ACL; //導入方法依賴的package包/類
private static synchronized void innerDeleteEventToJenkinsJobRun(
        final Build build) throws Exception {
    final WorkflowJob job = getJobFromBuild(build);
    if (job != null) {
        ACL.impersonate(ACL.SYSTEM,
                new NotReallyRoleSensitiveCallable<Void, Exception>() {
                    @Override
                    public Void call() throws Exception {
                        cancelBuild(job, build, true);
                        return null;
                    }
                });
    } else {
        // in case build was created and deleted quickly, prior to seeing BC
        // event, clear out from pre-BC cache
        removeBuildFromNoBCList(build);
    }
}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:19,代碼來源:BuildWatcher.java

示例6: doImpersonate

import hudson.security.ACL; //導入方法依賴的package包/類
@RequirePOST
public HttpResponse doImpersonate(StaplerRequest req, @QueryParameter String name) {
    Authentication auth = Jenkins.getAuthentication();
    GrantedAuthority[] authorities = auth.getAuthorities();
    if (authorities == null || StringUtils.isBlank(name)) {
        return HttpResponses.redirectToContextRoot();
    }
    GrantedAuthority authority = null;
    for (GrantedAuthority a : authorities) {
        if (a.getAuthority().equals(name)) {
            authority = a;
            break;
        }
    }
    if (authority == null) {
        return HttpResponses.redirectToContextRoot();
    }
    if (!SecurityRealm.AUTHENTICATED_AUTHORITY.equals(authority)) {
        ACL.impersonate(new ImpersonationAuthentication(auth, authority, SecurityRealm.AUTHENTICATED_AUTHORITY));
    } else {
        ACL.impersonate(new ImpersonationAuthentication(auth, SecurityRealm.AUTHENTICATED_AUTHORITY));
    }
    return HttpResponses.redirectToContextRoot();
}
 
開發者ID:jenkinsci,項目名稱:impersonation-plugin,代碼行數:25,代碼來源:ImpersonationAction.java

示例7: scheduleJob

import hudson.security.ACL; //導入方法依賴的package包/類
public SlackTextMessage scheduleJob(String projectName) {
    ACL.impersonate(ACL.SYSTEM);
    String response = "";

    Project project =
        Jenkins.getInstance().getItemByFullName(projectName, Project.class);

    boolean success = false;

    if (project != null)
        success = project.scheduleBuild(new SlackWebhookCause(this.slackUser));
    else
        return new SlackTextMessage("Could not find project ("+projectName+")\n");

    if (success) 
        return new SlackTextMessage("Build scheduled for project "+ projectName+"\n");
    else
        return new SlackTextMessage("Build not scheduled due to an issue with Jenkins");
}
 
開發者ID:dpires,項目名稱:jenkins-slack-webhook-plugin,代碼行數:20,代碼來源:WebhookEndpoint.java

示例8: execute

import hudson.security.ACL; //導入方法依賴的package包/類
public void execute() {
    if (pushHook.getRepository() != null && pushHook.getRepository().getUrl() == null) {
        LOGGER.log(Level.WARNING, "No repository url found.");
        return;
    }

    if (project instanceof Job<?, ?>) {
        ACL.impersonate(ACL.SYSTEM, new TriggerNotifier(project, secretToken, Jenkins.getAuthentication()) {
            @Override
            protected void performOnPost(GitLabPushTrigger trigger) {
                trigger.onPost(pushHook);
            }
        });
        throw HttpResponses.ok();
    }
    if (project instanceof SCMSourceOwner) {
        ACL.impersonate(ACL.SYSTEM, new SCMSourceOwnerNotifier());
        throw HttpResponses.ok();
    }
    throw HttpResponses.errorWithoutStack(409, "Push Hook is not supported for this project");
}
 
開發者ID:jenkinsci,項目名稱:gitlab-plugin,代碼行數:22,代碼來源:PushBuildAction.java

示例9: getProject

import hudson.security.ACL; //導入方法依賴的package包/類
public Job<?, ?> getProject( String job, StaplerRequest req, StaplerResponse rsp )
    throws HttpResponses.HttpResponseException
{
    Job<?, ?> p;

    SecurityContext orig = ACL.impersonate( ACL.SYSTEM );
    try
    {
        p = Jenkins.getInstance().getItemByFullName( job, Job.class );
    }
    finally
    {
        SecurityContextHolder.setContext( orig );
    }

    if ( p == null )
    {
        throw org.kohsuke.stapler.HttpResponses.notFound();
    }

    return p;
}
 
開發者ID:yannickcr,項目名稱:jenkins-status-badges-plugin,代碼行數:23,代碼來源:BuildStatus.java

示例10: testRebuildNotAuthorized

import hudson.security.ACL; //導入方法依賴的package包/類
@Test
public void testRebuildNotAuthorized() throws Exception {
    FreeStyleProject projectA = jenkins.createFreeStyleProject("A");
    jenkins.createFreeStyleProject("B");
    projectA.getPublishersList().add(new BuildPipelineTrigger("B", null));

    jenkins.getInstance().rebuildDependencyGraph();
    DeliveryPipelineView view = new DeliveryPipelineView("View");
    jenkins.getInstance().addView(view);

    jenkins.getInstance().setSecurityRealm(jenkins.createDummySecurityRealm());
    GlobalMatrixAuthorizationStrategy gmas = new GlobalMatrixAuthorizationStrategy();
    gmas.add(Permission.READ, "devel");
    jenkins.getInstance().setAuthorizationStrategy(gmas);

    SecurityContext oldContext = ACL.impersonate(User.get("devel").impersonate());
    try {
        view.triggerRebuild("B", "1");
        fail();
    } catch (AuthenticationException e) {
        //Should throw this
    }
    SecurityContextHolder.setContext(oldContext);
}
 
開發者ID:Diabol,項目名稱:delivery-pipeline-plugin,代碼行數:25,代碼來源:DeliveryPipelineViewTest.java

示例11: findBuild

import hudson.security.ACL; //導入方法依賴的package包/類
/**
 * Function to finds the build with the unique build id.
 *
 * @param jobName
 *      The jenkins job or project name
 * @param buildNumber
 *      The jenkins build number
 * @return
 *      the build Run if found, otherwise return null
 */
public static Run<?,?> findBuild(String jobName, int buildNumber) {

    SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
    try {
        AbstractProject<?,?> project = Jenkins.getActiveInstance().getItemByFullName(jobName, AbstractProject.class);
        if (project != null){
            Run<?,?> run = project.getBuildByNumber(buildNumber);
            if (run != null) {
                return run;
            }
        }
        return null;
    } finally {
        SecurityContextHolder.setContext(oldContext);
    }
}
 
開發者ID:openstack-infra,項目名稱:gearman-plugin,代碼行數:27,代碼來源:GearmanPluginUtil.java

示例12: testPermissionWhenParameterized

import hudson.security.ACL; //導入方法依賴的package包/類
/**
 * When the source project name is parameterized, cannot check at configure time whether
 * the project is accessible.  In this case, permission check is done when the build runs.
 * Only jobs accessible to all authenticated users are allowed.
 */
@LocalData
@Test
public void testPermissionWhenParameterized() throws Exception {
    FreeStyleProject p = createProject("test$JOB", null, "", "", false, false, false, true);
    ParameterDefinition paramDef = new StringParameterDefinition("JOB", "job1");
    ParametersDefinitionProperty paramsDef = new ParametersDefinitionProperty(paramDef);
    p.addProperty(paramsDef);
    // Build step should succeed when this parameter expands to a job accessible
    // to authenticated users (even if triggered by anonymous, as in this case):
    SecurityContextHolder.clearContext();
    FreeStyleBuild b = p.scheduleBuild2(0, new UserCause(),
            new ParametersAction(new StringParameterValue("JOB", "Job2"))).get();
    assertFile(true, "foo2.txt", b);
    rule.assertBuildStatusSuccess(b);
    // Build step should fail for a job not accessible to all authenticated users,
    // even when accessible to the user starting the job, as in this case:
    SecurityContext old = ACL.impersonate(
            new UsernamePasswordAuthenticationToken("joe","joe"));
    try {
    b = p.scheduleBuild2(0, new UserCause(),
            new ParametersAction(new StringParameterValue("JOB", "Job"))).get();
    assertFile(false, "foo.txt", b);
        rule.assertBuildStatus(Result.FAILURE, b);
    } finally {
        SecurityContextHolder.setContext(old);
    }
}
 
開發者ID:jenkinsci,項目名稱:run-selector-plugin,代碼行數:33,代碼來源:CopyArtifactTest.java

示例13: innerDeleteEventToJenkinsJob

import hudson.security.ACL; //導入方法依賴的package包/類
private void innerDeleteEventToJenkinsJob(final BuildConfig buildConfig) throws Exception {
	final Job job = getJobFromBuildConfig(buildConfig);
	if (job != null) {
		// employ intern of the BC UID to facilitate sync'ing on the same
		// actual object
		synchronized (buildConfig.getMetadata().getUid().intern()) {
			ACL.impersonate(ACL.SYSTEM, new NotReallyRoleSensitiveCallable<Void, Exception>() {
				@Override
				public Void call() throws Exception {
					try {
						job.delete();
					} finally {
						removeJobWithBuildConfig(buildConfig);
						Jenkins.getActiveInstance().rebuildDependencyGraphAsync();
					}
					return null;
				}
			});
               // if the bc has a source secret it is possible it should 
               // be deleted as well (called function will cross reference
               // with secret watch)
               CredentialsUtils.deleteSourceCredentials(buildConfig);
		}

	}

}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:28,代碼來源:BuildConfigWatcher.java

示例14: upsertCredential

import hudson.security.ACL; //導入方法依賴的package包/類
private static String upsertCredential(Secret secret, String namespace,
        String secretName) throws IOException {
    String id = null;
    if (secret != null) {
        Credentials creds = secretToCredentials(secret);
        if (creds == null)
            return null;
        id = secretName(namespace, secretName);
        Credentials existingCreds = lookupCredentials(id);
        final SecurityContext previousContext = ACL.impersonate(ACL.SYSTEM);
        try {
            CredentialsStore s = CredentialsProvider
                    .lookupStores(Jenkins.getActiveInstance()).iterator()
                    .next();
            if (existingCreds != null) {
                s.updateCredentials(Domain.global(), existingCreds, creds);
                logger.info("Updated credential " + id + " from Secret "
                        + NamespaceName.create(secret) + " with revision: "
                        + secret.getMetadata().getResourceVersion());
            } else {
                s.addCredentials(Domain.global(), creds);
                logger.info("Created credential " + id + " from Secret "
                        + NamespaceName.create(secret) + " with revision: "
                        + secret.getMetadata().getResourceVersion());
            }
            s.save();
        } finally {
            SecurityContextHolder.setContext(previousContext);
        }
    }
    return id;
}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:33,代碼來源:CredentialsUtils.java

示例15: deleteCredential

import hudson.security.ACL; //導入方法依賴的package包/類
private static void deleteCredential(String id, NamespaceName name,
        String resourceRevision) throws IOException {
    Credentials existingCred = lookupCredentials(id);
    if (existingCred != null) {
        final SecurityContext previousContext = ACL.impersonate(ACL.SYSTEM);
        try {
            Fingerprint fp = CredentialsProvider
                    .getFingerprintOf(existingCred);
            if (fp != null && fp.getJobs().size() > 0) {
                // per messages in credentials console, it is not a given,
                // but
                // it is possible for job refs to a credential to be
                // tracked;
                // if so, we will not prevent deletion, but at least note
                // things
                // for potential diagnostics
                StringBuffer sb = new StringBuffer();
                for (String job : fp.getJobs())
                    sb.append(job).append(" ");
                logger.info("About to delete credential " + id
                        + "which is referenced by jobs: " + sb.toString());
            }
            CredentialsStore s = CredentialsProvider
                    .lookupStores(Jenkins.getActiveInstance()).iterator()
                    .next();
            s.removeCredentials(Domain.global(), existingCred);
            logger.info("Deleted credential " + id + " from Secret " + name
                    + " with revision: " + resourceRevision);
            s.save();
        } finally {
            SecurityContextHolder.setContext(previousContext);
        }
    }
}
 
開發者ID:jenkinsci,項目名稱:openshift-sync-plugin,代碼行數:35,代碼來源:CredentialsUtils.java


注:本文中的hudson.security.ACL.impersonate方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。