Example usage for org.springframework.security.core.context SecurityContextHolder setContext

List of usage examples for org.springframework.security.core.context SecurityContextHolder setContext

Introduction

In this page you can find the example usage for org.springframework.security.core.context SecurityContextHolder setContext.

Prototype

public static void setContext(SecurityContext context) 

Source Link

Document

Associates a new SecurityContext with the current thread of execution.

Usage

From source file:org.unitedinternet.cosmo.acegisecurity.providers.ticket.TicketAuthenticationClearingFilter.java

/**
 * Detects if a ticket is associated with
 * the current context and clears the context.
 * @param request The servlet request./*from w w  w.  ja  v  a  2s  .  c o m*/
 * @param response The servlet response.
 * @param chain The filter chain.
 * @throws IOException - if something is wrong this exception is thrown.
 * @throws ServletException - if something is wrong this exception is thrown.
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    SecurityContext sc = SecurityContextHolder.getContext();
    if (sc.getAuthentication() != null && sc.getAuthentication() instanceof TicketAuthenticationToken) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("found ticket authentication clearing...");
        }
        SecurityContextHolder.setContext(new SecurityContextImpl());
    }

    chain.doFilter(request, response);
}

From source file:ubc.pavlab.aspiredb.server.service.ProjectServiceImpl.java

@Override
@RemoteMethod/*from   w  w  w.j  a va 2 s.  com*/
public String addSubjectVariantsPhenotypeToProject(final String variantFilename, final String phenotypeFilename,
        final boolean createProject, final String projectName, final String variantType, final boolean dryRun) {

    // Run the upload task on a separate thread so we don't block the current thread and return a proxy error on the
    // front end
    class ProjectUploadThread extends Thread {

        SecurityContext context;

        public ProjectUploadThread(SecurityContext context) {
            this.context = context;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            StopWatch timer = new StopWatch();
            timer.start();

            StringBuffer returnMsg = new StringBuffer();
            StringBuffer errMsg = new StringBuffer();

            VariantUploadServiceResult variantResult = null;
            Collection<Variant2VariantOverlap> overlap = null;
            PhenotypeUploadServiceResult phenResult = null;

            final String STR_FMT = "%35s: %5s\n";

            returnMsg.append(String.format(STR_FMT, "Project", projectName) + "\n");

            if (variantFilename.length() > 0) {

                try {
                    variantResult = addSubjectVariantsToProject(variantFilename, createProject, projectName,
                            variantType, dryRun);
                    returnMsg.append(
                            String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    returnMsg.append(String.format(STR_FMT, "Number of Variants",
                            variantResult.getVariantsToAdd().size()));
                    for (String err : variantResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }

                    if (!dryRun) {
                        // only run SpecialProject overlap if projectName is not a special project
                        try {
                            SpecialProject.valueOf(projectName);
                        } catch (IllegalArgumentException argEx) {
                            for (Project specialProject : projectDao.getSpecialOverlapProjects()) {
                                try {
                                    overlap = projectManager.populateProjectToProjectOverlap(projectName,
                                            specialProject.getName(), variantResult.getVariantsToAdd());
                                    returnMsg.append(String.format(STR_FMT,
                                            "Number of Overlaps with " + specialProject.getName(),
                                            overlap.size()));
                                } catch (Exception e) {
                                    log.error(e.getLocalizedMessage(), e);
                                    errMsg.append(e.getLocalizedMessage() + "\n");
                                }
                            }
                        }
                    }

                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            if (phenotypeFilename.length() > 0) {
                try {
                    phenResult = addSubjectPhenotypeToProject(phenotypeFilename, createProject, projectName,
                            dryRun);
                    if (returnMsg.indexOf("Number of Subjects") == -1) {
                        returnMsg.append(
                                String.format(STR_FMT, "Number of Subjects", getSubjects(projectName).size()));
                    }
                    returnMsg.append(String.format(STR_FMT, "Number of Phenotypes",
                            phenResult.getPhenotypesToAdd().size()));
                    for (String err : phenResult.getErrorMessages()) {
                        errMsg.append(err + "\n");
                    }
                } catch (Exception e) {
                    log.error(e.getLocalizedMessage(), e);
                    errMsg.append(e.getLocalizedMessage() + "\n");
                }
            }

            log.info("Uploading took " + timer.getTime() + " ms");

            // trim errorMssage
            final int ERRMSG_LIMIT = 500;
            if (errMsg.length() > ERRMSG_LIMIT) {
                errMsg.delete(ERRMSG_LIMIT, errMsg.length() - 1);
                errMsg.append("\n...\n");
            }

            String returnStr = returnMsg.toString();
            returnStr += errMsg.length() > 0 ? "\nExceptions\n" + errMsg : "";

            log.info(returnStr);

            if (!dryRun) {
                // email users that the upload has finished

                // if ( timer.getTime() > ConfigUtils.getLong( "aspiredb.uploadTimeThreshold", 60000 ) ) {
                emailUploadFinished(projectName, returnStr);
                // }
            }

        }
    }

    ProjectUploadThread thread = new ProjectUploadThread(SecurityContextHolder.getContext());
    thread.setName(ProjectUploadThread.class.getName() + "_" + projectName + "_load_thread_"
            + RandomStringUtils.randomAlphanumeric(5));
    // To prevent VM from waiting on this thread to shutdown (if shutting down).
    thread.setDaemon(true);
    thread.start();

    return thread.getName();
}

From source file:ubic.gemma.apps.ArrayDesignBlatCli.java

@Override
protected Exception doWork(String[] args) {
    Exception err = processCommandLine(
            "Array design sequence BLAT - only works if server is already started or if a PSL file is provided!",
            args);//from   w  w  w . j a  v a 2 s . c o  m
    if (err != null)
        return err;

    final Date skipIfLastRunLaterThan = getLimitingDate();

    if (!this.arrayDesignsToProcess.isEmpty()) {

        if (this.blatResultFile != null && this.arrayDesignsToProcess.size() > 1) {
            throw new IllegalArgumentException(
                    "Cannot provide a blat result file when multiple arrays are being analyzed");
        }

        for (ArrayDesign arrayDesign : this.arrayDesignsToProcess) {
            if (!needToRun(skipIfLastRunLaterThan, arrayDesign, ArrayDesignSequenceAnalysisEvent.class)) {
                log.warn(arrayDesign + " was last run more recently than " + skipIfLastRunLaterThan);
                return null;
            }

            arrayDesign = unlazifyArrayDesign(arrayDesign);
            Collection<BlatResult> persistedResults;
            try {
                if (this.blatResultFile != null) {
                    Collection<BlatResult> blatResults = getBlatResultsFromFile(arrayDesign);

                    if (blatResults == null || blatResults.size() == 0) {
                        throw new IllegalStateException("No blat results in file!");
                    }

                    log.info("Got " + blatResults.size() + " blat records");
                    persistedResults = arrayDesignSequenceAlignmentService.processArrayDesign(arrayDesign,
                            taxon, blatResults);
                    audit(arrayDesign, "BLAT results read from file: " + blatResultFile);
                } else {
                    // Run blat from scratch.
                    persistedResults = arrayDesignSequenceAlignmentService.processArrayDesign(arrayDesign,
                            this.sensitive);
                    audit(arrayDesign, "Based on a fresh alignment analysis; BLAT score threshold was "
                            + this.blatScoreThreshold + "; sensitive mode was " + this.sensitive);
                }
                log.info("Persisted " + persistedResults.size() + " results");
            } catch (FileNotFoundException e) {
                this.errorObjects.add(e);
            } catch (IOException e) {
                this.errorObjects.add(e);
            }
        }

    } else if (taxon != null) {

        Collection<ArrayDesign> allArrayDesigns = arrayDesignService.findByTaxon(taxon);
        log.warn("*** Running BLAT for all " + taxon.getCommonName() + " Array designs *** ["
                + allArrayDesigns.size() + " items]");

        final SecurityContext context = SecurityContextHolder.getContext();

        // split over multiple threads so we can multiplex. Put the array designs in a queue.

        /*
         * Here is our task runner.
         */
        class Consumer implements Runnable {
            private final BlockingQueue<ArrayDesign> queue;

            public Consumer(BlockingQueue<ArrayDesign> q) {
                queue = q;
            }

            @Override
            public void run() {
                SecurityContextHolder.setContext(context);
                while (true) {
                    ArrayDesign ad = queue.poll();
                    if (ad == null) {
                        break;
                    }
                    consume(ad);
                }
            }

            void consume(ArrayDesign x) {

                x = arrayDesignService.thaw(x);

                processArrayDesign(skipIfLastRunLaterThan, x);

            }
        }

        BlockingQueue<ArrayDesign> arrayDesigns = new ArrayBlockingQueue<ArrayDesign>(allArrayDesigns.size());
        for (ArrayDesign ad : allArrayDesigns) {
            arrayDesigns.add(ad);
        }

        /*
         * Start the threads
         */
        Collection<Thread> threads = new ArrayList<Thread>();
        for (int i = 0; i < this.numThreads; i++) {
            Consumer c1 = new Consumer(arrayDesigns);
            Thread k = new Thread(c1);
            threads.add(k);
            k.start();
        }

        waitForThreadPoolCompletion(threads);

        /*
         * All done
         */
        summarizeProcessing();

    } else {
        bail(ErrorCode.MISSING_ARGUMENT);
    }

    return null;
}

From source file:ubic.gemma.apps.ExpressionExperimentDataFileGeneratorCli.java

@Override
protected Exception doWork(String[] args) {

    Exception exp = processCommandLine(DESCRIPTION, args);
    if (exp != null) {
        return exp;
    }//  w  ww  . ja  v  a2s  .c  om

    BlockingQueue<BioAssaySet> queue = new ArrayBlockingQueue<BioAssaySet>(expressionExperiments.size());

    // Add the Experiments to the queue for processing
    for (BioAssaySet ee : expressionExperiments) {
        if (ee instanceof ExpressionExperiment) {
            try {
                queue.put(ee);
            } catch (InterruptedException ie) {
                log.info(ie);
            }
        } else {
            throw new UnsupportedOperationException("Can't handle non-EE BioAssaySets yet");
        }

    }

    // Inner class for processing the experiments
    class Worker extends Thread {
        BlockingQueue<BioAssaySet> q;
        SecurityContext context;

        Worker(BlockingQueue<BioAssaySet> q, SecurityContext context) {
            this.context = context;
            this.q = q;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            while (true) {
                BioAssaySet ee = q.poll();
                if (ee == null) {
                    break;
                }
                log.info("Processing Experiment: " + ee.getName());
                processExperiment((ExpressionExperiment) ee);

            }

        }
    }

    final SecurityContext context = SecurityContextHolder.getContext();

    Collection<Thread> threads = new ArrayList<Thread>();

    for (int i = 1; i <= this.numThreads; i++) {
        Worker worker = new Worker(queue, context);
        threads.add(worker);
        log.info("Starting thread " + i);
        worker.start();
    }

    waitForThreadPoolCompletion(threads);

    summarizeProcessing();

    return null;

}

From source file:ubic.gemma.core.apps.ExpressionExperimentDataFileGeneratorCli.java

@Override
protected Exception doWork(String[] args) {

    Exception exp = this.processCommandLine(args);
    if (exp != null) {
        return exp;
    }/*from  ww  w . j a  va 2s . co  m*/

    BlockingQueue<BioAssaySet> queue = new ArrayBlockingQueue<>(expressionExperiments.size());

    // Add the Experiments to the queue for processing
    for (BioAssaySet ee : expressionExperiments) {
        if (ee instanceof ExpressionExperiment) {
            try {
                queue.put(ee);
            } catch (InterruptedException ie) {
                AbstractCLI.log.info(ie);
            }
        } else {
            throw new UnsupportedOperationException("Can't handle non-EE BioAssaySets yet");
        }

    }

    // Inner class for processing the experiments
    class Worker extends Thread {
        private SecurityContext context;
        private BlockingQueue<BioAssaySet> q;

        private Worker(BlockingQueue<BioAssaySet> q, SecurityContext context) {
            this.context = context;
            this.q = q;
        }

        @Override
        public void run() {

            SecurityContextHolder.setContext(this.context);

            while (true) {
                BioAssaySet ee = q.poll();
                if (ee == null) {
                    break;
                }
                AbstractCLI.log.info("Processing Experiment: " + ee.getName());
                ExpressionExperimentDataFileGeneratorCli.this.processExperiment((ExpressionExperiment) ee);

            }

        }
    }

    final SecurityContext context = SecurityContextHolder.getContext();

    Collection<Thread> threads = new ArrayList<>();

    for (int i = 1; i <= this.numThreads; i++) {
        Worker worker = new Worker(queue, context);
        threads.add(worker);
        AbstractCLI.log.info("Starting thread " + i);
        worker.start();
    }

    this.waitForThreadPoolCompletion(threads);

    this.summarizeProcessing();

    return null;

}

From source file:ubic.gemma.core.loader.association.NCBIGene2GOAssociationLoader.java

public void load(final InputStream inputStream) {
    final BlockingQueue<Gene2GOAssociation> queue = new ArrayBlockingQueue<>(
            NCBIGene2GOAssociationLoader.QUEUE_SIZE);
    final SecurityContext context = SecurityContextHolder.getContext();
    final Authentication authentication = context.getAuthentication();

    Thread loadThread = new Thread(new Runnable() {
        @Override/*from w  ww  .jav a  2  s  .  c om*/
        public void run() {
            NCBIGene2GOAssociationLoader.log.info("Starting loading");
            SecurityContextHolder.setContext(context);
            NCBIGene2GOAssociationLoader.this.load(queue);
        }
    });

    loadThread.start();

    Thread parseThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // NCBIGene2GOAssociationParser parser = new NCBIGene2GOAssociationParser();
                SecurityContextHolder.getContext().setAuthentication(authentication);
                parser.parse(inputStream, queue);
                NCBIGene2GOAssociationLoader.this.setCount(parser.getCount());
            } catch (IOException e) {
                NCBIGene2GOAssociationLoader.log.error(e, e);
                throw new RuntimeException(e);
            }
            NCBIGene2GOAssociationLoader.log.info("Done parsing");
            producerDone.set(true);
        }
    });

    parseThread.start();

    while (!this.isProducerDone() || !this.isConsumerDone()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:ubic.gemma.core.loader.expression.arrayDesign.ArrayDesignProbeMapperServiceImpl.java

/**
 * @param persist true to get results saved to database; otherwise output is to standard out.
 *//*  w  ww  . jav a 2 s.  c  o  m*/
private void load(final BlockingQueue<BACS> queue, final AtomicBoolean generatorDone,
        final AtomicBoolean loaderDone, final boolean persist) {
    final SecurityContext context = SecurityContextHolder.getContext();
    assert context != null;

    Thread loadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            SecurityContextHolder.setContext(context);
            ArrayDesignProbeMapperServiceImpl.this.doLoad(queue, generatorDone, loaderDone, persist);
        }

    }, "PersistBlatAssociations");

    loadThread.start();

}

From source file:ubic.gemma.core.loader.genome.gene.ncbi.NcbiGeneLoader.java

/**
 * @param geneQueue a blocking queue of genes to be loaded into the database loads genes into the database
 *//*  ww  w  . j  av  a  2  s  .  com*/
private void load(final BlockingQueue<Gene> geneQueue) {
    final SecurityContext context = SecurityContextHolder.getContext();
    assert context != null;

    Thread loadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            SecurityContextHolder.setContext(context);
            NcbiGeneLoader.this.doLoad(geneQueue);
        }

    }, "Loading");
    loadThread.start();

    while (!generatorDone.get() || !converterDone.get() || !loaderDone.get()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:ubic.gemma.core.loader.protein.StringProteinInteractionLoader.java

/**
 * Thread to handle loading Gene2GeneProteinAssociation into db.
 *
 * @param gene2GeneProteinAssociationQueue a blocking queue of genes to be loaded into the database loads genes into the database
 *///from www  .ja  v a 2s.co m
private void load(final BlockingQueue<Gene2GeneProteinAssociation> gene2GeneProteinAssociationQueue) {
    final SecurityContext context = SecurityContextHolder.getContext();
    assert context != null;

    Thread loadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            SecurityContextHolder.setContext(context);
            StringProteinInteractionLoader.this.doLoad(gene2GeneProteinAssociationQueue);
        }

    }, "Loading");
    loadThread.start();

    while (!converterDone.get() || !loaderDone.get()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:ubic.gemma.loader.association.NCBIGene2GOAssociationLoader.java

/**
 * @param inputStream// ww  w . ja v a2s.c  om
 */
public void load(final InputStream inputStream) {
    final BlockingQueue<Gene2GOAssociation> queue = new ArrayBlockingQueue<Gene2GOAssociation>(QUEUE_SIZE);
    final SecurityContext context = SecurityContextHolder.getContext();
    final Authentication authentication = context.getAuthentication();

    Thread loadThread = new Thread(new Runnable() {
        @Override
        public void run() {
            log.info("Starting loading");
            SecurityContextHolder.setContext(context);
            load(queue);
        }
    });

    loadThread.start();

    Thread parseThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                // NCBIGene2GOAssociationParser parser = new NCBIGene2GOAssociationParser();
                SecurityContextHolder.getContext().setAuthentication(authentication);
                parser.parse(inputStream, queue);
                setCount(parser.getCount());
            } catch (IOException e) {
                log.error(e, e);
                throw new RuntimeException(e);
            }
            log.info("Done parsing");
            producerDone.set(true);
        }
    });

    parseThread.start();

    while (!isProducerDone() || !isConsumerDone()) {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}