Example usage for org.apache.shiro.subject Subject associateWith

List of usage examples for org.apache.shiro.subject Subject associateWith

Introduction

In this page you can find the example usage for org.apache.shiro.subject Subject associateWith.

Prototype

Runnable associateWith(Runnable runnable);

Source Link

Document

Returns a Runnable instance matching the given argument while additionally ensuring that it will retain and execute under this Subject's identity.

Usage

From source file:com.freedomotic.security.AuthImpl2.java

License:Open Source License

/**
 *
 * @param plugin//from  ww  w . ja v  a  2 s . c o m
 * @param action
 */
@Override
public Runnable pluginBindRunnablePrivileges(Plugin plugin, Runnable action) {

    if (isInited()) {
        //LOG.info("Executing privileged for plugin: " + classname);
        PrincipalCollection plugPrincipals = new SimplePrincipalCollection(plugin.getClassName(),
                pluginRealm.getName());
        Subject plugSubject = new Subject.Builder().principals(plugPrincipals).authenticated(true)
                .buildSubject();
        try {
            plugSubject.getSession().setTimeout(-1);
        } catch (Exception e) {
            LOG.warn("ERROR retrieving session for user {}", plugin.getClassName());
        }
        return plugSubject.associateWith(action);
    }
    return action;
}

From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java

License:Apache License

public static Callable associateWith(Callable callable) {
    Subject currentUser = getSubject();
    if (currentUser == null) {
        return callable;
    }/*  w w w. ja va 2  s. co m*/

    return currentUser.associateWith(callable);
}

From source file:com.sonicle.webtop.core.sdk.BaseServiceAsyncAction.java

License:Open Source License

public synchronized void start(Subject runSubject, UserProfileId runProfileId) {
    if ((thread != null) && thread.isAlive())
        return;/*  ww  w.ja v  a2 s .com*/
    shouldStop = false;
    completed = false;
    this.runProfileId = runProfileId;
    if (StringUtils.isBlank(threadName)) {
        thread = new Thread(runSubject.associateWith(this));
    } else {
        thread = new Thread(runSubject.associateWith(this), threadName);
    }
    thread.start();
}

From source file:org.apache.geode.internal.security.IntegratedSecurityService.java

License:Apache License

public Callable associateWith(Callable callable) {
    Subject currentUser = getSubject();
    if (currentUser == null) {
        return callable;
    }//w  ww . ja  v a 2s. c  o  m

    return currentUser.associateWith(callable);
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.endpoint.CswEndpoint.java

License:Open Source License

@Override
@POST//w  ww  .j ava2  s  . c om
@Consumes({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
@Produces({ MediaType.TEXT_XML, MediaType.APPLICATION_XML })
public TransactionResponseType transaction(CswTransactionRequest request) throws CswException {
    if (request == null) {
        throw new CswException("TransactionRequest request is null");
    }

    TransactionResponseType response = new TransactionResponseType();
    TransactionSummaryType summary = new TransactionSummaryType();
    summary.setTotalInserted(BigInteger.valueOf(0));
    summary.setTotalUpdated(BigInteger.valueOf(0));
    summary.setTotalDeleted(BigInteger.valueOf(0));
    response.setTransactionSummary(summary);
    response.setVersion(CswConstants.VERSION_2_0_2);

    int numInserted = 0;
    final Subject subject = SecurityUtils.getSubject();
    for (InsertAction insertAction : request.getInsertActions()) {
        final InsertAction transformInsertAction = transformInsertAction(insertAction);

        List<Metacard> metacards = transformInsertAction.getRecords();
        CompletionService<CreateResponse> completionService = new ExecutorCompletionService<>(queryExecutor);

        for (Metacard record : metacards) {
            CreateRequest createRequest = new CreateRequestImpl(record);
            Callable<CreateResponse> callable = () -> {
                try {
                    return framework.create(createRequest);
                } catch (IngestException | SourceUnavailableException e) {
                    LOGGER.debug("Unable to insert record(s)", e);
                    throw new CswException("Unable to insert record(s).", CswConstants.TRANSACTION_FAILED,
                            transformInsertAction.getHandle());
                }
            };
            Callable<CreateResponse> createCallable = subject.associateWith(callable);
            completionService.submit(createCallable);
        }

        for (int i = 0; i < metacards.size(); i++) {
            try {
                Future<CreateResponse> completedFuture = completionService.take();

                try {
                    CreateResponse futureResponse = completedFuture.get();
                    numInserted += futureResponse.getCreatedMetacards().size();
                    if (request.isVerbose()) {
                        response.getInsertResult().add(getInsertResultFromResponse(futureResponse));
                    }
                } catch (ExecutionException | CancellationException e) {
                    LOGGER.debug("Error ingesting Metacard", e);
                    throw new CswException("Unable to insert record(s).", CswConstants.TRANSACTION_FAILED,
                            insertAction.getHandle());
                }
            } catch (InterruptedException e) {
                LOGGER.debug("Metacard ingest interrupted", e);
                Thread.currentThread().interrupt();
                break;
            }
        }
    }
    LOGGER.debug("{} records inserted.", numInserted);
    response.getTransactionSummary().setTotalInserted(BigInteger.valueOf(numInserted));

    int numUpdated = 0;
    List<UpdateAction> updateActions = request.getUpdateActions();
    CompletionService<Integer> updateCompletionService = new ExecutorCompletionService<>(queryExecutor);

    for (final UpdateAction updateAction : updateActions) {
        Callable<Integer> callable = () -> {
            try {
                return updateRecords(subject, updateAction);
            } catch (CswException | FederationException | IngestException | SourceUnavailableException
                    | UnsupportedQueryException | CatalogQueryException e) {
                LOGGER.debug("Unable to update record(s)", e);
                throw new CswException("Unable to update record(s).", CswConstants.TRANSACTION_FAILED,
                        updateAction.getHandle());
            }
        };
        Callable<Integer> updateCallable = subject.associateWith(callable);
        updateCompletionService.submit(updateCallable);
    }
    for (int i = 0; i < updateActions.size(); i++) {
        try {
            Future<Integer> completedFuture = updateCompletionService.take();
            try {
                numUpdated += completedFuture.get();
            } catch (ExecutionException | CancellationException e) {
                LOGGER.debug("Error updating Metacard", e);
                throw new CswException("Unable to update record(s).", CswConstants.TRANSACTION_FAILED,
                        "Update");
            }
        } catch (InterruptedException e) {
            LOGGER.debug("Metacard update interrupted", e);
            Thread.currentThread().interrupt();
            break;
        }
    }

    LOGGER.debug("{} records updated.", numUpdated);
    response.getTransactionSummary().setTotalUpdated(BigInteger.valueOf(numUpdated));

    int numDeleted = 0;
    for (DeleteAction deleteAction : request.getDeleteActions()) {
        try {
            numDeleted += deleteRecords(deleteAction);
        } catch (Exception e) {
            LOGGER.debug("Unable to delete record(s)", e);
            throw new CswException("Unable to delete record(s).", CswConstants.TRANSACTION_FAILED,
                    deleteAction.getHandle());
        }
    }
    LOGGER.debug("{} records deleted.", numDeleted);
    response.getTransactionSummary().setTotalDeleted(BigInteger.valueOf(numDeleted));

    return response;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.endpoint.CswEndpoint.java

License:Open Source License

private int deleteRecords(DeleteAction deleteAction) throws CswException, UnsupportedQueryException {

    final DeleteAction transformDeleteAction = transformDeleteAction(deleteAction);

    QueryRequest queryRequest = queryFactory.getQuery(transformDeleteAction.getConstraint(),
            transformDeleteAction.getTypeName());

    queryRequest = queryFactory.updateQueryRequestTags(queryRequest,
            schemaTransformerManager.getTransformerSchemaForId(transformDeleteAction.getTypeName()));

    int batchCount = 1;
    int deletedCount = 0;

    String[] idsToDelete = getNextQueryBatch(queryRequest);

    CompletionService<DeleteResponse> deleteCompletionService = new ExecutorCompletionService<>(queryExecutor);

    while (idsToDelete.length > 0) {
        LOGGER.debug("Attempting to delete {} metacards from batch {}.", idsToDelete.length, ++batchCount);
        final Subject subject = SecurityUtils.getSubject();
        for (final String id : idsToDelete) {
            Callable<DeleteResponse> callable = () -> {
                try {
                    DeleteRequestImpl deleteRequest = new DeleteRequestImpl(id);
                    return framework.delete(deleteRequest);
                } catch (IngestException | SourceUnavailableException | CatalogQueryException e) {
                    LOGGER.debug("Unable to delete record: {}", id, e);
                    throw new CswException("Unable to delete record(s).", CswConstants.TRANSACTION_FAILED,
                            transformDeleteAction.getHandle());
                }/*from  ww  w  .  j a  va 2  s  .c o m*/
            };
            Callable<DeleteResponse> deleteCallable = subject.associateWith(callable);
            deleteCompletionService.submit(deleteCallable);
        }

        for (int i = 0; i < idsToDelete.length; i++) {
            try {
                Future<DeleteResponse> completedFuture = deleteCompletionService.take();

                try {
                    deletedCount += completedFuture.get().getDeletedMetacards().size();
                } catch (ExecutionException | CancellationException e) {
                    LOGGER.debug("Error deleting Metacard", e);
                    throw new CswException("Unable to delete record(s).", CswConstants.TRANSACTION_FAILED,
                            deleteAction.getHandle());
                }
            } catch (InterruptedException e) {
                LOGGER.debug("Metacard delete interrupted", e);
                Thread.currentThread().interrupt();
                break;
            }
        }

        idsToDelete = getNextQueryBatch(queryRequest);
    }

    return deletedCount;
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.endpoint.CswEndpoint.java

License:Open Source License

private int updateRecords(Subject subject, UpdateAction updateAction) throws CswException, FederationException,
        IngestException, SourceUnavailableException, UnsupportedQueryException {

    updateAction = transformUpdateAction(updateAction);

    if (updateAction.getMetacard() != null) {
        Metacard newRecord = updateAction.getMetacard();

        if (newRecord.getId() != null) {
            UpdateRequest updateRequest = new UpdateRequestImpl(newRecord.getId(), newRecord);
            LOGGER.debug("Attempting to update {} ", newRecord.getId());
            UpdateResponse updateResponse = framework.update(updateRequest);
            return updateResponse.getUpdatedMetacards().size();
        } else {/*from  w  ww  .  j a va 2s  .co  m*/
            throw new CswException("Unable to update record.  No ID was specified in the request.",
                    CswConstants.MISSING_PARAMETER_VALUE, updateAction.getHandle());
        }
    } else if (updateAction.getConstraint() != null) {
        QueryConstraintType constraint = updateAction.getConstraint();
        QueryRequest queryRequest = queryFactory.getQuery(constraint, updateAction.getTypeName());

        queryRequest = queryFactory.updateQueryRequestTags(queryRequest,
                schemaTransformerManager.getTransformerSchemaForId(updateAction.getTypeName()));

        Map<String, Serializable> recordProperties = updateAction.getRecordProperties();
        Iterable<List<Result>> resultList = Iterables
                .partition(ResultIterable.resultIterable(framework, queryRequest), DEFAULT_BATCH);
        int batchCount = 1;
        int updatedCount = 0;

        CompletionService<Integer> completionService = new ExecutorCompletionService<>(queryExecutor);
        final UpdateAction callableUpdateAction = updateAction;
        for (List<Result> results : resultList) {
            final int batch = batchCount;
            Callable<Integer> callable = () -> {
                try {
                    return updateResultList(recordProperties, batch, results);
                } catch (IngestException | SourceUnavailableException e) {
                    LOGGER.debug("Unable to update record(s)", e);
                    throw new CswException("Unable to update record(s).", CswConstants.TRANSACTION_FAILED,
                            callableUpdateAction.getHandle());
                }
            };
            batchCount++;
            Callable<Integer> updateCallable = subject.associateWith(callable);
            completionService.submit(updateCallable);
        }

        for (int i = 0; i < batchCount - 1; i++) {
            try {
                Future<Integer> completedFuture = completionService.take();
                try {
                    updatedCount += completedFuture.get();
                } catch (ExecutionException | CancellationException e) {
                    LOGGER.debug("Error updating", e);
                    throw new CswException("Unable to update record(s).", CswConstants.TRANSACTION_FAILED,
                            updateAction.getHandle());
                }
            } catch (InterruptedException e) {
                LOGGER.debug("Metacard update interrupted", e);
                Thread.currentThread().interrupt();
                break;
            }
        }

        return updatedCount;
    }
    return 0;
}

From source file:org.obiba.mica.core.MicaAsyncTaskExecutor.java

License:Open Source License

@Override
public void execute(Runnable task) {
    Subject subject = SecurityUtils.getSubject();
    Runnable work = subject.associateWith(task);
    executor.execute(work);/*from   w w w .  j a v a2 s  .  c o  m*/
}

From source file:org.obiba.mica.core.MicaAsyncTaskExecutor.java

License:Open Source License

@Override
public void execute(Runnable task, long startTimeout) {
    Subject subject = SecurityUtils.getSubject();
    Runnable work = subject.associateWith(task);
    executor.execute(createWrappedRunnable(work), startTimeout);
}

From source file:org.obiba.opal.r.service.OpalRSession.java

License:Open Source License

private void startRCommandsConsumer() {
    Subject owner = SessionDetachedSubject.asSessionDetachedSubject(SecurityUtils.getSubject());
    consumer = transactionalThreadFactory.newThread(owner.associateWith(rCommandsConsumer));
    consumer.setName("R Operations Consumer " + rCommandsConsumer);
    consumer.start();//from  ww w.j  av  a2s. c  o m
}