org.springframework.core.task.TaskExecutor

Here are the examples of the java api org.springframework.core.task.TaskExecutor taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

159 Examples 7

19 View Source File : DefaultFlywayDataSourceContext.java
License : Apache License 2.0
Project Creator : zonkyio

/**
 * Specify an asynchronous executor for background bootstrapping,
 * e.g. a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}.
 * <p>
 * {@code DataSource} initialization will then switch into background
 * bootstrap mode, with a {@code DataSource} proxy immediately returned for
 * injection purposes instead of waiting for the Flyway's bootstrapping to complete.
 * However, note that the first actual call to a {@code DataSource} method will
 * then block until the Flyway's bootstrapping completed, if not ready by then.
 * For maximum benefit, make sure to avoid early {@code DataSource} calls
 * in init methods of related beans.
 * <p>
 * Inspired by {@code org.springframework.orm.jpa.AbstractEnreplacedyManagerFactoryBean#setBootstrapExecutor}.
 */
public void setBootstrapExecutor(TaskExecutor bootstrapExecutor) {
    this.bootstrapExecutor = bootstrapExecutor;
}

19 View Source File : RestTemplateXhrTransport.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Configure the {@code TaskExecutor} to use to execute XHR receive requests.
 * <p>By default {@link org.springframework.core.task.SimpleAsyncTaskExecutor
 * SimpleAsyncTaskExecutor} is configured which creates a new thread every
 * time the transports connects.
 */
public void setTaskExecutor(TaskExecutor taskExecutor) {
    replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
    this.taskExecutor = taskExecutor;
}

19 View Source File : AnnotatedEndpointConnectionManager.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Set a {@link TaskExecutor} to use to open the connection.
 * By default {@link SimpleAsyncTaskExecutor} is used.
 */
public void setTaskExecutor(TaskExecutor taskExecutor) {
    replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
    this.taskExecutor = taskExecutor;
}

19 View Source File : ReactiveTypeHandler.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Private helper clreplaced to replacedist with handling "reactive" return values types
 * that can be adapted to a Reactive Streams {@link Publisher} through the
 * {@link ReactiveAdapterRegistry}.
 *
 * <p>Such return values may be bridged to a {@link ResponseBodyEmitter} for
 * streaming purposes at the presence of a streaming media type or based on the
 * generic type.
 *
 * <p>For all other cases {@code Publisher} output is collected and bridged to
 * {@link DeferredResult} for standard async request processing.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 */
clreplaced ReactiveTypeHandler {

    private static final long STREAMING_TIMEOUT_VALUE = -1;

    private static Log logger = LogFactory.getLog(ReactiveTypeHandler.clreplaced);

    private final ReactiveAdapterRegistry adapterRegistry;

    private final TaskExecutor taskExecutor;

    private final ContentNegotiationManager contentNegotiationManager;

    private boolean taskExecutorWarning;

    public ReactiveTypeHandler() {
        this(ReactiveAdapterRegistry.getSharedInstance(), new SyncTaskExecutor(), new ContentNegotiationManager());
    }

    ReactiveTypeHandler(ReactiveAdapterRegistry registry, TaskExecutor executor, ContentNegotiationManager manager) {
        replacedert.notNull(registry, "ReactiveAdapterRegistry is required");
        replacedert.notNull(executor, "TaskExecutor is required");
        replacedert.notNull(manager, "ContentNegotiationManager is required");
        this.adapterRegistry = registry;
        this.taskExecutor = executor;
        this.contentNegotiationManager = manager;
        this.taskExecutorWarning = (executor instanceof SimpleAsyncTaskExecutor || executor instanceof SyncTaskExecutor);
    }

    /**
     * Whether the type can be adapted to a Reactive Streams {@link Publisher}.
     */
    public boolean isReactiveType(Clreplaced<?> type) {
        return (this.adapterRegistry.getAdapter(type) != null);
    }

    /**
     * Process the given reactive return value and decide whether to adapt it
     * to a {@link ResponseBodyEmitter} or a {@link DeferredResult}.
     * @return an emitter for streaming, or {@code null} if handled internally
     * with a {@link DeferredResult}
     */
    @Nullable
    public ResponseBodyEmitter handleValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mav, NativeWebRequest request) throws Exception {
        replacedert.notNull(returnValue, "Expected return value");
        ReactiveAdapter adapter = this.adapterRegistry.getAdapter(returnValue.getClreplaced());
        replacedert.state(adapter != null, () -> "Unexpected return value: " + returnValue);
        ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
        Clreplaced<?> elementClreplaced = elementType.toClreplaced();
        Collection<MediaType> mediaTypes = getMediaTypes(request);
        Optional<MediaType> mediaType = mediaTypes.stream().filter(MimeType::isConcrete).findFirst();
        if (adapter.isMultiValue()) {
            if (mediaTypes.stream().anyMatch(MediaType.TEXT_EVENT_STREAM::includes) || ServerSentEvent.clreplaced.isreplacedignableFrom(elementClreplaced)) {
                logExecutorWarning(returnType);
                SseEmitter emitter = new SseEmitter(STREAMING_TIMEOUT_VALUE);
                new SseEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
            if (CharSequence.clreplaced.isreplacedignableFrom(elementClreplaced)) {
                logExecutorWarning(returnType);
                ResponseBodyEmitter emitter = getEmitter(mediaType.orElse(MediaType.TEXT_PLAIN));
                new TextEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
            if (mediaTypes.stream().anyMatch(MediaType.APPLICATION_STREAM_JSON::includes)) {
                logExecutorWarning(returnType);
                ResponseBodyEmitter emitter = getEmitter(MediaType.APPLICATION_STREAM_JSON);
                new JsonEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
        }
        // Not streaming...
        DeferredResult<Object> result = new DeferredResult<>();
        new DeferredResultSubscriber(result, adapter, elementType).connect(adapter, returnValue);
        WebAsyncUtils.getAsyncManager(request).startDeferredResultProcessing(result, mav);
        return null;
    }

    @SuppressWarnings("unchecked")
    private Collection<MediaType> getMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
        Collection<MediaType> mediaTypes = (Collection<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        return CollectionUtils.isEmpty(mediaTypes) ? this.contentNegotiationManager.resolveMediaTypes(request) : mediaTypes;
    }

    private ResponseBodyEmitter getEmitter(MediaType mediaType) {
        return new ResponseBodyEmitter(STREAMING_TIMEOUT_VALUE) {

            @Override
            protected void extendResponse(ServerHttpResponse outputMessage) {
                outputMessage.getHeaders().setContentType(mediaType);
            }
        };
    }

    @SuppressWarnings("ConstantConditions")
    private void logExecutorWarning(MethodParameter returnType) {
        if (this.taskExecutorWarning && logger.isWarnEnabled()) {
            synchronized (this) {
                if (this.taskExecutorWarning) {
                    String executorTypeName = this.taskExecutor.getClreplaced().getSimpleName();
                    logger.warn("\n!!!\n" + "Streaming through a reactive type requires an Executor to write to the response.\n" + "Please, configure a TaskExecutor in the MVC config under \"async support\".\n" + "The " + executorTypeName + " currently in use is not suitable under load.\n" + "-------------------------------\n" + "Controller:\t" + returnType.getContainingClreplaced().getName() + "\n" + "Method:\t\t" + returnType.getMethod().getName() + "\n" + "Returning:\t" + ResolvableType.forMethodParameter(returnType).toString() + "\n" + "!!!");
                    this.taskExecutorWarning = false;
                }
            }
        }
    }

    private abstract static clreplaced AbstractEmitterSubscriber implements Subscriber<Object>, Runnable {

        private final ResponseBodyEmitter emitter;

        private final TaskExecutor taskExecutor;

        @Nullable
        private Subscription subscription;

        private final AtomicReference<Object> elementRef = new AtomicReference<>();

        @Nullable
        private Throwable error;

        private volatile boolean terminated;

        private final AtomicLong executing = new AtomicLong();

        private volatile boolean done;

        protected AbstractEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            this.emitter = emitter;
            this.taskExecutor = executor;
        }

        public void connect(ReactiveAdapter adapter, Object returnValue) {
            Publisher<Object> publisher = adapter.toPublisher(returnValue);
            publisher.subscribe(this);
        }

        protected ResponseBodyEmitter getEmitter() {
            return this.emitter;
        }

        @Override
        public final void onSubscribe(Subscription subscription) {
            this.subscription = subscription;
            this.emitter.onTimeout(() -> {
                if (logger.isTraceEnabled()) {
                    logger.trace("Connection timeout for " + this.emitter);
                }
                terminate();
                this.emitter.complete();
            });
            this.emitter.onError(this.emitter::completeWithError);
            subscription.request(1);
        }

        @Override
        public final void onNext(Object element) {
            this.elementRef.lazySet(element);
            trySchedule();
        }

        @Override
        public final void onError(Throwable ex) {
            this.error = ex;
            this.terminated = true;
            trySchedule();
        }

        @Override
        public final void onComplete() {
            this.terminated = true;
            trySchedule();
        }

        private void trySchedule() {
            if (this.executing.getAndIncrement() == 0) {
                schedule();
            }
        }

        private void schedule() {
            try {
                this.taskExecutor.execute(this);
            } catch (Throwable ex) {
                try {
                    terminate();
                } finally {
                    this.executing.decrementAndGet();
                    this.elementRef.lazySet(null);
                }
            }
        }

        @Override
        public void run() {
            if (this.done) {
                this.elementRef.lazySet(null);
                return;
            }
            // Check terminal signal before processing element..
            boolean isTerminated = this.terminated;
            Object element = this.elementRef.get();
            if (element != null) {
                this.elementRef.lazySet(null);
                replacedert.state(this.subscription != null, "No subscription");
                try {
                    send(element);
                    this.subscription.request(1);
                } catch (final Throwable ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Send for " + this.emitter + " failed: " + ex);
                    }
                    terminate();
                    return;
                }
            }
            if (isTerminated) {
                this.done = true;
                Throwable ex = this.error;
                this.error = null;
                if (ex != null) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Publisher for " + this.emitter + " failed: " + ex);
                    }
                    this.emitter.completeWithError(ex);
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Publisher for " + this.emitter + " completed");
                    }
                    this.emitter.complete();
                }
                return;
            }
            if (this.executing.decrementAndGet() != 0) {
                schedule();
            }
        }

        protected abstract void send(Object element) throws IOException;

        private void terminate() {
            this.done = true;
            if (this.subscription != null) {
                this.subscription.cancel();
            }
        }
    }

    private static clreplaced SseEmitterSubscriber extends AbstractEmitterSubscriber {

        SseEmitterSubscriber(SseEmitter sseEmitter, TaskExecutor executor) {
            super(sseEmitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            if (element instanceof ServerSentEvent) {
                ServerSentEvent<?> event = (ServerSentEvent<?>) element;
                ((SseEmitter) getEmitter()).send(adapt(event));
            } else {
                getEmitter().send(element, MediaType.APPLICATION_JSON);
            }
        }

        private SseEmitter.SseEventBuilder adapt(ServerSentEvent<?> sse) {
            SseEmitter.SseEventBuilder builder = SseEmitter.event();
            String id = sse.id();
            String event = sse.event();
            Duration retry = sse.retry();
            String comment = sse.comment();
            Object data = sse.data();
            if (id != null) {
                builder.id(id);
            }
            if (event != null) {
                builder.name(event);
            }
            if (data != null) {
                builder.data(data);
            }
            if (retry != null) {
                builder.reconnectTime(retry.toMillis());
            }
            if (comment != null) {
                builder.comment(comment);
            }
            return builder;
        }
    }

    private static clreplaced JsonEmitterSubscriber extends AbstractEmitterSubscriber {

        JsonEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            super(emitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            getEmitter().send(element, MediaType.APPLICATION_JSON);
            getEmitter().send("\n", MediaType.TEXT_PLAIN);
        }
    }

    private static clreplaced TextEmitterSubscriber extends AbstractEmitterSubscriber {

        TextEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            super(emitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            getEmitter().send(element, MediaType.TEXT_PLAIN);
        }
    }

    private static clreplaced DeferredResultSubscriber implements Subscriber<Object> {

        private final DeferredResult<Object> result;

        private final boolean multiValueSource;

        private final CollectedValuesList values;

        DeferredResultSubscriber(DeferredResult<Object> result, ReactiveAdapter adapter, ResolvableType elementType) {
            this.result = result;
            this.multiValueSource = adapter.isMultiValue();
            this.values = new CollectedValuesList(elementType);
        }

        public void connect(ReactiveAdapter adapter, Object returnValue) {
            Publisher<Object> publisher = adapter.toPublisher(returnValue);
            publisher.subscribe(this);
        }

        @Override
        public void onSubscribe(Subscription subscription) {
            this.result.onTimeout(subscription::cancel);
            subscription.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Object element) {
            this.values.add(element);
        }

        @Override
        public void onError(Throwable ex) {
            this.result.setErrorResult(ex);
        }

        @Override
        public void onComplete() {
            if (this.values.size() > 1 || this.multiValueSource) {
                this.result.setResult(this.values);
            } else if (this.values.size() == 1) {
                this.result.setResult(this.values.get(0));
            } else {
                this.result.setResult(null);
            }
        }
    }

    /**
     * List of collect values where all elements are a specified type.
     */
    @SuppressWarnings("serial")
    static clreplaced CollectedValuesList extends ArrayList<Object> {

        private final ResolvableType elementType;

        CollectedValuesList(ResolvableType elementType) {
            this.elementType = elementType;
        }

        public ResolvableType getReturnType() {
            return ResolvableType.forClreplacedWithGenerics(List.clreplaced, this.elementType);
        }
    }
}

19 View Source File : SimpleTaskWorkManager.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Specify the TaskExecutor to use for <i>synchronous</i> work execution
 * (i.e. {@link #doWork} calls).
 * <p>Default is a {@link org.springframework.core.task.SyncTaskExecutor}.
 */
public void setSyncTaskExecutor(TaskExecutor syncTaskExecutor) {
    this.syncTaskExecutor = syncTaskExecutor;
}

19 View Source File : ExecutorServiceAdapter.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Adapter that takes a Spring {@link org.springframework.core.task.TaskExecutor}
 * and exposes a full {@code java.util.concurrent.ExecutorService} for it.
 *
 * <p>This is primarily for adapting to client components that communicate via the
 * {@code java.util.concurrent.ExecutorService} API. It can also be used as
 * common ground between a local Spring {@code TaskExecutor} backend and a
 * JNDI-located {@code ManagedExecutorService} in a Java EE 7 environment.
 *
 * <p><b>NOTE:</b> This ExecutorService adapter does <em>not</em> support the
 * lifecycle methods in the {@code java.util.concurrent.ExecutorService} API
 * ("shutdown()" etc), similar to a server-wide {@code ManagedExecutorService}
 * in a Java EE 7 environment. The lifecycle is always up to the backend pool,
 * with this adapter acting as an access-only proxy for that target pool.
 *
 * @author Juergen Hoeller
 * @since 3.0
 * @see java.util.concurrent.ExecutorService
 */
public clreplaced ExecutorServiceAdapter extends AbstractExecutorService {

    private final TaskExecutor taskExecutor;

    /**
     * Create a new ExecutorServiceAdapter, using the given target executor.
     * @param taskExecutor the target executor to delegate to
     */
    public ExecutorServiceAdapter(TaskExecutor taskExecutor) {
        replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void execute(Runnable task) {
        this.taskExecutor.execute(task);
    }

    @Override
    public void shutdown() {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public List<Runnable> shutdownNow() {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public boolean isShutdown() {
        return false;
    }

    @Override
    public boolean isTerminated() {
        return false;
    }
}

19 View Source File : ConcurrentExecutorAdapter.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Adapter that exposes the {@link java.util.concurrent.Executor} interface
 * for any Spring {@link org.springframework.core.task.TaskExecutor}.
 *
 * <p>This is less useful as of Spring 3.0, since TaskExecutor itself
 * extends the Executor interface. The adapter is only relevant for
 * <em>hiding</em> the TaskExecutor nature of a given object now,
 * solely exposing the standard Executor interface to a client.
 *
 * @author Juergen Hoeller
 * @since 2.5
 * @see java.util.concurrent.Executor
 * @see org.springframework.core.task.TaskExecutor
 */
public clreplaced ConcurrentExecutorAdapter implements Executor {

    private final TaskExecutor taskExecutor;

    /**
     * Create a new ConcurrentExecutorAdapter for the given Spring TaskExecutor.
     * @param taskExecutor the Spring TaskExecutor to wrap
     */
    public ConcurrentExecutorAdapter(TaskExecutor taskExecutor) {
        replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void execute(Runnable command) {
        this.taskExecutor.execute(command);
    }
}

19 View Source File : ProcessTailInboundChannelAdapterFactoryBean.java
License : MIT License
Project Creator : Toparvion

public void setTaskExecutor(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
}

19 View Source File : ProcessTailAdapterSpec.java
License : MIT License
Project Creator : Toparvion

/**
 * Configure a task executor. Defaults to a
 * {@link org.springframework.core.task.SimpleAsyncTaskExecutor}.
 *
 * @param taskExecutor the taskExecutor.
 * @return the spec.
 */
public ProcessTailAdapterSpec taskExecutor(TaskExecutor taskExecutor) {
    this.factoryBean.setTaskExecutor(taskExecutor);
    return _this();
}

19 View Source File : InstrumentApplication.java
License : MIT License
Project Creator : spring2go

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
    return new CommandLineRunner() {

        public void run(String... args) throws Exception {
            // 10 jobs per worker
            workerManager = new WorkerManager(queue, 1, 4, 10);
            executor.execute(workerManager);
            System.out.println("WorkerManager thread started...");
        }
    };
}

19 View Source File : HttpSimulatorApplication.java
License : MIT License
Project Creator : spring2go

@Bean
public CommandLineRunner schedulingRunner(TaskExecutor executor) {
    return new CommandLineRunner() {

        public void run(String... args) throws Exception {
            simulator = new ActivitySimulator(opts);
            executor.execute(simulator);
            System.out.println("Simulator thread started...");
        }
    };
}

19 View Source File : SpringBatchFlowRunner.java
License : Apache License 2.0
Project Creator : spring-cloud

private TaskExecutor taskExecutor() {
    TaskExecutor taskExecutor = this.flowRunnerTaskExecutorSupplier.get();
    EXECUTORS.add(taskExecutor);
    return taskExecutor;
}

19 View Source File : WebSocketMessageBrokerStats.java
License : Apache License 2.0
Project Creator : SourceHot

public void setInboundChannelExecutor(TaskExecutor inboundChannelExecutor) {
    this.inboundChannelExecutor = inboundChannelExecutor;
}

19 View Source File : WebSocketMessageBrokerStats.java
License : Apache License 2.0
Project Creator : SourceHot

public void setOutboundChannelExecutor(TaskExecutor outboundChannelExecutor) {
    this.outboundChannelExecutor = outboundChannelExecutor;
}

19 View Source File : TelegramConfiguration.java
License : MIT License
Project Creator : OlegNyr

private Supplier<OkHttpClient> getOkHttpClientSupplier(TaskExecutor taskExecutorLocal) {
    return new Supplier<OkHttpClient>() {

        @Override
        public OkHttpClient get() {
            return new OkHttpClient().newBuilder().dispatcher(new Dispatcher(new ExecutorServiceAdapter(taskExecutorLocal))).build();
        }
    };
}

19 View Source File : ReactiveTypeHandler.java
License : MIT License
Project Creator : mindcarver

/**
 * Private helper clreplaced to replacedist with handling "reactive" return values types
 * that can be adapted to a Reactive Streams {@link Publisher} through the
 * {@link ReactiveAdapterRegistry}.
 *
 * <p>Such return values may be bridged to a {@link ResponseBodyEmitter} for
 * streaming purposes at the presence of a streaming media type or based on the
 * generic type.
 *
 * <p>For all other cases {@code Publisher} output is collected and bridged to
 * {@link DeferredResult} for standard async request processing.
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 */
clreplaced ReactiveTypeHandler {

    private static final long STREAMING_TIMEOUT_VALUE = -1;

    private static Log logger = LogFactory.getLog(ReactiveTypeHandler.clreplaced);

    private final ReactiveAdapterRegistry reactiveRegistry;

    private final TaskExecutor taskExecutor;

    private Boolean taskExecutorWarning;

    private final ContentNegotiationManager contentNegotiationManager;

    public ReactiveTypeHandler() {
        this(ReactiveAdapterRegistry.getSharedInstance(), new SyncTaskExecutor(), new ContentNegotiationManager());
    }

    ReactiveTypeHandler(ReactiveAdapterRegistry registry, TaskExecutor executor, ContentNegotiationManager manager) {
        replacedert.notNull(registry, "ReactiveAdapterRegistry is required");
        replacedert.notNull(executor, "TaskExecutor is required");
        replacedert.notNull(manager, "ContentNegotiationManager is required");
        this.reactiveRegistry = registry;
        this.taskExecutor = executor;
        this.taskExecutorWarning = executor instanceof SimpleAsyncTaskExecutor || executor instanceof SyncTaskExecutor;
        this.contentNegotiationManager = manager;
    }

    /**
     * Whether the type can be adapted to a Reactive Streams {@link Publisher}.
     */
    public boolean isReactiveType(Clreplaced<?> type) {
        return (this.reactiveRegistry.hasAdapters() && this.reactiveRegistry.getAdapter(type) != null);
    }

    /**
     * Process the given reactive return value and decide whether to adapt it
     * to a {@link ResponseBodyEmitter} or a {@link DeferredResult}.
     * @return an emitter for streaming, or {@code null} if handled internally
     * with a {@link DeferredResult}
     */
    @Nullable
    public ResponseBodyEmitter handleValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mav, NativeWebRequest request) throws Exception {
        replacedert.notNull(returnValue, "Expected return value");
        ReactiveAdapter adapter = this.reactiveRegistry.getAdapter(returnValue.getClreplaced());
        replacedert.state(adapter != null, () -> "Unexpected return value: " + returnValue);
        ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
        Clreplaced<?> elementClreplaced = elementType.toClreplaced();
        Collection<MediaType> mediaTypes = getMediaTypes(request);
        Optional<MediaType> mediaType = mediaTypes.stream().filter(MimeType::isConcrete).findFirst();
        if (adapter.isMultiValue()) {
            if (mediaTypes.stream().anyMatch(MediaType.TEXT_EVENT_STREAM::includes) || ServerSentEvent.clreplaced.isreplacedignableFrom(elementClreplaced)) {
                logExecutorWarning(returnType);
                SseEmitter emitter = new SseEmitter(STREAMING_TIMEOUT_VALUE);
                new SseEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
            if (CharSequence.clreplaced.isreplacedignableFrom(elementClreplaced)) {
                logExecutorWarning(returnType);
                ResponseBodyEmitter emitter = getEmitter(mediaType.orElse(MediaType.TEXT_PLAIN));
                new TextEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
            if (mediaTypes.stream().anyMatch(MediaType.APPLICATION_STREAM_JSON::includes)) {
                logExecutorWarning(returnType);
                ResponseBodyEmitter emitter = getEmitter(MediaType.APPLICATION_STREAM_JSON);
                new JsonEmitterSubscriber(emitter, this.taskExecutor).connect(adapter, returnValue);
                return emitter;
            }
        }
        // Not streaming...
        DeferredResult<Object> result = new DeferredResult<>();
        new DeferredResultSubscriber(result, adapter, elementType).connect(adapter, returnValue);
        WebAsyncUtils.getAsyncManager(request).startDeferredResultProcessing(result, mav);
        return null;
    }

    @SuppressWarnings("unchecked")
    private Collection<MediaType> getMediaTypes(NativeWebRequest request) throws HttpMediaTypeNotAcceptableException {
        Collection<MediaType> mediaTypes = (Collection<MediaType>) request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
        return CollectionUtils.isEmpty(mediaTypes) ? this.contentNegotiationManager.resolveMediaTypes(request) : mediaTypes;
    }

    private ResponseBodyEmitter getEmitter(MediaType mediaType) {
        return new ResponseBodyEmitter(STREAMING_TIMEOUT_VALUE) {

            @Override
            protected void extendResponse(ServerHttpResponse outputMessage) {
                outputMessage.getHeaders().setContentType(mediaType);
            }
        };
    }

    @SuppressWarnings("ConstantConditions")
    private void logExecutorWarning(MethodParameter returnType) {
        if (this.taskExecutorWarning && logger.isWarnEnabled()) {
            synchronized (this) {
                if (this.taskExecutorWarning) {
                    String executorTypeName = this.taskExecutor.getClreplaced().getSimpleName();
                    logger.warn("\n!!!\n" + "Streaming through a reactive type requires an Executor to write to the response.\n" + "Please, configure a TaskExecutor in the MVC config under \"async support\".\n" + "The " + executorTypeName + " currently in use is not suitable under load.\n" + "-------------------------------\n" + "Controller:\t" + returnType.getContainingClreplaced().getName() + "\n" + "Method:\t\t" + returnType.getMethod().getName() + "\n" + "Returning:\t" + ResolvableType.forMethodParameter(returnType).toString() + "\n" + "!!!");
                    this.taskExecutorWarning = false;
                }
            }
        }
    }

    private abstract static clreplaced AbstractEmitterSubscriber implements Subscriber<Object>, Runnable {

        private final ResponseBodyEmitter emitter;

        private final TaskExecutor taskExecutor;

        @Nullable
        private Subscription subscription;

        private final AtomicReference<Object> elementRef = new AtomicReference<>();

        @Nullable
        private Throwable error;

        private volatile boolean terminated;

        private final AtomicLong executing = new AtomicLong();

        private volatile boolean done;

        protected AbstractEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            this.emitter = emitter;
            this.taskExecutor = executor;
        }

        public void connect(ReactiveAdapter adapter, Object returnValue) {
            Publisher<Object> publisher = adapter.toPublisher(returnValue);
            publisher.subscribe(this);
        }

        protected ResponseBodyEmitter getEmitter() {
            return this.emitter;
        }

        @Override
        public final void onSubscribe(Subscription subscription) {
            this.subscription = subscription;
            this.emitter.onTimeout(() -> {
                if (logger.isTraceEnabled()) {
                    logger.trace("Connection timeout for " + this.emitter);
                }
                terminate();
                this.emitter.complete();
            });
            this.emitter.onError(this.emitter::completeWithError);
            subscription.request(1);
        }

        @Override
        public final void onNext(Object element) {
            this.elementRef.lazySet(element);
            trySchedule();
        }

        @Override
        public final void onError(Throwable ex) {
            this.error = ex;
            this.terminated = true;
            trySchedule();
        }

        @Override
        public final void onComplete() {
            this.terminated = true;
            trySchedule();
        }

        private void trySchedule() {
            if (this.executing.getAndIncrement() == 0) {
                schedule();
            }
        }

        private void schedule() {
            try {
                this.taskExecutor.execute(this);
            } catch (Throwable ex) {
                try {
                    terminate();
                } finally {
                    this.executing.decrementAndGet();
                    this.elementRef.lazySet(null);
                }
            }
        }

        @Override
        public void run() {
            if (this.done) {
                this.elementRef.lazySet(null);
                return;
            }
            // Check terminal signal before processing element..
            boolean isTerminated = this.terminated;
            Object element = this.elementRef.get();
            if (element != null) {
                this.elementRef.lazySet(null);
                replacedert.state(this.subscription != null, "No subscription");
                try {
                    send(element);
                    this.subscription.request(1);
                } catch (final Throwable ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Send for " + this.emitter + " failed: " + ex);
                    }
                    terminate();
                    return;
                }
            }
            if (isTerminated) {
                this.done = true;
                Throwable ex = this.error;
                this.error = null;
                if (ex != null) {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Publisher for " + this.emitter + " failed: " + ex);
                    }
                    this.emitter.completeWithError(ex);
                } else {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Publisher for " + this.emitter + " completed");
                    }
                    this.emitter.complete();
                }
                return;
            }
            if (this.executing.decrementAndGet() != 0) {
                schedule();
            }
        }

        protected abstract void send(Object element) throws IOException;

        private void terminate() {
            this.done = true;
            if (this.subscription != null) {
                this.subscription.cancel();
            }
        }
    }

    private static clreplaced SseEmitterSubscriber extends AbstractEmitterSubscriber {

        SseEmitterSubscriber(SseEmitter sseEmitter, TaskExecutor executor) {
            super(sseEmitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            if (element instanceof ServerSentEvent) {
                ServerSentEvent<?> event = (ServerSentEvent<?>) element;
                ((SseEmitter) getEmitter()).send(adapt(event));
            } else {
                getEmitter().send(element, MediaType.APPLICATION_JSON);
            }
        }

        private SseEmitter.SseEventBuilder adapt(ServerSentEvent<?> sse) {
            SseEmitter.SseEventBuilder builder = SseEmitter.event();
            String id = sse.id();
            String event = sse.event();
            Duration retry = sse.retry();
            String comment = sse.comment();
            Object data = sse.data();
            if (id != null) {
                builder.id(id);
            }
            if (event != null) {
                builder.name(event);
            }
            if (data != null) {
                builder.data(data);
            }
            if (retry != null) {
                builder.reconnectTime(retry.toMillis());
            }
            if (comment != null) {
                builder.comment(comment);
            }
            return builder;
        }
    }

    private static clreplaced JsonEmitterSubscriber extends AbstractEmitterSubscriber {

        JsonEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            super(emitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            getEmitter().send(element, MediaType.APPLICATION_JSON);
            getEmitter().send("\n", MediaType.TEXT_PLAIN);
        }
    }

    private static clreplaced TextEmitterSubscriber extends AbstractEmitterSubscriber {

        TextEmitterSubscriber(ResponseBodyEmitter emitter, TaskExecutor executor) {
            super(emitter, executor);
        }

        @Override
        protected void send(Object element) throws IOException {
            getEmitter().send(element, MediaType.TEXT_PLAIN);
        }
    }

    private static clreplaced DeferredResultSubscriber implements Subscriber<Object> {

        private final DeferredResult<Object> result;

        private final boolean multiValueSource;

        private final CollectedValuesList values;

        DeferredResultSubscriber(DeferredResult<Object> result, ReactiveAdapter adapter, ResolvableType elementType) {
            this.result = result;
            this.multiValueSource = adapter.isMultiValue();
            this.values = new CollectedValuesList(elementType);
        }

        public void connect(ReactiveAdapter adapter, Object returnValue) {
            Publisher<Object> publisher = adapter.toPublisher(returnValue);
            publisher.subscribe(this);
        }

        @Override
        public void onSubscribe(Subscription subscription) {
            this.result.onTimeout(subscription::cancel);
            subscription.request(Long.MAX_VALUE);
        }

        @Override
        public void onNext(Object element) {
            this.values.add(element);
        }

        @Override
        public void onError(Throwable ex) {
            this.result.setErrorResult(ex);
        }

        @Override
        public void onComplete() {
            if (this.values.size() > 1 || this.multiValueSource) {
                this.result.setResult(this.values);
            } else if (this.values.size() == 1) {
                this.result.setResult(this.values.get(0));
            } else {
                this.result.setResult(null);
            }
        }
    }

    /**
     * List of collect values where all elements are a specified type.
     */
    @SuppressWarnings("serial")
    static clreplaced CollectedValuesList extends ArrayList<Object> {

        private final ResolvableType elementType;

        CollectedValuesList(ResolvableType elementType) {
            this.elementType = elementType;
        }

        public ResolvableType getReturnType() {
            return ResolvableType.forClreplacedWithGenerics(List.clreplaced, this.elementType);
        }
    }
}

19 View Source File : RestTemplateXhrTransport.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Configure the {@code TaskExecutor} to use to execute XHR receive requests.
 * <p>By default {@link org.springframework.core.task.SimpleAsyncTaskExecutor
 * SimpleAsyncTaskExecutor} is configured which creates a new thread every
 * time the transports connects.
 */
public void setTaskExecutor(TaskExecutor taskExecutor) {
    replacedert.notNull(this.taskExecutor);
    this.taskExecutor = taskExecutor;
}

19 View Source File : ExecutorServiceAdapter.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Adapter that takes a Spring {@link org.springframework.core.task.TaskExecutor})
 * and exposes a full {@code java.util.concurrent.ExecutorService} for it.
 *
 * <p>This is primarily for adapting to client components that communicate via the
 * {@code java.util.concurrent.ExecutorService} API. It can also be used as
 * common ground between a local Spring {@code TaskExecutor} backend and a
 * JNDI-located {@code ManagedExecutorService} in a Java EE 6 environment.
 *
 * <p><b>NOTE:</b> This ExecutorService adapter does <em>not</em> support the
 * lifecycle methods in the {@code java.util.concurrent.ExecutorService} API
 * ("shutdown()" etc), similar to a server-wide {@code ManagedExecutorService}
 * in a Java EE 6 environment. The lifecycle is always up to the backend pool,
 * with this adapter acting as an access-only proxy for that target pool.
 *
 * @author Juergen Hoeller
 * @since 3.0
 * @see java.util.concurrent.ExecutorService
 */
public clreplaced ExecutorServiceAdapter extends AbstractExecutorService {

    private final TaskExecutor taskExecutor;

    /**
     * Create a new ExecutorServiceAdapter, using the given target executor.
     * @param taskExecutor the target executor to delegate to
     */
    public ExecutorServiceAdapter(TaskExecutor taskExecutor) {
        replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void execute(Runnable task) {
        this.taskExecutor.execute(task);
    }

    @Override
    public void shutdown() {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public List<Runnable> shutdownNow() {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        throw new IllegalStateException("Manual shutdown not supported - ExecutorServiceAdapter is dependent on an external lifecycle");
    }

    @Override
    public boolean isShutdown() {
        return false;
    }

    @Override
    public boolean isTerminated() {
        return false;
    }
}

19 View Source File : TaskExecutorFactoryBean.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * FactoryBean for creating ThreadPoolTaskExecutor instances, choosing
 * between the standard concurrent and the backport-concurrent variant.
 *
 * @author Mark Fisher
 * @author Juergen Hoeller
 * @since 3.0
 */
public clreplaced TaskExecutorFactoryBean implements FactoryBean<TaskExecutor>, BeanNameAware, InitializingBean, DisposableBean {

    private String poolSize;

    private Integer queueCapacity;

    private Object rejectedExecutionHandler;

    private Integer keepAliveSeconds;

    private String beanName;

    private TaskExecutor target;

    public void setPoolSize(String poolSize) {
        this.poolSize = poolSize;
    }

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public void setRejectedExecutionHandler(Object rejectedExecutionHandler) {
        this.rejectedExecutionHandler = rejectedExecutionHandler;
    }

    public void setKeepAliveSeconds(int keepAliveSeconds) {
        this.keepAliveSeconds = keepAliveSeconds;
    }

    @Override
    public void setBeanName(String beanName) {
        this.beanName = beanName;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.clreplaced);
        determinePoolSizeRange(bw);
        if (this.queueCapacity != null) {
            bw.setPropertyValue("queueCapacity", this.queueCapacity);
        }
        if (this.keepAliveSeconds != null) {
            bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds);
        }
        if (this.rejectedExecutionHandler != null) {
            bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler);
        }
        if (this.beanName != null) {
            bw.setPropertyValue("threadNamePrefix", this.beanName + "-");
        }
        this.target = (TaskExecutor) bw.getWrappedInstance();
        if (this.target instanceof InitializingBean) {
            ((InitializingBean) this.target).afterPropertiesSet();
        }
    }

    private void determinePoolSizeRange(BeanWrapper bw) {
        if (StringUtils.hasText(this.poolSize)) {
            try {
                int corePoolSize;
                int maxPoolSize;
                int separatorIndex = this.poolSize.indexOf('-');
                if (separatorIndex != -1) {
                    corePoolSize = Integer.valueOf(this.poolSize.substring(0, separatorIndex));
                    maxPoolSize = Integer.valueOf(this.poolSize.substring(separatorIndex + 1, this.poolSize.length()));
                    if (corePoolSize > maxPoolSize) {
                        throw new IllegalArgumentException("Lower bound of pool-size range must not exceed the upper bound");
                    }
                    if (this.queueCapacity == null) {
                        // no queue-capacity provided, so unbounded
                        if (corePoolSize == 0) {
                            // actually set 'corePoolSize' to the upper bound of the range
                            // but allow core threads to timeout
                            bw.setPropertyValue("allowCoreThreadTimeOut", true);
                            corePoolSize = maxPoolSize;
                        } else {
                            // non-zero lower bound implies a core-max size range
                            throw new IllegalArgumentException("A non-zero lower bound for the size range requires a queue-capacity value");
                        }
                    }
                } else {
                    Integer value = Integer.valueOf(this.poolSize);
                    corePoolSize = value;
                    maxPoolSize = value;
                }
                bw.setPropertyValue("corePoolSize", corePoolSize);
                bw.setPropertyValue("maxPoolSize", maxPoolSize);
            } catch (NumberFormatException ex) {
                throw new IllegalArgumentException("Invalid pool-size value [" + this.poolSize + "]: only single " + "maximum integer (e.g. \"5\") and minimum-maximum range (e.g. \"3-5\") are supported", ex);
            }
        }
    }

    @Override
    public TaskExecutor getObject() {
        return this.target;
    }

    @Override
    public Clreplaced<? extends TaskExecutor> getObjectType() {
        return (this.target != null ? this.target.getClreplaced() : ThreadPoolTaskExecutor.clreplaced);
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        if (this.target instanceof DisposableBean) {
            ((DisposableBean) this.target).destroy();
        }
    }
}

/**
 * 事件:ApplicationEvent
 * 事件监听器:ApplicationListener,对监听到的事件进行处理。
 * 事件广播器:ApplicationEventMulticaster,将Springpublish的事件广播给所有的监听器。
 * Spring在ApplicationContext接口的抽象实现类AbstractApplicationContext中完成了事件体系的搭建。
 * AbstractApplicationContext拥有一个applicationEventMulticaster成员变
 * 量,applicationEventMulticaster提供了容器监听器的注册表。
 *
 * @author hui.zhao.cfs
 */
public clreplaced AsyncApplicationEventMulticaster extends AbstractApplicationEventMulticaster {

    private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = (taskExecutor != null ? taskExecutor : new SimpleAsyncTaskExecutor());
    }

    protected TaskExecutor getTaskExecutor() {
        return this.taskExecutor;
    }

    @SuppressWarnings("unchecked")
    public void multicastEvent(final ApplicationEvent event) {
        for (Iterator<ApplicationListener<?>> it = getApplicationListeners().iterator(); it.hasNext(); ) {
            final ApplicationListener listener = it.next();
            getTaskExecutor().execute(new Runnable() {

                public void run() {
                    listener.onApplicationEvent(event);
                }
            });
        }
    }

    @Override
    public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
    }
}

public void setTaskExecutor(TaskExecutor taskExecutor) {
    this.taskExecutor = (taskExecutor != null ? taskExecutor : new SimpleAsyncTaskExecutor());
}

19 View Source File : DiscordEventListener.java
License : GNU General Public License v3.0
Project Creator : JuniperBot

public abstract clreplaced DiscordEventListener extends ListenerAdapter {

    @Autowired
    protected TaskExecutor taskExecutor;

    @Autowired
    protected ContextService contextService;

    @Autowired
    protected ApplicationContext applicationContext;

    @Autowired
    protected DiscordEnreplacedyAccessor enreplacedyAccessor;

    private AuditService auditService;

    protected AuditService getAuditService() {
        if (auditService == null) {
            auditService = applicationContext.getBean(AuditService.clreplaced);
        }
        return auditService;
    }
}

19 View Source File : RabbitOperations.java
License : Apache License 2.0
Project Creator : FlowCI

public void startConsumer(String queue, boolean autoAck, OnMessage onMessage, TaskExecutor executor) throws IOException {
    Consumer consumer = new DefaultConsumer(channel) {

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) {
            if (executor == null) {
                doHandleDelivery(envelope, properties, body, onMessage);
                return;
            }
            executor.execute(() -> doHandleDelivery(envelope, properties, body, onMessage));
        }
    };
    String tag = getChannel().basicConsume(queue, autoAck, consumer);
    consumers.put(queue, tag);
    log.info("[Consumer STARTED] queue {} with tag {}", queue, tag);
}

19 View Source File : ArchiveService.java
License : European Union Public License 1.1
Project Creator : EUSurvey

@Service("archiveService")
public clreplaced ArchiveService extends BasicService {

    @Resource(name = "taskExecutorLong")
    protected TaskExecutor taskExecutorLong;

    @Autowired
    private SqlQueryService sqlQueryService;

    @Transactional(readOnly = false)
    public void update(Archive archive) {
        Session session = sessionFactory.getCurrentSession();
        archive = (Archive) session.merge(archive);
        session.update(archive);
    }

    @Transactional(readOnly = false)
    public void delete(Archive archive) throws IOException {
        String uid = archive.getSurveyUID();
        Session session = sessionFactory.getCurrentSession();
        archive = (Archive) session.merge(archive);
        session.delete(archive);
        // delete archive files
        java.io.File file = fileService.getArchiveFile(uid, uid);
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + ".pdf");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + "statistics.pdf");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + "statistics.xls");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + "results.xls");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + "results.zip");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFile(uid, uid + "results.xls.zip");
        Files.deleteIfExists(file.toPath());
        file = fileService.getArchiveFolder(uid);
        Files.deleteIfExists(file.toPath());
        // delete old archive files
        file = new java.io.File(archiveFileDir + uid);
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + ".pdf");
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + "statistics.pdf");
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + "statistics.xls");
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + "results.xls");
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + "results.zip");
        Files.deleteIfExists(file.toPath());
        file = new java.io.File(archiveFileDir + uid + "results.xls.zip");
        Files.deleteIfExists(file.toPath());
    }

    @Transactional(readOnly = false)
    public void add(Archive archive) {
        Session session = sessionFactory.getCurrentSession();
        session.saveOrUpdate(archive);
        session.flush();
    }

    @Transactional(readOnly = true)
    public Archive get(int id) {
        Session session = sessionFactory.getCurrentSession();
        return (Archive) session.get(Archive.clreplaced, id);
    }

    public Survey restore(Archive archive, User user, String alias) throws Exception {
        java.io.File file = fileService.getArchiveFile(archive.getSurveyUID(), archive.getSurveyUID());
        if (!file.exists())
            file = new java.io.File(archiveFileDir + archive.getSurveyUID());
        if (file.exists()) {
            ImportResult result = SurveyExportHelper.importSurvey(file, fileService, null);
            if (result != null && result.getSurvey() != null) {
                Survey existing = null;
                if (alias != null && alias.length() > 0) {
                    existing = surveyService.getSurvey(alias, true, false, false, false, null, true, false);
                } else {
                    existing = surveyService.getSurvey(result.getSurvey().getShortname(), true, false, false, false, null, true, false);
                }
                if (existing != null) {
                    throw new MessageException("A survey with this alias already exists and cannot be imported: " + result.getSurvey().getShortname());
                } else {
                    if (alias != null && alias.length() > 0) {
                        result.getSurvey().setShortname(alias);
                        if (result.getActiveSurvey() != null) {
                            result.getActiveSurvey().setShortname(alias);
                        }
                        for (Survey s : result.getOldSurveys().values()) {
                            s.setShortname(alias);
                        }
                    }
                    int id = surveyService.importSurvey(result, user, true);
                    delete(archive);
                    return surveyService.getSurvey(id);
                }
            } else {
                throw new MessageException("The survey could not be imported: " + archive.getSurveyreplacedle());
            }
        }
        throw new MessageException("The survey could not be imported as the file does not exist: " + archive.getSurveyreplacedle());
    }

    @Transactional(readOnly = true)
    public List<Archive> getAllArchives(ArchiveFilter filter, int page, int rowsPerPage, boolean includingErrors) throws Exception {
        Session session = sessionFactory.getCurrentSession();
        String hql = "FROM Archive a WHERE a.error IS NULL";
        if (includingErrors) {
            hql = "FROM Archive a WHERE a.id > 0";
        }
        Map<String, Object> params = new HashMap<>();
        if (filter.getUniqueId() != null && filter.getUniqueId().trim().length() > 0) {
            hql += " AND a.surveyUID LIKE :uid";
            params.put("uid", "%" + filter.getUniqueId() + "%");
        }
        if (filter.getUserId() > 0) {
            hql += " AND a.userId = :userid";
            params.put("userid", filter.getUserId());
        }
        if (filter.getFinished() != null && filter.getFinished()) {
            hql += " AND a.finished = true";
        }
        if (filter.getShortname() != null && filter.getShortname().trim().length() > 0) {
            hql += " AND a.surveyShortname LIKE :shortname";
            params.put(Constants.SHORTNAME, "%" + filter.getShortname() + "%");
        }
        if (filter.getreplacedle() != null && filter.getreplacedle().trim().length() > 0) {
            hql += " AND a.surveyreplacedle LIKE :replacedle";
            params.put("replacedle", "%" + filter.getreplacedle() + "%");
        }
        if (filter.getOwner() != null && filter.getOwner().trim().length() > 0) {
            hql += " AND a.owner LIKE :owner";
            params.put("owner", "%" + filter.getOwner() + "%");
        }
        if (filter.getCreatedFrom() != null) {
            hql += " AND a.created >= :createdFrom";
            params.put("createdFrom", filter.getCreatedFrom());
        }
        if (filter.getCreatedTo() != null) {
            hql += " AND a.created < :createdTo";
            Calendar c = Calendar.getInstance();
            c.setTime(filter.getCreatedTo());
            c.add(Calendar.DAY_OF_MONTH, 1);
            params.put("createdTo", c.getTime());
        }
        if (filter.getArchivedFrom() != null) {
            hql += " AND a.archived >= :archivedFrom";
            params.put("archivedFrom", filter.getArchivedFrom());
        }
        if (filter.getArchivedTo() != null) {
            hql += " AND a.archived < :archivedTo";
            Calendar c = Calendar.getInstance();
            c.setTime(filter.getArchivedTo());
            c.add(Calendar.DAY_OF_MONTH, 1);
            params.put("archivedTo", c.getTime());
        }
        if (filter.getSortKey() != null && filter.getSortKey().length() > 0) {
            hql += " ORDER BY " + filter.getSortKey() + " " + filter.getSortOrder();
        }
        Query query = session.createQuery(hql);
        sqlQueryService.setParameters(query, params);
        @SuppressWarnings("unchecked")
        List<Archive> result = query.setFirstResult((page - 1) * rowsPerPage).setMaxResults(rowsPerPage).list();
        return result;
    }

    @Transactional(readOnly = true)
    public int getNumberOfArchives(Integer userId) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("SELECT COUNT(*) FROM Archive a WHERE a.userId = :userId").setInteger("userId", userId);
        return ConversionTools.getValue(query.uniqueResult());
    }

    @Transactional(readOnly = true)
    public List<Archive> getArchivesToRestart() {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM Archive a WHERE a.finished = false AND a.error IS NULL");
        @SuppressWarnings("unchecked")
        List<Archive> result = query.list();
        return result;
    }

    @Transactional(readOnly = false)
    public void markRestoring(Archive archive) {
        archive.setRestoring(true);
        update(archive);
    }

    @Transactional(readOnly = false)
    public void unmarkRestoring(Archive archive) {
        archive.setRestoring(false);
        update(archive);
    }

    @Transactional
    public Archive getArchive(Integer userid, String shortname) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM Archive a WHERE a.userId = :userId AND a.surveyShortname = :shortname AND a.finished = true AND a.error IS NULL").setInteger("userId", userid).setString(Constants.SHORTNAME, shortname);
        @SuppressWarnings("unchecked")
        List<Archive> result = query.list();
        if (!result.isEmpty())
            return result.get(0);
        return null;
    }

    @Transactional
    public String getSurveyUIDForArchivedSurveyShortname(String shortname) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("SELECT a.surveyUID FROM Archive a WHERE a.surveyShortname = :shortname");
        query.setString(Constants.SHORTNAME, shortname);
        return (String) query.uniqueResult();
    }

    @Transactional
    public List<Archive> getArchivesForUser(int userid) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("FROM Archive a WHERE a.userId = :userId").setInteger("userId", userid);
        @SuppressWarnings("unchecked")
        List<Archive> result = query.list();
        return result;
    }
}

19 View Source File : ExtenderConfigurationDefaultSettingsTest.java
License : Apache License 2.0
Project Creator : eclipse

public void testShutdownTaskExecutor() throws Exception {
    TaskExecutor executor = config.getShutdownTaskExecutor();
    replacedertTrue(executor instanceof ThreadPoolTaskExecutor);
}

19 View Source File : DependencyWaiterApplicationContextExecutor.java
License : Apache License 2.0
Project Creator : eclipse

public void setTaskExecutor(TaskExecutor taskExec) {
    synchronized (monitor) {
        this.taskExecutor = taskExec;
    }
}

19 View Source File : LifecycleManager.java
License : Apache License 2.0
Project Creator : eclipse

/**
 * Manager handling the startup/shutdown threading issues regarding OSGi contexts. Used by {@link ContextLoaderListener}
 * .
 *
 * @author Costin Leau
 */
clreplaced LifecycleManager implements DisposableBean {

    /**
     * logger
     */
    private static final Log log = LogFactory.getLog(LifecycleManager.clreplaced);

    /**
     * The contexts we are currently managing. Keys are bundle ids, values are ServiceDependentOsgiApplicationContexts
     * for the application context
     */
    private final Map<Long, ConfigurableOsgiBundleApplicationContext> managedContexts = new ConcurrentHashMap<Long, ConfigurableOsgiBundleApplicationContext>(16);

    /**
     * listener counter - used to properly synchronize shutdown
     */
    private Counter contextsStarted = new Counter("contextsStarted");

    // "Spring Application Context Creation Timer"
    private final Timer timer = new Timer("Spring DM Context Creation Timer", true);

    /**
     * Task executor used for bootstraping the Spring contexts in async mode
     */
    private final TaskExecutor taskExecutor;

    /**
     * ApplicationContext Creator
     */
    private final OsgiApplicationContextCreator contextCreator;

    /**
     * BFPP list
     */
    private final List<OsgiBeanFactoryPostProcessor> postProcessors;

    /**
     * shutdown task executor
     */
    private final TaskExecutor shutdownTaskExecutor;

    /**
     * Task executor which uses the same thread for running tasks. Used when doing a synchronous wait-for-dependencies.
     */
    private final TaskExecutor sameThreadTaskExecutor = new SyncTaskExecutor();

    private final OsgiBundleApplicationContextEventMulticaster multicaster;

    private final ExtenderConfiguration extenderConfiguration;

    private final BundleContext bundleContext;

    private final OsgiContextProcessor processor;

    private final ApplicationContextConfigurationFactory contextConfigurationFactory;

    private final VersionMatcher versionMatcher;

    private final TypeCompatibilityChecker typeChecker;

    LifecycleManager(ExtenderConfiguration extenderConfiguration, VersionMatcher versionMatcher, ApplicationContextConfigurationFactory appCtxCfgFactory, OsgiApplicationContextCreator osgiApplicationContextCreator, OsgiContextProcessor processor, TypeCompatibilityChecker checker, BundleContext context) {
        this.versionMatcher = versionMatcher;
        this.extenderConfiguration = extenderConfiguration;
        this.contextConfigurationFactory = appCtxCfgFactory;
        this.contextCreator = osgiApplicationContextCreator;
        this.processor = processor;
        this.taskExecutor = extenderConfiguration.getTaskExecutor();
        this.shutdownTaskExecutor = extenderConfiguration.getShutdownTaskExecutor();
        this.multicaster = extenderConfiguration.getEventMulticaster();
        this.postProcessors = extenderConfiguration.getPostProcessors();
        this.typeChecker = checker;
        this.bundleContext = context;
    }

    /**
     * Context creation is a potentially long-running activity (certainly more than we want to do on the synchronous
     * event callback).
     *
     * <p/> Based on our configuration, the context can be started on the same thread or on a different one.
     *
     * <p/> Kick off a background activity to create an application context for the given bundle if needed.
     *
     * <b>Note:</b> Make sure to do the fastest filtering first to avoid slow-downs on platforms with a big number of
     * plugins and wiring (i.e. Eclipse platform).
     *
     * @param bundle
     */
    protected void maybeCreateApplicationContextFor(Bundle bundle) {
        boolean debug = log.isDebugEnabled();
        String bundleString = "[" + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]";
        final Long bundleId = new Long(bundle.getBundleId());
        if (managedContexts.containsKey(bundleId)) {
            if (debug) {
                log.debug("Bundle " + bundleString + " is already managed; ignoring...");
            }
            return;
        }
        if (!versionMatcher.matchVersion(bundle)) {
            return;
        }
        BundleContext localBundleContext = OsgiBundleUtils.getBundleContext(bundle);
        if (localBundleContext == null) {
            if (debug)
                log.debug("Bundle " + bundleString + " has no bundle context; skipping...");
            return;
        }
        // initialize context
        final DelegatedExecutionOsgiBundleApplicationContext localApplicationContext;
        if (debug)
            log.debug("Inspecting bundle " + bundleString);
        try {
            localApplicationContext = contextCreator.createApplicationContext(localBundleContext);
        } catch (Exception ex) {
            log.error("Cannot create application context for bundle " + bundleString, ex);
            return;
        }
        if (localApplicationContext == null) {
            log.debug("No application context created for bundle " + bundleString);
            return;
        }
        if (typeChecker != null) {
            if (!typeChecker.isTypeCompatible(localBundleContext)) {
                log.info("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is not type compatible with extender " + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; ignoring bundle...");
                return;
            }
        }
        log.debug("Bundle " + OsgiStringUtils.nullSafeName(bundle) + " is type compatible with extender " + OsgiStringUtils.nullSafeName(bundleContext.getBundle()) + "; processing bundle...");
        // create a dedicated hook for this application context
        BeanFactoryPostProcessor processingHook = new OsgiBeanFactoryPostProcessorAdapter(localBundleContext, postProcessors);
        // add in the post processors
        localApplicationContext.addBeanFactoryPostProcessor(processingHook);
        // add the context to the tracker
        managedContexts.put(bundleId, localApplicationContext);
        localApplicationContext.setDelegatedEventMulticaster(multicaster);
        ApplicationContextConfiguration config = contextConfigurationFactory.createConfiguration(bundle);
        final boolean asynch = config.isCreateAsynchronously();
        // create refresh runnable
        Runnable contextRefresh = new Runnable() {

            public void run() {
                // post refresh events are caught through events
                if (log.isTraceEnabled()) {
                    log.trace("Calling pre-refresh on processor " + processor);
                }
                processor.preProcessRefresh(localApplicationContext);
                localApplicationContext.refresh();
            }
        };
        // executor used for creating the appCtx
        // chosen based on the sync/async configuration
        TaskExecutor executor = null;
        String creationType;
        // synch/asynch context creation
        if (asynch) {
            // for the async stuff use the executor
            executor = taskExecutor;
            creationType = "Asynchronous";
        } else {
            // for the sync stuff, use this thread
            executor = sameThreadTaskExecutor;
            creationType = "Synchronous";
        }
        if (debug) {
            log.debug(creationType + " context creation for bundle " + bundleString);
        }
        // wait/no wait for dependencies behaviour
        if (config.isWaitForDependencies()) {
            DependencyWaiterApplicationContextExecutor appCtxExecutor = new DependencyWaiterApplicationContextExecutor(localApplicationContext, !asynch, extenderConfiguration.getDependencyFactories());
            long timeout;
            // check whether a timeout has been defined
            if (config.isTimeoutDeclared()) {
                timeout = config.getTimeout();
                if (debug)
                    log.debug("Setting bundle-defined, wait-for-dependencies/graceperiod timeout value=" + timeout + " ms, for bundle " + bundleString);
            } else {
                timeout = extenderConfiguration.getDependencyWaitTime();
                if (debug)
                    log.debug("Setting globally defined wait-for-dependencies/graceperiod timeout value=" + timeout + " ms, for bundle " + bundleString);
            }
            appCtxExecutor.setTimeout(timeout);
            appCtxExecutor.sereplacedchdog(timer);
            appCtxExecutor.setTaskExecutor(executor);
            appCtxExecutor.setMonitoringCounter(contextsStarted);
            // set events publisher
            appCtxExecutor.setDelegatedMulticaster(this.multicaster);
            contextsStarted.increment();
        } else {
        // do nothing; by default contexts do not wait for services.
        }
        executor.execute(contextRefresh);
    }

    /**
     * Closing an application context is a potentially long-running activity, however, we *have* to do it synchronously
     * during the event process as the BundleContext object is not valid once we return from this method.
     *
     * @param bundle
     */
    protected void maybeCloseApplicationContextFor(Bundle bundle) {
        final ConfigurableOsgiBundleApplicationContext context = managedContexts.remove(bundle.getBundleId());
        if (context == null) {
            return;
        }
        maybeClose(context);
    }

    protected void maybeClose(final ConfigurableOsgiBundleApplicationContext context) {
        final String displayName = context.getDisplayName();
        Runnable shutdownTask = new Runnable() {

            private final String toString = "Closing runnable for context " + displayName;

            public void run() {
                closeApplicationContext(context);
            }

            public String toString() {
                return toString;
            }
        };
        if (extenderConfiguration.shouldShutdownAsynchronously()) {
            execute(shutdownTask, extenderConfiguration.getShutdownWaitTime(), shutdownTaskExecutor);
        } else {
            try {
                shutdownTask.run();
            } catch (Exception e) {
                log.error(displayName + " context shutdown failed.", e);
            }
        }
    }

    /**
     * Closes an application context. This is a convenience methods that invokes the event notification as well.
     *
     * @param ctx
     */
    private void closeApplicationContext(ConfigurableOsgiBundleApplicationContext ctx) {
        if (log.isDebugEnabled()) {
            log.debug("Closing application context " + ctx.getDisplayName());
        }
        if (log.isTraceEnabled()) {
            log.trace("Calling pre-close on processor " + processor);
        }
        processor.preProcessClose(ctx);
        try {
            ctx.close();
        } finally {
            if (log.isTraceEnabled()) {
                log.trace("Calling post close on processor " + processor);
            }
            processor.postProcessClose(ctx);
        }
    }

    public void destroy() {
        // first stop the watchdog
        stopTimer();
        // get hold of the needed bundles
        List<Bundle> bundles = new ArrayList<Bundle>(managedContexts.size());
        for (ConfigurableOsgiBundleApplicationContext context : managedContexts.values()) {
            bundles.add(context.getBundle());
        }
        boolean debug = log.isDebugEnabled();
        if (debug) {
            log.debug("Starting shutdown procedure for bundles " + bundles);
        }
        while (!bundles.isEmpty()) {
            Collection<Bundle> candidates = ShutdownSorter.getBundles(bundles);
            if (debug)
                log.debug("Staging shutdown for bundles " + candidates);
            final List<Runnable> taskList = new ArrayList<Runnable>(candidates.size());
            final List<ConfigurableOsgiBundleApplicationContext> closedContexts = Collections.synchronizedList(new ArrayList<ConfigurableOsgiBundleApplicationContext>());
            final Object[] contextClosingDown = new Object[1];
            for (Bundle shutdownBundle : candidates) {
                final ConfigurableOsgiBundleApplicationContext context = getManagedContext(shutdownBundle);
                if (context != null) {
                    closedContexts.add(context);
                    // add a new runnable
                    taskList.add(new Runnable() {

                        private final String toString = "Closing runnable for context " + context.getDisplayName();

                        public void run() {
                            contextClosingDown[0] = context;
                            // eliminate context
                            closedContexts.remove(context);
                            closeApplicationContext(context);
                        }

                        public String toString() {
                            return toString;
                        }
                    });
                }
            }
            // tasks
            final Runnable[] tasks = taskList.toArray(new Runnable[taskList.size()]);
            for (Runnable task : tasks) {
                if (extenderConfiguration.shouldShutdownAsynchronously()) {
                    if (execute(task, extenderConfiguration.getShutdownWaitTime(), shutdownTaskExecutor)) {
                        if (debug) {
                            log.debug(contextClosingDown[0] + " context did not close successfully; forcing shutdown...");
                        }
                    }
                } else {
                    try {
                        task.run();
                    } catch (Exception e) {
                        log.error(contextClosingDown[0] + " context close failed.", e);
                    }
                }
            }
        }
        this.managedContexts.clear();
        // before bailing out; wait for the threads that might be left by
        // the task executor
        stopTaskExecutor();
    }

    public ConfigurableOsgiBundleApplicationContext getManagedContext(Bundle bundle) {
        ConfigurableOsgiBundleApplicationContext context = null;
        try {
            Long id = new Long(bundle.getBundleId());
            context = (ConfigurableOsgiBundleApplicationContext) managedContexts.get(id);
        } catch (IllegalStateException _) {
        // ignore
        }
        return context;
    }

    /**
     * Do some additional waiting so the service dependency listeners detect the shutdown.
     */
    private void stopTaskExecutor() {
        boolean debug = log.isDebugEnabled();
        if (debug)
            log.debug("Waiting for " + contextsStarted + " service dependency listener(s) to stop...");
        contextsStarted.waitForZero(extenderConfiguration.getShutdownWaitTime());
        if (!contextsStarted.isZero()) {
            if (debug)
                log.debug(contextsStarted.getValue() + " service dependency listener(s) did not responded in time; forcing them to shutdown...");
            extenderConfiguration.setForceThreadShutdown(true);
        } else
            log.debug("All listeners closed");
    }

    /**
     * Cancel any tasks scheduled for the timer.
     */
    private void stopTimer() {
        if (log.isDebugEnabled())
            log.debug("Canceling timer tasks");
        timer.cancel();
    }
}

19 View Source File : SpringAsyncExecutor.java
License : Apache License 2.0
Project Creator : dingziyang

/**
 * <p>
 * This is a spring based implementation of the {@link JobExecutor} using spring abstraction {@link TaskExecutor} for performing background task execution.
 * </p>
 * <p>
 * The idea behind this implementation is to externalize the configuration of the task executor, so it can leverage to Application servers controller thread pools, for example using the commonj API.
 * The use of unmanaged thread in application servers is discouraged by the Java EE spec.
 * </p>
 *
 * @author Pablo Ganga
 */
public clreplaced SpringAsyncExecutor extends DefaultAsyncJobExecutor {

    protected TaskExecutor taskExecutor;

    protected SpringRejectedJobsHandler rejectedJobsHandler;

    public SpringAsyncExecutor() {
    }

    public SpringAsyncExecutor(TaskExecutor taskExecutor, SpringRejectedJobsHandler rejectedJobsHandler) {
        this.taskExecutor = taskExecutor;
        this.rejectedJobsHandler = rejectedJobsHandler;
    }

    public TaskExecutor getTaskExecutor() {
        return taskExecutor;
    }

    /**
     * Required spring injected {@link TaskExecutor} implementation that will be used to execute runnable jobs.
     *
     * @param taskExecutor
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public SpringRejectedJobsHandler getRejectedJobsHandler() {
        return rejectedJobsHandler;
    }

    /**
     * Required spring injected {@link RejectedJobsHandler} implementation that will be used when jobs were rejected by the task executor.
     *
     * @param taskExecutor
     */
    public void setRejectedJobsHandler(SpringRejectedJobsHandler rejectedJobsHandler) {
        this.rejectedJobsHandler = rejectedJobsHandler;
    }

    @Override
    public boolean executeAsyncJob(Job job) {
        try {
            taskExecutor.execute(new ExecuteAsyncRunnable((JobEnreplacedy) job, processEngineConfiguration));
            return true;
        } catch (RejectedExecutionException e) {
            rejectedJobsHandler.jobRejected(this, job);
            return false;
        }
    }

    @Override
    protected void initAsyncJobExecutionThreadPool() {
    // Do nothing, using the Spring taskExecutor
    }
}

19 View Source File : SpringAsyncExecutor.java
License : Apache License 2.0
Project Creator : dingziyang

/**
 * Required spring injected {@link TaskExecutor} implementation that will be used to execute runnable jobs.
 *
 * @param taskExecutor
 */
public void setTaskExecutor(TaskExecutor taskExecutor) {
    this.taskExecutor = taskExecutor;
}

19 View Source File : FlinkAutoConfiguration.java
License : MIT License
Project Creator : btleedev

@Bean
FlinkExecutor flinkExecutor(ApplicationContext appCtx, TaskExecutor taskExecutor, FlinkProperties flinkProperties, StreamExecutionEnvironment flinkEnvironment) {
    return new FlinkExecutor(appCtx, taskExecutor, flinkProperties, flinkEnvironment);
}

18 View Source File : DefaultFlywayDataSourceContext.java
License : Apache License 2.0
Project Creator : zonkyio

/**
 * Default implementation of {@link FlywayDataSourceContext} that is used for deferred initialization of the embedded database.
 * Note that this target source is dynamic and supports hot reloading while the application is running.
 * <p/>
 * For the reloading of the underlying data source is used cacheable {@link DatabasePreparer},
 * which can utilize a special template database to effective copy data into multiple independent databases.
 *
 * @see io.zonky.test.db.postgres.FlywayEmbeddedPostgresDataSourceFactoryBean
 * @see OptimizedFlywayTestExecutionListener
 * @see <a href="https://www.postgresql.org/docs/9.6/static/manage-ag-templatedbs.html">Template Databases</a>
 */
public clreplaced DefaultFlywayDataSourceContext implements FlywayDataSourceContext {

    protected static final int DEFAULT_MAX_RETRY_ATTEMPTS = 2;

    protected static final ThreadLocal<DataSource> preparerDataSourceHolder = new ThreadLocal<>();

    protected volatile CompletableFuture<DataSource> dataSourceFuture = CompletableFuture.completedFuture(null);

    @Autowired
    protected GenericDatabaseProvider databaseProvider;

    protected DatabaseDescriptor databaseDescriptor;

    protected int maxAttempts = DEFAULT_MAX_RETRY_ATTEMPTS;

    protected TaskExecutor bootstrapExecutor;

    @Override
    public Clreplaced<?> getTargetClreplaced() {
        return DataSource.clreplaced;
    }

    @Override
    public boolean isStatic() {
        return false;
    }

    @Override
    public Object getTarget() throws Exception {
        DataSource threadBoundDataSource = preparerDataSourceHolder.get();
        if (threadBoundDataSource != null) {
            return threadBoundDataSource;
        }
        if (bootstrapExecutor == null && !dataSourceFuture.isDone()) {
            throw new IllegalStateException("dataSource is not initialized yet");
        }
        DataSource dataSource = dataSourceFuture.get();
        checkState(dataSource != null, "Unexpected error occurred while initializing the data source");
        return dataSource;
    }

    @Override
    public void releaseTarget(Object target) {
    // nothing to do
    }

    @Override
    public void setDescriptor(DatabaseDescriptor descriptor) {
        this.databaseDescriptor = descriptor;
    }

    @Override
    public synchronized ListenableFuture<DataSource> reload(Flyway flyway) {
        Executor executor = bootstrapExecutor != null ? bootstrapExecutor : Runnable::run;
        CompletableFuture<DataSource> reloadFuture = dataSourceFuture.thenApplyAsync(x -> {
            for (int current = 1; current <= maxAttempts; current++) {
                try {
                    FlywayDatabasePreparer databasePreparer = new FlywayDatabasePreparer(flyway);
                    return databaseProvider.getDatabase(databasePreparer, databaseDescriptor);
                } catch (Exception e) {
                    if (ExceptionUtils.indexOfType(e, IOException.clreplaced) == -1 || current == maxAttempts) {
                        throw new CompletionException(e);
                    }
                }
            }
            throw new IllegalStateException("maxAttempts parameter must be greater or equal to 1");
        }, executor);
        // main data source future must never fail, otherwise all following tests will fail
        dataSourceFuture = reloadFuture.exceptionally(throwable -> null);
        return new CompletableToListenableFutureAdapter<>(reloadFuture);
    }

    /**
     * Set the number of attempts for initialization of the embedded database.
     * Includes the initial attempt before the retries begin so, generally, will be {@code >= 1}.
     * For example setting this property to 3 means 3 attempts total (initial + 2 retries).
     *
     * @param maxAttempts the maximum number of attempts including the initial attempt.
     */
    public void setMaxAttempts(int maxAttempts) {
        this.maxAttempts = maxAttempts;
    }

    /**
     * Specify an asynchronous executor for background bootstrapping,
     * e.g. a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}.
     * <p>
     * {@code DataSource} initialization will then switch into background
     * bootstrap mode, with a {@code DataSource} proxy immediately returned for
     * injection purposes instead of waiting for the Flyway's bootstrapping to complete.
     * However, note that the first actual call to a {@code DataSource} method will
     * then block until the Flyway's bootstrapping completed, if not ready by then.
     * For maximum benefit, make sure to avoid early {@code DataSource} calls
     * in init methods of related beans.
     * <p>
     * Inspired by {@code org.springframework.orm.jpa.AbstractEnreplacedyManagerFactoryBean#setBootstrapExecutor}.
     */
    public void setBootstrapExecutor(TaskExecutor bootstrapExecutor) {
        this.bootstrapExecutor = bootstrapExecutor;
    }

    protected FlywayConfigSnapshot createConfigSnapshot(Flyway flyway) {
        return new FlywayConfigSnapshot(flyway);
    }

    protected clreplaced FlywayDatabasePreparer implements DatabasePreparer {

        private final FlywayConfigSnapshot configSnapshot;

        private final Flyway flyway;

        public FlywayDatabasePreparer(Flyway flyway) {
            this.configSnapshot = createConfigSnapshot(flyway);
            this.flyway = flyway;
        }

        @Override
        public void prepare(DataSource ds) {
            preparerDataSourceHolder.set(ds);
            try {
                // Return type changed in v7, breaking static call
                ReflectionUtils.invokeMethod(flyway, "migrate");
            } finally {
                preparerDataSourceHolder.remove();
            }
        }

        @Override
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClreplaced() != o.getClreplaced())
                return false;
            FlywayDatabasePreparer that = (FlywayDatabasePreparer) o;
            return Objects.equals(configSnapshot, that.configSnapshot);
        }

        @Override
        public int hashCode() {
            return Objects.hash(configSnapshot);
        }
    }
}

18 View Source File : SendMailHelper.java
License : MIT License
Project Creator : zhangjikai

/**
 * 用来发送邮件,使用了spring中的线程池,使用户在注册完之后不处于阻塞状态
 *
 * @author zhangjk
 */
@Component("sendMailHelper")
public clreplaced SendMailHelper {

    @Autowired
    private TaskExecutor taskExecutor;

    public void sendMail(User user, int sendType) {
        taskExecutor.execute(new SendThread(user, sendType));
    }

    private clreplaced SendThread implements Runnable {

        User user;

        int sendType;

        public SendThread(User user, int sendType) {
            this.user = user;
            this.sendType = sendType;
        }

        @Override
        public void run() {
            switch(sendType) {
                case Constants.SEND_ACTIVE_EMAIL:
                    MailUtil.sendAccountActiveEmail(user);
                    break;
                case Constants.SEND_RESETPS_EMAIL:
                    MailUtil.sendResetPreplacedwordEmail(user);
                    break;
                default:
                    MailUtil.sendAccountActiveEmail(user);
            }
        }
    }
}

18 View Source File : SysLogAop.java
License : Apache License 2.0
Project Creator : yanghaiji

/**
 * <p>
 * 日志记录Aop
 * </p>
 *
 * @author Dylan-haiji
 * @version 1.0.0
 * @since 2020-03-01 23:49
 */
@Slf4j
@Aspect
@Order(-1)
public clreplaced SysLogAop {

    private static final String YMDHMS = "yyyy-MM-dd HH:mm:ss";

    private volatile int size = 200;

    private static CopyOnWriteArrayList copyOnWriteArrayList = new CopyOnWriteArrayList();

    @Autowired
    private TaskExecutor taskExecutor;

    @Autowired(required = false)
    private LogError logError;

    @Around("@annotation(sysLog)")
    public Object getLog(ProceedingJoinPoint joinPoint, SysLog sysLog) throws Throwable {
        Object proceed = null;
        long time = System.currentTimeMillis();
        try {
            proceed = joinPoint.proceed();
            time = System.currentTimeMillis() - time;
            return proceed;
        } catch (Throwable throwable) {
            logError.logPrint("SysLogAop", throwable.getStackTrace());
            throw throwable;
        } finally {
            // 方法执行后
            addLogAspect(joinPoint, proceed, time);
        }
    }

    private void addLogAspect(ProceedingJoinPoint joinPoint, Object proceed, long time) {
        HttpServletRequest request = RequestUtils.getRequest();
        // 判断返回值是否为空
        if (!ObjectUtils.allNotNull()) {
        }
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        OperationLog operationLog = new OperationLog();
        // 消耗的时间
        operationLog.setRunTime(time);
        // UID
        operationLog.setId(RandomUtil.generateOrderCode());
        // 参数 防止参数中有不能序列化的对象 而报错
        Object[] args = joinPoint.getArgs();
        List<Object> params = new ArrayList<>();
        for (Object arg : args) {
            if (arg instanceof ServletRequest || arg instanceof ServletResponse || arg instanceof MultipartFile) {
                continue;
            }
            params.add(arg);
        }
        operationLog.setArgs(JsonUtils.beanToJson(params));
        // 创建时间
        operationLog.setCreateTime(DateFormatUtils.format(new Date(), YMDHMS));
        // 类名
        String clreplacedName = methodSignature.getDeclaringTypeName() + "." + methodSignature.getName();
        operationLog.setMethod(clreplacedName);
        // 获取注解
        SysLog annotation = methodSignature.getMethod().getAnnotation(SysLog.clreplaced);
        if (annotation != null) {
            // 描述
            operationLog.setDescribe(annotation.detail());
            // 等级
            operationLog.setLevel(annotation.level());
            // 调用方ip
            operationLog.setCallerIp(request.getRemoteAddr());
            // 本地ip
            operationLog.setLocalHostIp(IPUtils.getHostIp());
            // 获取当前用户信息 TODO
            operationLog.setUserId("1234");
            operationLog.setUserName("javayh");
            operationLog.setMode(annotation.value());
            // 判断是否持久化
            boolean requestParam = annotation.recordRequestParam();
            save(requestParam, operationLog, clreplacedName, time);
        }
    }

    /**
     * <p>
     *      持久化操作
     * </p>
     * @version 1.0.0
     * @author Dylan
     * @since 2020/4/16
     * @param requestParam	标识
     * @param operationLog	内容
     * @param clreplacedName		类名
     * @return void
     */
    private void save(boolean requestParam, OperationLog operationLog, String clreplacedName, long time) {
        // copyOnWriteArrayList.add(operationLog);
        // FIXME: 2020/4/17
        StringBuilder sb = new StringBuilder();
        if (requestParam && copyOnWriteArrayList.size() >= size) {
            // 进行日志的保存
            CompletableFuture.runAsync(() -> {
                try {
                    log.trace("日志落库开始:{}", operationLog);
                    // 持久化
                    log.trace("开始落库结束:{}", operationLog);
                } catch (Exception e) {
                    logError.logPrint("落库失败:{}", e.getStackTrace());
                }
            }, taskExecutor);
        } else {
            sb.append(ConstantUtils.NEWLINE).append(ConstantUtils.PREFIX).append(clreplacedName).append("-> 执行耗时: ").append(time).append("s");
            sb.append(ConstantUtils.NEWLINE).append(ConstantUtils.PREFIX).append("操作记录:").append(operationLog);
            log.info(sb.toString());
        }
    }
}

18 View Source File : Log.java
License : Apache License 2.0
Project Creator : yanghaiji

/**
 * <p>
 * 		Log记录
 * </p>
 *
 * @author Dylan-haiji
 * @version 1.0.0
 * @since 2020-04-01 21:53
 */
@Slf4j
public clreplaced Log {

    @Autowired(required = false)
    private static TaskExecutor taskExecutor = SpringUtils.getBean("taskExecutor", TaskExecutor.clreplaced);

    /**
     * <p>
     * 统一日志输出
     * </p>
     * @version 1.0.0
     * @author Dylan-haiji
     * @since 2020/2/28
     * @param
     * @param stackTrace
     * @return void
     */
    public static void error(String pr, StackTraceElement[] stackTrace) {
        HttpServletRequest request = RequestUtils.getRequest();
        StringBuilder sb = new StringBuilder();
        String requestUri = request.getRequestURI();
        sb.append(ConstantUtils.NEWLINE).append(ConstantUtils.PREFIX).append(pr).append("异常 method -->").append(request.getMethod());
        sb.append(ConstantUtils.NEWLINE).append(ConstantUtils.PREFIX).append(pr).append("异常 requestURI -->").append(requestUri);
        CompletableFuture.runAsync(() -> {
            for (int depth = 1, count = 0; depth < stackTrace.length; ++depth) {
                sb.append(ConstantUtils.NEWLINE).append(ConstantUtils.PREFIX).append(pr).append(" -->").append(stackTrace[depth]);
                if (count == ConstantUtils.MAX_STACK_DEPTH) {
                    break;
                }
                count++;
            }
            log.error(sb.toString());
        }, taskExecutor);
    }
}

18 View Source File : RestTemplateXhrTransport.java
License : MIT License
Project Creator : Vip-Augus

/**
 * An {@code XhrTransport} implementation that uses a
 * {@link org.springframework.web.client.RestTemplate RestTemplate}.
 *
 * @author Rossen Stoyanchev
 * @since 4.1
 */
public clreplaced RestTemplateXhrTransport extends AbstractXhrTransport {

    private final RestOperations restTemplate;

    private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    public RestTemplateXhrTransport() {
        this(new RestTemplate());
    }

    public RestTemplateXhrTransport(RestOperations restTemplate) {
        replacedert.notNull(restTemplate, "'restTemplate' is required");
        this.restTemplate = restTemplate;
    }

    /**
     * Return the configured {@code RestTemplate}.
     */
    public RestOperations getRestTemplate() {
        return this.restTemplate;
    }

    /**
     * Configure the {@code TaskExecutor} to use to execute XHR receive requests.
     * <p>By default {@link org.springframework.core.task.SimpleAsyncTaskExecutor
     * SimpleAsyncTaskExecutor} is configured which creates a new thread every
     * time the transports connects.
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
        this.taskExecutor = taskExecutor;
    }

    /**
     * Return the configured {@code TaskExecutor}.
     */
    public TaskExecutor getTaskExecutor() {
        return this.taskExecutor;
    }

    @Override
    protected void connectInternal(final TransportRequest transportRequest, final WebSocketHandler handler, final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, final SettableListenableFuture<WebSocketSession> connectFuture) {
        getTaskExecutor().execute(() -> {
            HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
            XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders);
            XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders);
            XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session);
            while (true) {
                if (session.isDisconnected()) {
                    session.afterTransportClosed(null);
                    break;
                }
                try {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Starting XHR receive request, url=" + receiveUrl);
                    }
                    getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
                    requestCallback = requestCallbackAfterHandshake;
                } catch (Throwable ex) {
                    if (!connectFuture.isDone()) {
                        connectFuture.setException(ex);
                    } else {
                        session.handleTransportError(ex);
                        session.afterTransportClosed(new CloseStatus(1006, ex.getMessage()));
                    }
                    break;
                }
            }
        });
    }

    @Override
    protected ResponseEnreplacedy<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) {
        RequestCallback requestCallback = new XhrRequestCallback(headers);
        return nonNull(this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor));
    }

    @Override
    public ResponseEnreplacedy<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message) {
        RequestCallback requestCallback = new XhrRequestCallback(headers, message.getPayload());
        return nonNull(this.restTemplate.execute(url, HttpMethod.POST, requestCallback, textResponseExtractor));
    }

    private static <T> T nonNull(@Nullable T result) {
        replacedert.state(result != null, "No result");
        return result;
    }

    /**
     * A simple ResponseExtractor that reads the body into a String.
     */
    private static final ResponseExtractor<ResponseEnreplacedy<String>> textResponseExtractor = response -> {
        String body = StreamUtils.copyToString(response.getBody(), SockJsFrame.CHARSET);
        return ResponseEnreplacedy.status(response.getRawStatusCode()).headers(response.getHeaders()).body(body);
    };

    /**
     * A RequestCallback to add the headers and (optionally) String content.
     */
    private static clreplaced XhrRequestCallback implements RequestCallback {

        private final HttpHeaders headers;

        @Nullable
        private final String body;

        public XhrRequestCallback(HttpHeaders headers) {
            this(headers, null);
        }

        public XhrRequestCallback(HttpHeaders headers, @Nullable String body) {
            this.headers = headers;
            this.body = body;
        }

        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            request.getHeaders().putAll(this.headers);
            if (this.body != null) {
                StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody());
            }
        }
    }

    /**
     * Splits the body of an HTTP response into SockJS frames and delegates those
     * to an {@link XhrClientSockJsSession}.
     */
    private clreplaced XhrReceiveExtractor implements ResponseExtractor<Object> {

        private final XhrClientSockJsSession sockJsSession;

        public XhrReceiveExtractor(XhrClientSockJsSession sockJsSession) {
            this.sockJsSession = sockJsSession;
        }

        @Override
        public Object extractData(ClientHttpResponse response) throws IOException {
            HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
            if (httpStatus == null) {
                throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
            }
            if (httpStatus != HttpStatus.OK) {
                throw new HttpServerErrorException(httpStatus, response.getStatusText(), response.getHeaders(), null, null);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive headers: " + response.getHeaders());
            }
            InputStream is = response.getBody();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            while (true) {
                if (this.sockJsSession.isDisconnected()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("SockJS sockJsSession closed, closing response.");
                    }
                    response.close();
                    break;
                }
                int b = is.read();
                if (b == -1) {
                    if (os.size() > 0) {
                        handleFrame(os);
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("XHR receive completed");
                    }
                    break;
                }
                if (b == '\n') {
                    handleFrame(os);
                } else {
                    os.write(b);
                }
            }
            return null;
        }

        private void handleFrame(ByteArrayOutputStream os) {
            byte[] bytes = os.toByteArray();
            os.reset();
            String content = new String(bytes, SockJsFrame.CHARSET);
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive content: " + content);
            }
            if (!PRELUDE.equals(content)) {
                this.sockJsSession.handleFrame(new String(bytes, SockJsFrame.CHARSET));
            }
        }
    }
}

18 View Source File : EndpointConnectionManager.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Set a {@link TaskExecutor} to use to open connections.
 * By default {@link SimpleAsyncTaskExecutor} is used.
 */
public void setTaskExecutor(TaskExecutor taskExecutor) {
    replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
    this.taskExecutor = taskExecutor;
}

18 View Source File : SimpleTaskWorkManager.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Simple JCA 1.7 {@link javax.resource.spi.work.WorkManager} implementation that
 * delegates to a Spring {@link org.springframework.core.task.TaskExecutor}.
 * Provides simple task execution including start timeouts, but without support
 * for a JCA ExecutionContext (i.e. without support for imported transactions).
 *
 * <p>Uses a {@link org.springframework.core.task.SyncTaskExecutor} for {@link #doWork}
 * calls and a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}
 * for {@link #startWork} and {@link #scheduleWork} calls, by default.
 * These default task executors can be overridden through configuration.
 *
 * <p><b>NOTE: This WorkManager does not provide thread pooling by default!</b>
 * Specify a {@link org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor}
 * (or any other thread-pooling TaskExecutor) as "asyncTaskExecutor" in order to
 * achieve actual thread pooling.
 *
 * <p>This WorkManager automatically detects a specified
 * {@link org.springframework.core.task.AsyncTaskExecutor} implementation
 * and uses its extended timeout functionality where appropriate.
 * JCA WorkListeners are fully supported in any case.
 *
 * @author Juergen Hoeller
 * @since 2.0.3
 * @see #setSyncTaskExecutor
 * @see #setAsyncTaskExecutor
 */
public clreplaced SimpleTaskWorkManager implements WorkManager {

    @Nullable
    private TaskExecutor syncTaskExecutor = new SyncTaskExecutor();

    @Nullable
    private AsyncTaskExecutor asyncTaskExecutor = new SimpleAsyncTaskExecutor();

    /**
     * Specify the TaskExecutor to use for <i>synchronous</i> work execution
     * (i.e. {@link #doWork} calls).
     * <p>Default is a {@link org.springframework.core.task.SyncTaskExecutor}.
     */
    public void setSyncTaskExecutor(TaskExecutor syncTaskExecutor) {
        this.syncTaskExecutor = syncTaskExecutor;
    }

    /**
     * Specify the TaskExecutor to use for <i>asynchronous</i> work execution
     * (i.e. {@link #startWork} and {@link #scheduleWork} calls).
     * <p>This will typically (but not necessarily) be an
     * {@link org.springframework.core.task.AsyncTaskExecutor} implementation.
     * Default is a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}.
     */
    public void setAsyncTaskExecutor(AsyncTaskExecutor asyncTaskExecutor) {
        this.asyncTaskExecutor = asyncTaskExecutor;
    }

    @Override
    public void doWork(Work work) throws WorkException {
        doWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public void doWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener) throws WorkException {
        replacedert.state(this.syncTaskExecutor != null, "No 'syncTaskExecutor' set");
        executeWork(this.syncTaskExecutor, work, startTimeout, false, executionContext, workListener);
    }

    @Override
    public long startWork(Work work) throws WorkException {
        return startWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public long startWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener) throws WorkException {
        replacedert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
        return executeWork(this.asyncTaskExecutor, work, startTimeout, true, executionContext, workListener);
    }

    @Override
    public void scheduleWork(Work work) throws WorkException {
        scheduleWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public void scheduleWork(Work work, long startTimeout, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener) throws WorkException {
        replacedert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
        executeWork(this.asyncTaskExecutor, work, startTimeout, false, executionContext, workListener);
    }

    /**
     * Execute the given Work on the specified TaskExecutor.
     * @param taskExecutor the TaskExecutor to use
     * @param work the Work to execute
     * @param startTimeout the time duration within which the Work is supposed to start
     * @param blockUntilStarted whether to block until the Work has started
     * @param executionContext the JCA ExecutionContext for the given Work
     * @param workListener the WorkListener to clal for the given Work
     * @return the time elapsed from Work acceptance until start of execution
     * (or -1 if not applicable or not known)
     * @throws WorkException if the TaskExecutor did not accept the Work
     */
    protected long executeWork(TaskExecutor taskExecutor, Work work, long startTimeout, boolean blockUntilStarted, @Nullable ExecutionContext executionContext, @Nullable WorkListener workListener) throws WorkException {
        if (executionContext != null && executionContext.getXid() != null) {
            throw new WorkException("SimpleTaskWorkManager does not supported imported XIDs: " + executionContext.getXid());
        }
        WorkListener workListenerToUse = workListener;
        if (workListenerToUse == null) {
            workListenerToUse = new WorkAdapter();
        }
        boolean isAsync = (taskExecutor instanceof AsyncTaskExecutor);
        DelegatingWorkAdapter workHandle = new DelegatingWorkAdapter(work, workListenerToUse, !isAsync);
        try {
            if (isAsync) {
                ((AsyncTaskExecutor) taskExecutor).execute(workHandle, startTimeout);
            } else {
                taskExecutor.execute(workHandle);
            }
        } catch (TaskTimeoutException ex) {
            WorkException wex = new WorkRejectedException("TaskExecutor rejected Work because of timeout: " + work, ex);
            wex.setErrorCode(WorkException.START_TIMED_OUT);
            workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
            throw wex;
        } catch (TaskRejectedException ex) {
            WorkException wex = new WorkRejectedException("TaskExecutor rejected Work: " + work, ex);
            wex.setErrorCode(WorkException.INTERNAL);
            workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
            throw wex;
        } catch (Throwable ex) {
            WorkException wex = new WorkException("TaskExecutor failed to execute Work: " + work, ex);
            wex.setErrorCode(WorkException.INTERNAL);
            throw wex;
        }
        if (isAsync) {
            workListenerToUse.workAccepted(new WorkEvent(this, WorkEvent.WORK_ACCEPTED, work, null));
        }
        if (blockUntilStarted) {
            long acceptanceTime = System.currentTimeMillis();
            synchronized (workHandle.monitor) {
                try {
                    while (!workHandle.started) {
                        workHandle.monitor.wait();
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
            return (System.currentTimeMillis() - acceptanceTime);
        } else {
            return WorkManager.UNKNOWN;
        }
    }

    /**
     * Work adapter that supports start timeouts and WorkListener callbacks
     * for a given Work that it delegates to.
     */
    private static clreplaced DelegatingWorkAdapter implements Work {

        private final Work work;

        private final WorkListener workListener;

        private final boolean acceptOnExecution;

        public final Object monitor = new Object();

        public boolean started = false;

        public DelegatingWorkAdapter(Work work, WorkListener workListener, boolean acceptOnExecution) {
            this.work = work;
            this.workListener = workListener;
            this.acceptOnExecution = acceptOnExecution;
        }

        @Override
        public void run() {
            if (this.acceptOnExecution) {
                this.workListener.workAccepted(new WorkEvent(this, WorkEvent.WORK_ACCEPTED, this.work, null));
            }
            synchronized (this.monitor) {
                this.started = true;
                this.monitor.notify();
            }
            this.workListener.workStarted(new WorkEvent(this, WorkEvent.WORK_STARTED, this.work, null));
            try {
                this.work.run();
            } catch (RuntimeException | Error ex) {
                this.workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, this.work, new WorkCompletedException(ex)));
                throw ex;
            }
            this.workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, this.work, null));
        }

        @Override
        public void release() {
            this.work.release();
        }
    }
}

18 View Source File : ExecutorSubscribableChannelTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void sendWithExecutor() {
    BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
    TaskExecutor executor = mock(TaskExecutor.clreplaced);
    ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
    testChannel.addInterceptor(interceptor);
    testChannel.subscribe(this.handler);
    testChannel.send(this.message);
    verify(executor).execute(this.runnableCaptor.capture());
    verify(this.handler, never()).handleMessage(this.message);
    this.runnableCaptor.getValue().run();
    verify(this.handler).handleMessage(this.message);
    replacedertEquals(1, interceptor.getCounter().get());
    replacedertTrue(interceptor.wasAfterHandledInvoked());
}

18 View Source File : ProcessTailInboundChannelAdapterFactoryBean.java
License : MIT License
Project Creator : Toparvion

/**
 * @author Gary Russell
 * @author Artem Bilan
 * @author Ali Shahbour
 * @author Vladimir Plizga
 * @since 3.0
 */
public clreplaced ProcessTailInboundChannelAdapterFactoryBean extends AbstractFactoryBean<FileTailingMessageProducerSupport> implements BeanNameAware, SmartLifecycle, ApplicationEventPublisherAware {

    private volatile String nativeOptions;

    private volatile boolean enableStatusReader = true;

    private volatile Long idleEventInterval;

    private volatile String executbale;

    private volatile File file;

    private volatile TaskExecutor taskExecutor;

    private volatile TaskScheduler taskScheduler;

    private volatile Long fileDelay;

    private volatile FileTailingMessageProducerSupport adapter;

    private volatile String beanName;

    private volatile MessageChannel outputChannel;

    private volatile MessageChannel errorChannel;

    private volatile Boolean autoStartup;

    private volatile Integer phase;

    private volatile ApplicationEventPublisher applicationEventPublisher;

    public void setNativeOptions(String nativeOptions) {
        if (StringUtils.hasText(nativeOptions)) {
            this.nativeOptions = nativeOptions;
        }
    }

    /**
     * If false, thread for capturing stderr will not be started
     * and stderr output will be ignored
     *
     * @param enableStatusReader true or false
     * @since 4.3.6
     */
    public void setEnableStatusReader(boolean enableStatusReader) {
        this.enableStatusReader = enableStatusReader;
    }

    /**
     * How often to emit {@link FileTailingMessageProducerSupport.FileTailingIdleEvent}s in milliseconds.
     *
     * @param idleEventInterval the interval.
     * @since 5.0
     */
    public void setIdleEventInterval(long idleEventInterval) {
        this.idleEventInterval = idleEventInterval;
    }

    public void setTaskExecutor(TaskExecutor taskExecutor) {
        this.taskExecutor = taskExecutor;
    }

    public void setTaskScheduler(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    public void setFileDelay(Long fileDelay) {
        this.fileDelay = fileDelay;
    }

    public void setFile(File file) {
        this.file = file;
    }

    @Override
    public void setBeanName(String name) {
        this.beanName = name;
    }

    public void setOutputChannel(MessageChannel outputChannel) {
        this.outputChannel = outputChannel;
    }

    public void setErrorChannel(MessageChannel errorChannel) {
        this.errorChannel = errorChannel;
    }

    public void setAutoStartup(boolean autoStartup) {
        this.autoStartup = autoStartup;
    }

    public void setPhase(int phase) {
        this.phase = phase;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @Override
    public void start() {
        if (this.adapter != null) {
            this.adapter.start();
        }
    }

    @Override
    public void stop() {
        if (this.adapter != null) {
            this.adapter.stop();
        }
    }

    @Override
    public boolean isRunning() {
        return this.adapter != null && this.adapter.isRunning();
    }

    @Override
    public int getPhase() {
        if (this.adapter != null) {
            return this.adapter.getPhase();
        }
        return 0;
    }

    @Override
    public boolean isAutoStartup() {
        return this.adapter != null && this.adapter.isAutoStartup();
    }

    @Override
    public void stop(Runnable callback) {
        if (this.adapter != null) {
            this.adapter.stop(callback);
        } else {
            callback.run();
        }
    }

    @Override
    public Clreplaced<?> getObjectType() {
        return this.adapter == null ? FileTailingMessageProducerSupport.clreplaced : this.adapter.getClreplaced();
    }

    @Override
    protected FileTailingMessageProducerSupport createInstance() throws Exception {
        ProcessTailMessageProducer adapter = new ProcessTailMessageProducer();
        adapter.setOptions(this.nativeOptions);
        adapter.setEnableStatusReader(this.enableStatusReader);
        adapter.setFile(this.file);
        adapter.setExecutable(this.executbale);
        if (this.taskExecutor != null) {
            adapter.setTaskExecutor(this.taskExecutor);
        }
        if (this.taskScheduler != null) {
            adapter.setTaskScheduler(this.taskScheduler);
        }
        if (this.fileDelay != null) {
            adapter.setTailAttemptsDelay(this.fileDelay);
        }
        if (this.idleEventInterval != null) {
            adapter.setIdleEventInterval(this.idleEventInterval);
        }
        adapter.setOutputChannel(this.outputChannel);
        adapter.setErrorChannel(this.errorChannel);
        adapter.setBeanName(this.beanName);
        if (this.autoStartup != null) {
            adapter.setAutoStartup(this.autoStartup);
        }
        if (this.phase != null) {
            adapter.setPhase(this.phase);
        }
        if (this.applicationEventPublisher != null) {
            adapter.setApplicationEventPublisher(this.applicationEventPublisher);
        }
        if (getBeanFactory() != null) {
            adapter.setBeanFactory(getBeanFactory());
        }
        adapter.afterPropertiesSet();
        this.adapter = adapter;
        return adapter;
    }

    public void setExecutbale(String executbale) {
        this.executbale = executbale;
    }
}

18 View Source File : WebSocketServlet.java
License : GNU General Public License v2.0
Project Creator : taktik

@Autowired
public void setWsExecutor(TaskExecutor wsExecutor) {
    this.wsExecutor = wsExecutor;
}

18 View Source File : RestTemplateXhrTransport.java
License : Apache License 2.0
Project Creator : SourceHot

/**
 * An {@code XhrTransport} implementation that uses a
 * {@link org.springframework.web.client.RestTemplate RestTemplate}.
 *
 * @author Rossen Stoyanchev
 * @since 4.1
 */
public clreplaced RestTemplateXhrTransport extends AbstractXhrTransport {

    private final RestOperations restTemplate;

    private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    public RestTemplateXhrTransport() {
        this(new RestTemplate());
    }

    public RestTemplateXhrTransport(RestOperations restTemplate) {
        replacedert.notNull(restTemplate, "'restTemplate' is required");
        this.restTemplate = restTemplate;
    }

    /**
     * Return the configured {@code RestTemplate}.
     */
    public RestOperations getRestTemplate() {
        return this.restTemplate;
    }

    /**
     * Configure the {@code TaskExecutor} to use to execute XHR receive requests.
     * <p>By default {@link org.springframework.core.task.SimpleAsyncTaskExecutor
     * SimpleAsyncTaskExecutor} is configured which creates a new thread every
     * time the transports connects.
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        replacedert.notNull(taskExecutor, "TaskExecutor must not be null");
        this.taskExecutor = taskExecutor;
    }

    /**
     * Return the configured {@code TaskExecutor}.
     */
    public TaskExecutor getTaskExecutor() {
        return this.taskExecutor;
    }

    @Override
    protected void connectInternal(final TransportRequest transportRequest, final WebSocketHandler handler, final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, final SettableListenableFuture<WebSocketSession> connectFuture) {
        getTaskExecutor().execute(() -> {
            HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
            XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders);
            XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders);
            XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session);
            while (true) {
                if (session.isDisconnected()) {
                    session.afterTransportClosed(null);
                    break;
                }
                try {
                    if (logger.isTraceEnabled()) {
                        logger.trace("Starting XHR receive request, url=" + receiveUrl);
                    }
                    getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
                    requestCallback = requestCallbackAfterHandshake;
                } catch (Exception ex) {
                    if (!connectFuture.isDone()) {
                        connectFuture.setException(ex);
                    } else {
                        session.handleTransportError(ex);
                        session.afterTransportClosed(new CloseStatus(1006, ex.getMessage()));
                    }
                    break;
                }
            }
        });
    }

    @Override
    protected ResponseEnreplacedy<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) {
        RequestCallback requestCallback = new XhrRequestCallback(headers);
        return nonNull(this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor));
    }

    @Override
    public ResponseEnreplacedy<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message) {
        RequestCallback requestCallback = new XhrRequestCallback(headers, message.getPayload());
        return nonNull(this.restTemplate.execute(url, HttpMethod.POST, requestCallback, textResponseExtractor));
    }

    private static <T> T nonNull(@Nullable T result) {
        replacedert.state(result != null, "No result");
        return result;
    }

    /**
     * A simple ResponseExtractor that reads the body into a String.
     */
    private static final ResponseExtractor<ResponseEnreplacedy<String>> textResponseExtractor = response -> {
        String body = StreamUtils.copyToString(response.getBody(), SockJsFrame.CHARSET);
        return ResponseEnreplacedy.status(response.getRawStatusCode()).headers(response.getHeaders()).body(body);
    };

    /**
     * A RequestCallback to add the headers and (optionally) String content.
     */
    private static clreplaced XhrRequestCallback implements RequestCallback {

        private final HttpHeaders headers;

        @Nullable
        private final String body;

        public XhrRequestCallback(HttpHeaders headers) {
            this(headers, null);
        }

        public XhrRequestCallback(HttpHeaders headers, @Nullable String body) {
            this.headers = headers;
            this.body = body;
        }

        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            request.getHeaders().putAll(this.headers);
            if (this.body != null) {
                if (request instanceof StreamingHttpOutputMessage) {
                    ((StreamingHttpOutputMessage) request).setBody(outputStream -> StreamUtils.copy(this.body, SockJsFrame.CHARSET, outputStream));
                } else {
                    StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody());
                }
            }
        }
    }

    /**
     * Splits the body of an HTTP response into SockJS frames and delegates those
     * to an {@link XhrClientSockJsSession}.
     */
    private clreplaced XhrReceiveExtractor implements ResponseExtractor<Object> {

        private final XhrClientSockJsSession sockJsSession;

        public XhrReceiveExtractor(XhrClientSockJsSession sockJsSession) {
            this.sockJsSession = sockJsSession;
        }

        @Override
        public Object extractData(ClientHttpResponse response) throws IOException {
            HttpStatus httpStatus = HttpStatus.resolve(response.getRawStatusCode());
            if (httpStatus == null) {
                throw new UnknownHttpStatusCodeException(response.getRawStatusCode(), response.getStatusText(), response.getHeaders(), null, null);
            }
            if (httpStatus != HttpStatus.OK) {
                throw new HttpServerErrorException(httpStatus, response.getStatusText(), response.getHeaders(), null, null);
            }
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive headers: " + response.getHeaders());
            }
            InputStream is = response.getBody();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            while (true) {
                if (this.sockJsSession.isDisconnected()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("SockJS sockJsSession closed, closing response.");
                    }
                    response.close();
                    break;
                }
                int b = is.read();
                if (b == -1) {
                    if (os.size() > 0) {
                        handleFrame(os);
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("XHR receive completed");
                    }
                    break;
                }
                if (b == '\n') {
                    handleFrame(os);
                } else {
                    os.write(b);
                }
            }
            return null;
        }

        private void handleFrame(ByteArrayOutputStream os) {
            byte[] bytes = os.toByteArray();
            os.reset();
            String content = new String(bytes, SockJsFrame.CHARSET);
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive content: " + content);
            }
            if (!PRELUDE.equals(content)) {
                this.sockJsSession.handleFrame(new String(bytes, SockJsFrame.CHARSET));
            }
        }
    }
}

18 View Source File : ExecutorSubscribableChannelTests.java
License : Apache License 2.0
Project Creator : SourceHot

@Test
public void sendWithExecutor() {
    BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
    TaskExecutor executor = mock(TaskExecutor.clreplaced);
    ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
    testChannel.addInterceptor(interceptor);
    testChannel.subscribe(this.handler);
    testChannel.send(this.message);
    verify(executor).execute(this.runnableCaptor.capture());
    verify(this.handler, never()).handleMessage(this.message);
    this.runnableCaptor.getValue().run();
    verify(this.handler).handleMessage(this.message);
    replacedertThat(interceptor.getCounter().get()).isEqualTo(1);
    replacedertThat(interceptor.wasAfterHandledInvoked()).isTrue();
}

18 View Source File : MailServiceImpl.java
License : GNU General Public License v3.0
Project Creator : qiushi123

/**
 * @author : langhsu
 */
@Slf4j
@Service
public clreplaced MailServiceImpl implements MailService {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private SiteOptions siteOptions;

    @Autowired
    private TaskExecutor taskExecutor;

    @Override
    public void config() {
        String mailHost = siteOptions.getValue("mail_smtp_host");
        String mailUsername = siteOptions.getValue("mail_smtp_username");
        String mailPreplacedowrd = siteOptions.getValue("mail_smtp_preplacedword");
        if (StringUtils.isNoneBlank(mailHost, mailUsername, mailPreplacedowrd)) {
            final Properties properties = OhMyEmail.defaultConfig(false);
            properties.setProperty("mail.smtp.host", mailHost);
            OhMyEmail.config(properties, mailUsername, mailPreplacedowrd);
        } else {
            log.error("邮件服务配置信息未设置, 请在后台系统配置中进行设置");
        }
    }

    @Override
    public void sendTemplateEmail(String to, String replacedle, String template, Map<String, Object> content) {
        String text = render(template, content);
        String from = siteOptions.getValue("site_name");
        taskExecutor.execute(() -> {
            try {
                OhMyEmail.subject(replacedle).from(from).to(to).html(text).send();
            } catch (SendMailException e) {
                log.error(e.getMessage(), e);
            }
            log.info("email: {} send success", to);
        });
    }

    private String render(String templateName, Map<String, Object> model) {
        try {
            Template t = freeMarkerConfigurer.getConfiguration().getTemplate(templateName, "UTF-8");
            t.setOutputEncoding("UTF-8");
            return FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
        } catch (Exception e) {
            throw new MtonsException(e.getMessage(), e);
        }
    }
}

18 View Source File : MdcExceptionLogServiceImpl.java
License : Apache License 2.0
Project Creator : paascloud

/**
 * The clreplaced Mdc exception log service.
 *
 * @author paascloud.net @gmail.com
 */
@Service
public clreplaced MdcExceptionLogServiceImpl extends BaseService<MdcExceptionLog> implements MdcExceptionLogService {

    @Resource
    private MdcExceptionLogMapper mdcExceptionLogMapper;

    @Resource
    private TaskExecutor taskExecutor;

    @Resource
    private OpcRpcService opcRpcService;

    @Value("${paascloud.dingTalk.webhookToken.sendException}")
    private String webhookToken;

    @Override
    public void saveAndSendExceptionLog(final GlobalExceptionLogDto exceptionLogDto) {
        MdcExceptionLog exceptionLog = new ModelMapper().map(exceptionLogDto, MdcExceptionLog.clreplaced);
        exceptionLog.setId(generateId());
        exceptionLog.setCreateTime(new Date());
        mdcExceptionLogMapper.insertSelective(exceptionLog);
        taskExecutor.execute(() -> {
            if (judgeIsSend(exceptionLogDto.getProfile())) {
                String text = exceptionLog.getApplicationName() + "出现异常. 环境:" + exceptionLogDto.getProfile() + ",操作人:" + exceptionLogDto.getCreator() + ".异常类型:" + exceptionLogDto.getExceptionSimpleName();
                ChatRobotMsgDto chatRobotMsgDto = ChatRobotMsgFactory.createChatRobotTextMsg(webhookToken, text, false, null);
                opcRpcService.sendChatRobotMsg(chatRobotMsgDto);
            }
        });
    }

    @Override
    public PageInfo queryExceptionListWithPage(final MdcExceptionQueryDto mdcExceptionQueryDto) {
        PageHelper.startPage(mdcExceptionQueryDto.getPageNum(), mdcExceptionQueryDto.getPageSize());
        List<MdcExceptionLog> actionList = mdcExceptionLogMapper.queryExceptionListWithPage(mdcExceptionQueryDto);
        return new PageInfo<>(actionList);
    }

    private boolean judgeIsSend(String profile) {
        Calendar calendar = Calendar.getInstance();
        int time = calendar.get(Calendar.HOUR_OF_DAY);
        return GlobalConstant.PRO_PROFILE.equals(profile) || time >= 10 && time <= 18;
    }
}

18 View Source File : RequestDispatcher.java
License : MIT License
Project Creator : OlegNyr

public clreplaced RequestDispatcher {

    private static final Logger logger = LoggerFactory.getLogger(RequestDispatcher.clreplaced);

    private final HandlerMethodContainer handlerMethodContainer;

    private final HandlerAdapter handlerAdapter;

    private final TaskExecutor taskExecutor;

    @Autowired
    private TelegramSession telegramSession;

    public RequestDispatcher(HandlerMethodContainer handlerMethodContainer, HandlerAdapter handlerAdapter, TaskExecutor taskExecutor) {
        this.handlerMethodContainer = handlerMethodContainer;
        this.handlerAdapter = handlerAdapter;
        this.taskExecutor = taskExecutor;
    }

    /**
     * Находит обработчик запроса пользователя и вызывает его, далее передает в телеграмм ответ обработчика
     * @param update Запрос пользователя
     * @param telegramBot какой бот принял запрос
     */
    public void execute(Update update, TelegramBot telegramBot) {
        taskExecutor.execute(() -> {
            TelegramRequest telegramRequest = new TelegramRequest(update, telegramBot);
            HandlerMethod handlerMethod = handlerMethodContainer.lookupHandlerMethod(telegramRequest);
            if (handlerMethod == null) {
                logger.error("Not found controller for {} type {}", telegramRequest.getText(), telegramRequest.getMessageType());
            }
            TelegramScope.setIdThreadLocal(telegramRequest.chatId());
            telegramRequest.setSession(telegramSession);
            BaseRequest baseRequest = null;
            try {
                baseRequest = handlerAdapter.handle(telegramRequest, handlerMethod);
                if (baseRequest != null) {
                    logger.debug("Request {}", baseRequest);
                    telegramBot.execute(baseRequest, new Callback<BaseRequest, BaseResponse>() {

                        @Override
                        public void onResponse(BaseRequest request, BaseResponse response) {
                            telegramRequest.complete(response);
                        }

                        @Override
                        public void onFailure(BaseRequest request, IOException e) {
                            logger.error("Send request callback {}", telegramRequest.chatId(), e);
                            telegramRequest.error(e);
                        }
                    });
                    TelegramScope.removeId();
                } else {
                    telegramRequest.complete(null);
                    logger.debug("handlerAdapter return null");
                }
            } catch (Exception e) {
                telegramRequest.error(e);
                logger.info("Execute error handlerAdapter {}", handlerAdapter, e);
            }
        });
    }
}

18 View Source File : RestTemplateXhrTransport.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * An {@code XhrTransport} implementation that uses a
 * {@link org.springframework.web.client.RestTemplate RestTemplate}.
 *
 * @author Rossen Stoyanchev
 * @since 4.1
 */
public clreplaced RestTemplateXhrTransport extends AbstractXhrTransport {

    private final RestOperations restTemplate;

    private TaskExecutor taskExecutor = new SimpleAsyncTaskExecutor();

    public RestTemplateXhrTransport() {
        this(new RestTemplate());
    }

    public RestTemplateXhrTransport(RestOperations restTemplate) {
        replacedert.notNull(restTemplate, "'restTemplate' is required");
        this.restTemplate = restTemplate;
    }

    /**
     * Return the configured {@code RestTemplate}.
     */
    public RestOperations getRestTemplate() {
        return this.restTemplate;
    }

    /**
     * Configure the {@code TaskExecutor} to use to execute XHR receive requests.
     * <p>By default {@link org.springframework.core.task.SimpleAsyncTaskExecutor
     * SimpleAsyncTaskExecutor} is configured which creates a new thread every
     * time the transports connects.
     */
    public void setTaskExecutor(TaskExecutor taskExecutor) {
        replacedert.notNull(this.taskExecutor);
        this.taskExecutor = taskExecutor;
    }

    /**
     * Return the configured {@code TaskExecutor}.
     */
    public TaskExecutor getTaskExecutor() {
        return this.taskExecutor;
    }

    @Override
    protected void connectInternal(final TransportRequest transportRequest, final WebSocketHandler handler, final URI receiveUrl, final HttpHeaders handshakeHeaders, final XhrClientSockJsSession session, final SettableListenableFuture<WebSocketSession> connectFuture) {
        getTaskExecutor().execute(new Runnable() {

            @Override
            public void run() {
                HttpHeaders httpHeaders = transportRequest.getHttpRequestHeaders();
                XhrRequestCallback requestCallback = new XhrRequestCallback(handshakeHeaders);
                XhrRequestCallback requestCallbackAfterHandshake = new XhrRequestCallback(httpHeaders);
                XhrReceiveExtractor responseExtractor = new XhrReceiveExtractor(session);
                while (true) {
                    if (session.isDisconnected()) {
                        session.afterTransportClosed(null);
                        break;
                    }
                    try {
                        if (logger.isTraceEnabled()) {
                            logger.trace("Starting XHR receive request, url=" + receiveUrl);
                        }
                        getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
                        requestCallback = requestCallbackAfterHandshake;
                    } catch (Throwable ex) {
                        if (!connectFuture.isDone()) {
                            connectFuture.setException(ex);
                        } else {
                            session.handleTransportError(ex);
                            session.afterTransportClosed(new CloseStatus(1006, ex.getMessage()));
                        }
                        break;
                    }
                }
            }
        });
    }

    @Override
    protected ResponseEnreplacedy<String> executeInfoRequestInternal(URI infoUrl, HttpHeaders headers) {
        RequestCallback requestCallback = new XhrRequestCallback(headers);
        return this.restTemplate.execute(infoUrl, HttpMethod.GET, requestCallback, textResponseExtractor);
    }

    @Override
    public ResponseEnreplacedy<String> executeSendRequestInternal(URI url, HttpHeaders headers, TextMessage message) {
        RequestCallback requestCallback = new XhrRequestCallback(headers, message.getPayload());
        return this.restTemplate.execute(url, HttpMethod.POST, requestCallback, textResponseExtractor);
    }

    /**
     * A simple ResponseExtractor that reads the body into a String.
     */
    private final static ResponseExtractor<ResponseEnreplacedy<String>> textResponseExtractor = new ResponseExtractor<ResponseEnreplacedy<String>>() {

        @Override
        public ResponseEnreplacedy<String> extractData(ClientHttpResponse response) throws IOException {
            if (response.getBody() == null) {
                return new ResponseEnreplacedy<String>(response.getHeaders(), response.getStatusCode());
            } else {
                String body = StreamUtils.copyToString(response.getBody(), SockJsFrame.CHARSET);
                return new ResponseEnreplacedy<String>(body, response.getHeaders(), response.getStatusCode());
            }
        }
    };

    /**
     * A RequestCallback to add the headers and (optionally) String content.
     */
    private static clreplaced XhrRequestCallback implements RequestCallback {

        private final HttpHeaders headers;

        private final String body;

        public XhrRequestCallback(HttpHeaders headers) {
            this(headers, null);
        }

        public XhrRequestCallback(HttpHeaders headers, String body) {
            this.headers = headers;
            this.body = body;
        }

        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            if (this.headers != null) {
                request.getHeaders().putAll(this.headers);
            }
            if (this.body != null) {
                StreamUtils.copy(this.body, SockJsFrame.CHARSET, request.getBody());
            }
        }
    }

    /**
     * Splits the body of an HTTP response into SockJS frames and delegates those
     * to an {@link XhrClientSockJsSession}.
     */
    private clreplaced XhrReceiveExtractor implements ResponseExtractor<Object> {

        private final XhrClientSockJsSession sockJsSession;

        public XhrReceiveExtractor(XhrClientSockJsSession sockJsSession) {
            this.sockJsSession = sockJsSession;
        }

        @Override
        public Object extractData(ClientHttpResponse response) throws IOException {
            if (!HttpStatus.OK.equals(response.getStatusCode())) {
                throw new HttpServerErrorException(response.getStatusCode());
            }
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive headers: " + response.getHeaders());
            }
            InputStream is = response.getBody();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            while (true) {
                if (this.sockJsSession.isDisconnected()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("SockJS sockJsSession closed, closing response.");
                    }
                    response.close();
                    break;
                }
                int b = is.read();
                if (b == -1) {
                    if (os.size() > 0) {
                        handleFrame(os);
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("XHR receive completed");
                    }
                    break;
                }
                if (b == '\n') {
                    handleFrame(os);
                } else {
                    os.write(b);
                }
            }
            return null;
        }

        private void handleFrame(ByteArrayOutputStream os) {
            byte[] bytes = os.toByteArray();
            os.reset();
            String content = new String(bytes, SockJsFrame.CHARSET);
            if (logger.isTraceEnabled()) {
                logger.trace("XHR receive content: " + content);
            }
            if (!PRELUDE.equals(content)) {
                this.sockJsSession.handleFrame(new String(bytes, SockJsFrame.CHARSET));
            }
        }
    }
}

18 View Source File : SimpleTaskWorkManager.java
License : Apache License 2.0
Project Creator : langtianya

/**
 * Simple JCA 1.5 {@link javax.resource.spi.work.WorkManager} implementation that
 * delegates to a Spring {@link org.springframework.core.task.TaskExecutor}.
 * Provides simple task execution including start timeouts, but without support
 * for a JCA ExecutionContext (i.e. without support for imported transactions).
 *
 * <p>Uses a {@link org.springframework.core.task.SyncTaskExecutor} for {@link #doWork}
 * calls and a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}
 * for {@link #startWork} and {@link #scheduleWork} calls, by default.
 * These default task executors can be overridden through configuration.
 *
 * <p><b>NOTE: This WorkManager does not provide thread pooling by default!</b>
 * Specify a {@link org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor}
 * (or any other thread-pooling TaskExecutor) as "asyncTaskExecutor" in order to
 * achieve actual thread pooling.
 *
 * <p>This WorkManager automatically detects a specified
 * {@link org.springframework.core.task.AsyncTaskExecutor} implementation
 * and uses its extended timeout functionality where appropriate.
 * JCA WorkListeners are fully supported in any case.
 *
 * @author Juergen Hoeller
 * @since 2.0.3
 * @see #setSyncTaskExecutor
 * @see #setAsyncTaskExecutor
 */
public clreplaced SimpleTaskWorkManager implements WorkManager {

    private TaskExecutor syncTaskExecutor = new SyncTaskExecutor();

    private AsyncTaskExecutor asyncTaskExecutor = new SimpleAsyncTaskExecutor();

    /**
     * Specify the TaskExecutor to use for <i>synchronous</i> work execution
     * (i.e. {@link #doWork} calls).
     * <p>Default is a {@link org.springframework.core.task.SyncTaskExecutor}.
     */
    public void setSyncTaskExecutor(TaskExecutor syncTaskExecutor) {
        this.syncTaskExecutor = syncTaskExecutor;
    }

    /**
     * Specify the TaskExecutor to use for <i>asynchronous</i> work execution
     * (i.e. {@link #startWork} and {@link #scheduleWork} calls).
     * <p>This will typically (but not necessarily) be an
     * {@link org.springframework.core.task.AsyncTaskExecutor} implementation.
     * Default is a {@link org.springframework.core.task.SimpleAsyncTaskExecutor}.
     */
    public void setAsyncTaskExecutor(AsyncTaskExecutor asyncTaskExecutor) {
        this.asyncTaskExecutor = asyncTaskExecutor;
    }

    @Override
    public void doWork(Work work) throws WorkException {
        doWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public void doWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener) throws WorkException {
        replacedert.state(this.syncTaskExecutor != null, "No 'syncTaskExecutor' set");
        executeWork(this.syncTaskExecutor, work, startTimeout, false, executionContext, workListener);
    }

    @Override
    public long startWork(Work work) throws WorkException {
        return startWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public long startWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener) throws WorkException {
        replacedert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
        return executeWork(this.asyncTaskExecutor, work, startTimeout, true, executionContext, workListener);
    }

    @Override
    public void scheduleWork(Work work) throws WorkException {
        scheduleWork(work, WorkManager.INDEFINITE, null, null);
    }

    @Override
    public void scheduleWork(Work work, long startTimeout, ExecutionContext executionContext, WorkListener workListener) throws WorkException {
        replacedert.state(this.asyncTaskExecutor != null, "No 'asyncTaskExecutor' set");
        executeWork(this.asyncTaskExecutor, work, startTimeout, false, executionContext, workListener);
    }

    /**
     * Execute the given Work on the specified TaskExecutor.
     * @param taskExecutor the TaskExecutor to use
     * @param work the Work to execute
     * @param startTimeout the time duration within which the Work is supposed to start
     * @param blockUntilStarted whether to block until the Work has started
     * @param executionContext the JCA ExecutionContext for the given Work
     * @param workListener the WorkListener to clal for the given Work
     * @return the time elapsed from Work acceptance until start of execution
     * (or -1 if not applicable or not known)
     * @throws WorkException if the TaskExecutor did not accept the Work
     */
    protected long executeWork(TaskExecutor taskExecutor, Work work, long startTimeout, boolean blockUntilStarted, ExecutionContext executionContext, WorkListener workListener) throws WorkException {
        if (executionContext != null && executionContext.getXid() != null) {
            throw new WorkException("SimpleTaskWorkManager does not supported imported XIDs: " + executionContext.getXid());
        }
        WorkListener workListenerToUse = workListener;
        if (workListenerToUse == null) {
            workListenerToUse = new WorkAdapter();
        }
        boolean isAsync = (taskExecutor instanceof AsyncTaskExecutor);
        DelegatingWorkAdapter workHandle = new DelegatingWorkAdapter(work, workListenerToUse, !isAsync);
        try {
            if (isAsync) {
                ((AsyncTaskExecutor) taskExecutor).execute(workHandle, startTimeout);
            } else {
                taskExecutor.execute(workHandle);
            }
        } catch (TaskTimeoutException ex) {
            WorkException wex = new WorkRejectedException("TaskExecutor rejected Work because of timeout: " + work, ex);
            wex.setErrorCode(WorkException.START_TIMED_OUT);
            workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
            throw wex;
        } catch (TaskRejectedException ex) {
            WorkException wex = new WorkRejectedException("TaskExecutor rejected Work: " + work, ex);
            wex.setErrorCode(WorkException.INTERNAL);
            workListenerToUse.workRejected(new WorkEvent(this, WorkEvent.WORK_REJECTED, work, wex));
            throw wex;
        } catch (Throwable ex) {
            WorkException wex = new WorkException("TaskExecutor failed to execute Work: " + work, ex);
            wex.setErrorCode(WorkException.INTERNAL);
            throw wex;
        }
        if (isAsync) {
            workListenerToUse.workAccepted(new WorkEvent(this, WorkEvent.WORK_ACCEPTED, work, null));
        }
        if (blockUntilStarted) {
            long acceptanceTime = System.currentTimeMillis();
            synchronized (workHandle.monitor) {
                try {
                    while (!workHandle.started) {
                        workHandle.monitor.wait();
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
            return (System.currentTimeMillis() - acceptanceTime);
        } else {
            return WorkManager.UNKNOWN;
        }
    }

    /**
     * Work adapter that supports start timeouts and WorkListener callbacks
     * for a given Work that it delegates to.
     */
    private static clreplaced DelegatingWorkAdapter implements Work {

        private final Work work;

        private final WorkListener workListener;

        private final boolean acceptOnExecution;

        public final Object monitor = new Object();

        public boolean started = false;

        public DelegatingWorkAdapter(Work work, WorkListener workListener, boolean acceptOnExecution) {
            this.work = work;
            this.workListener = workListener;
            this.acceptOnExecution = acceptOnExecution;
        }

        @Override
        public void run() {
            if (this.acceptOnExecution) {
                this.workListener.workAccepted(new WorkEvent(this, WorkEvent.WORK_ACCEPTED, work, null));
            }
            synchronized (this.monitor) {
                this.started = true;
                this.monitor.notify();
            }
            this.workListener.workStarted(new WorkEvent(this, WorkEvent.WORK_STARTED, this.work, null));
            try {
                this.work.run();
            } catch (RuntimeException ex) {
                this.workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, this.work, new WorkCompletedException(ex)));
                throw ex;
            } catch (Error err) {
                this.workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, this.work, new WorkCompletedException(err)));
                throw err;
            }
            this.workListener.workCompleted(new WorkEvent(this, WorkEvent.WORK_COMPLETED, this.work, null));
        }

        @Override
        public void release() {
            this.work.release();
        }
    }
}

18 View Source File : ExecutorSubscribableChannelTests.java
License : Apache License 2.0
Project Creator : langtianya

@Test
public void sendWithExecutor() throws Exception {
    BeforeHandleInterceptor interceptor = new BeforeHandleInterceptor();
    TaskExecutor executor = mock(TaskExecutor.clreplaced);
    ExecutorSubscribableChannel testChannel = new ExecutorSubscribableChannel(executor);
    testChannel.addInterceptor(interceptor);
    testChannel.subscribe(this.handler);
    testChannel.send(this.message);
    verify(executor).execute(this.runnableCaptor.capture());
    verify(this.handler, never()).handleMessage(this.message);
    this.runnableCaptor.getValue().run();
    verify(this.handler).handleMessage(this.message);
    replacedertEquals(1, interceptor.getCounter().get());
    replacedertTrue(interceptor.wasAfterHandledInvoked());
}

18 View Source File : SystemSchedule.java
License : MIT License
Project Creator : Jorian93

/**
 * @author: jorian
 * @date: 2019/12/21 18:57
 * @description: this is  description for the clreplaced
 */
@Slf4j
@Configuration
public clreplaced SystemSchedule {

    @Autowired
    private JobService jobService;

    @Autowired
    private TaskExecutor taskExecutor;

    /**
     * 初始化一个定时删除日志的任务,随系统启动
     */
    @PostConstruct
    public void initDeleteLogsJob() {
        taskExecutor.execute(() -> {
            Job jobModel = new Job();
            jobModel.setJobName("系统任务-删除2星期前日志");
            jobModel.setCron("0 0 0 * * ?");
            jobModel.setDescription("定时删除2个星期前日志");
            jobModel.setSpringBeanName("logServiceImpl");
            jobModel.setMethodName("deleteLogs2weekFromNow");
            jobModel.setIsSysJob(true);
            jobModel.setStatus(1);
            JobAddDTO jobAddDTO = new JobAddDTO();
            BeanUtils.copyProperties(jobModel, jobAddDTO);
            jobService.saveJob(jobAddDTO);
        });
    }
}

18 View Source File : GitServiceImpl.java
License : Apache License 2.0
Project Creator : FlowCI

/**
 * @author yang
 */
@Log4j2
@Service
public clreplaced GitServiceImpl implements GitService {

    @Autowired
    private TaskExecutor appTaskExecutor;

    @Autowired
    private Path tmpDir;

    @Autowired
    private Cache<String, List<String>> gitBranchCache;

    @Autowired
    private SpringEventManager eventManager;

    @Autowired
    private SecretService credentialService;

    @Override
    public void testConn(Flow flow, String url, String secret) {
        Secret c = getSecret(secret);
        if (c != null) {
            if (c.getCategory() != Secret.Category.AUTH && StringHelper.isHttpLink(url)) {
                throw new ArgumentException("Invalid credential for http git url");
            }
        }
        appTaskExecutor.execute(() -> fetchBranchFromGit(flow, url, c));
    }

    @Override
    public void testConn(Flow flow, String url, SimpleKeyPair rsa) {
        if (StringHelper.isHttpLink(url)) {
            throw new ArgumentException("Invalid git url");
        }
        RSASecret c = new RSASecret();
        c.setPair(rsa);
        appTaskExecutor.execute(() -> fetchBranchFromGit(flow, url, c));
    }

    @Override
    public void testConn(Flow flow, String url, SimpleAuthPair auth) {
        if (!StringHelper.isHttpLink(url)) {
            throw new ArgumentException("Invalid git url");
        }
        AuthSecret c = new AuthSecret();
        c.setPair(auth);
        appTaskExecutor.execute(() -> fetchBranchFromGit(flow, url, c));
    }

    @Override
    public List<String> listGitBranch(Flow flow) {
        final String credentialName = flow.getCredentialName();
        return gitBranchCache.get(flow.getId(), (Function<String, List<String>>) flowId -> fetchBranchFromGit(flow, flow.getGitUrl(), getSecret(credentialName)));
    }

    // ====================================================================
    // %% Utils
    // ====================================================================
    private Secret getSecret(String name) {
        if (!StringHelper.hasValue(name)) {
            return null;
        }
        return credentialService.get(name);
    }

    private List<String> fetchBranchFromGit(Flow flow, String url, Secret credential) {
        if (Strings.isNullOrEmpty(url)) {
            eventManager.publish(new GitTestEvent(this, flow.getId(), "Git url is missing"));
            return Collections.emptyList();
        }
        eventManager.publish(new GitTestEvent(this, flow.getId()));
        SimpleSecret secret = null;
        if (credential != null) {
            secret = credential.toSimpleSecret();
        }
        GitClient client = new GitClient(flow.getGitUrl(), tmpDir, secret);
        try {
            final List<String> branches = client.branches();
            eventManager.publish(new GitTestEvent(this, flow.getId(), branches));
            return branches;
        } catch (Exception e) {
            log.warn(e.getMessage());
            eventManager.publish(new GitTestEvent(this, flow.getId(), e.getMessage()));
            return Collections.emptyList();
        }
    }
}

See More Examples