当前位置: 首页>>代码示例>>Java>>正文


Java SecurityContextHolder.setContext方法代码示例

本文整理汇总了Java中org.acegisecurity.context.SecurityContextHolder.setContext方法的典型用法代码示例。如果您正苦于以下问题:Java SecurityContextHolder.setContext方法的具体用法?Java SecurityContextHolder.setContext怎么用?Java SecurityContextHolder.setContext使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.acegisecurity.context.SecurityContextHolder的用法示例。


在下文中一共展示了SecurityContextHolder.setContext方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getRun

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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: doFilter

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {


    if(1 + 1 == 2) {
        SecurityContext oldCtx = SecurityContextHolder.getContext();
        SecurityContextHolder.setContext(null); //
        try {
            super.doFilter(req, res, chain);
        } finally {
            SecurityContextHolder.setContext(oldCtx);
        }
    }
    else {
        super.doFilter(req, res, chain);
    }
}
 
开发者ID:blackarbiter,项目名称:Android_Code_Arbiter,代码行数:18,代码来源:AcegiSafeSessionFilter.java

示例3: getProject

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例4: testRebuildNotAuthorized

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例5: findBuild

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例6: retrieveDataElement

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public CommonDataElement retrieveDataElement(Long dataElementId, Float dataElementVersion)
throws ConnectionException {
    // Satish Patel informed me that the cadsrApi clears out the SecurityContext after they're done with it,
    // they are working on a fix but as a workaround I need to store the context and set it again after
    // I am done with all of the caDSR domain objects.  --TJ
    SecurityContext originalContext = SecurityContextHolder.getContext();
    try {
        List<Object> cadsrDataElements = searchDataElement(dataElementId, dataElementVersion);
        gov.nih.nci.cadsr.domain.DataElement latestCadsrDataElement = getLatestDataElement(cadsrDataElements);
        return convertCadsrDataElementToDataElements(latestCadsrDataElement);
    } catch (Exception e) {
        throw new ConnectionException("Couldn't connect to the caDSR server", e);
    } finally {
        // Restore context as described above.
        SecurityContextHolder.setContext(originalContext);
    }
}
 
开发者ID:NCIP,项目名称:caintegrator,代码行数:22,代码来源:CaDSRFacadeImpl.java

示例7: testPermissionWhenParameterized

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例8: upsertCredential

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例9: deleteCredential

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的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

示例10: triggerJobs

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
public GogsResults triggerJobs(String jobName, String deliveryID) {
  SecurityContext saveCtx = null;
  GogsResults result = new GogsResults();

  try {
    saveCtx = SecurityContextHolder.getContext();

    Jenkins instance = Jenkins.getActiveInstance();
    if (instance!=null) {
      ACL acl = instance.getACL();
      acl.impersonate(ACL.SYSTEM);

      BuildableItem project = GogsUtils.find(jobName, BuildableItem.class);
      if (project != null) {
        Cause cause = new GogsCause(deliveryID);
        project.scheduleBuild(0, cause);
        result.setMessage(String.format("Job '%s' is executed",jobName));
      } else {
        String msg = String.format("Job '%s' is not defined in Jenkins",jobName);
        result.setStatus(404, msg);
        LOGGER.warning(msg);
      }
    }
  } catch (Exception e) {
  } finally {
      SecurityContextHolder.setContext(saveCtx);
  }

  return result;
}
 
开发者ID:jenkinsci,项目名称:gogs-webhook-plugin,代码行数:31,代码来源:GogsPayloadProcessor.java

示例11: getJob

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
@CheckForNull
public Job<?, ?> getJob() {
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            return jenkins.getItemByFullName(jobName, Job.class);
        } catch (Exception e) {
            logger.log(Level.WARNING, "Unable to retrieve job " + jobName, e);
        } finally {
            SecurityContextHolder.setContext(old);
        }
    }
    return null;
}
 
开发者ID:jenkinsci,项目名称:dockerhub-notification-plugin,代码行数:16,代码来源:TriggerStore.java

示例12: run

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
@Override
protected int run() throws Exception {
    Jenkins.getInstance().checkPermission(SupportPlugin.CREATE_BUNDLE);
    List<Component> selected = new ArrayList<Component>();
    for (Component c : SupportPlugin.getComponents()) {
        if (c.isEnabled() && (components.isEmpty() || components.contains(c.getId()))) {
            selected.add(c);
        }
    }
    SupportPlugin.setRequesterAuthentication(Jenkins.getAuthentication());
    try {
        SecurityContext old = ACL.impersonate(ACL.SYSTEM);
        try {
            OutputStream os;
            if (channel != null) { // Remoting mode
                os = channel.call(new SaveBundle(SupportPlugin.getBundleFileName()));
            } else { // redirect output to a ZIP file yourself
                os = new CloseProofOutputStream(stdout);
            }
            SupportPlugin.writeBundle(os, selected);
        } finally {
            SecurityContextHolder.setContext(old);
        }
    } finally {
        SupportPlugin.clearRequesterAuthentication();
    }
    return 0;
}
 
开发者ID:jenkinsci,项目名称:support-core-plugin,代码行数:29,代码来源:SupportCommand.java

示例13: testIsRebuildableNoPermission

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
@Test
@Issue("JENKINS-28845")
public void testIsRebuildableNoPermission() throws Exception {
    FreeStyleProject a = jenkins.createFreeStyleProject("A");
    FreeStyleProject b = jenkins.createFreeStyleProject("B");
    b.getBuildersList().add(new FailureBuilder());
    a.getPublishersList().add(new BuildTrigger("B", false));
    jenkins.setQuietPeriod(0);
    jenkins.getInstance().rebuildDependencyGraph();
    FreeStyleBuild firstBuild = jenkins.buildAndAssertSuccess(a);
    jenkins.waitUntilNoActivity();
    assertNotNull(b.getLastBuild());
    assertTrue(b.getLastBuild().getResult().equals(Result.FAILURE));

    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());

    Task prototype  = Task.getPrototypeTask(b, false);
    Task task = prototype.getLatestTask(jenkins.getInstance(), firstBuild);
    assertNotNull(task);
    assertFalse(task.isRebuildable());

    SecurityContextHolder.setContext(oldContext);
}
 
开发者ID:Diabol,项目名称:delivery-pipeline-plugin,代码行数:29,代码来源:TaskTest.java

示例14: setBuildDescription

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
/**
 * Sets description of the build
 *
 * @param build
 *      Build to set the description of
 * @param description
 *      New build description
 */
public static void setBuildDescription(Run build, String description) throws IOException {
    SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
    try {
        build.setDescription(description);
    } finally {
        SecurityContextHolder.setContext(oldContext);
    }
}
 
开发者ID:openstack-infra,项目名称:gearman-plugin,代码行数:17,代码来源:GearmanPluginUtil.java

示例15: retrieveValueDomainForDataElement

import org.acegisecurity.context.SecurityContextHolder; //导入方法依赖的package包/类
/**
 * {@inheritDoc}
 */
@Override
public ValueDomain retrieveValueDomainForDataElement(Long dataElementId, Float dataElementVersion)
throws ConnectionException {
    ValueDomain valueDomain = new ValueDomain();
    // Satish Patel informed me that the cadsrApi clears out the SecurityContext after they're done with it,
    // they are working on a fix but as a workaround I need to store the context and set it again after
    // I am done with all of the caDSR domain objects.  --TJ
    SecurityContext originalContext = SecurityContextHolder.getContext();
    try {
        List<Object> cadsrDataElements = searchDataElement(dataElementId, dataElementVersion);

        if (!cadsrDataElements.isEmpty()) {
            gov.nih.nci.cadsr.domain.ValueDomain cadsrValueDomain =
                ((gov.nih.nci.cadsr.domain.DataElement) cadsrDataElements.get(0)).getValueDomain();
            // Default will be String, Character, Alphanumeric, and Alpha DVG
            AnnotationTypeEnum annotationType = AnnotationTypeEnum.STRING;
            String cadsrDataType = cadsrValueDomain.getDatatypeName();
            if (cadsrDataType.matches("DATE")) {
                annotationType = AnnotationTypeEnum.DATE;
            }
            if (cadsrDataType.matches("NUMBER")) {
                annotationType = AnnotationTypeEnum.NUMERIC;
            }
            valueDomain.setDataType(annotationType);
            valueDomain.setLongName(cadsrValueDomain.getLongName());
            valueDomain.setPublicID(cadsrValueDomain.getPublicID());
            if (cadsrValueDomain instanceof EnumeratedValueDomain) {
                retrievePermissibleValues(valueDomain, cadsrValueDomain);
            }
        }
        return valueDomain;
    } catch (Exception e) {
        throw new ConnectionException("Couldn't connect to the caDSR server", e);
    } finally {
        // Restore context as described above.
        SecurityContextHolder.setContext(originalContext);
    }
}
 
开发者ID:NCIP,项目名称:caintegrator,代码行数:42,代码来源:CaDSRFacadeImpl.java


注:本文中的org.acegisecurity.context.SecurityContextHolder.setContext方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。