repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpSender.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpSender.java | package dev.snowdrop.vertx.amqp;
import java.util.function.Consumer;
import io.smallrye.mutiny.converters.uni.UniReactorConverters;
import reactor.core.publisher.Mono;
class SnowdropAmqpSender implements AmqpSender {
private final io.vertx.mutiny.amqp.AmqpSender delegate;
private final MessageConverter messageConverter;
SnowdropAmqpSender(io.vertx.mutiny.amqp.AmqpSender delegate, MessageConverter messageConverter) {
this.delegate = delegate;
this.messageConverter = messageConverter;
}
@Override
public io.vertx.core.streams.WriteStream vertxWriteStream() {
return delegate.getDelegate();
}
@Override
public AmqpSender exceptionHandler(Consumer<Throwable> handler) {
delegate.exceptionHandler(handler);
return this;
}
@Override
public AmqpSender drainHandler(Consumer<Void> handler) {
delegate.drainHandler(() -> handler.accept(null));
return this;
}
@Override
public AmqpSender setWriteQueueMaxSize(int maxSize) {
delegate.setWriteQueueMaxSize(maxSize);
return this;
}
@Override
public boolean writeQueueFull() {
return delegate.writeQueueFull();
}
@Override
public Mono<Void> write(AmqpMessage message) {
return delegate.write(messageConverter.toMutinyMessage(message))
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public Mono<Void> end() {
return delegate.end()
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public Mono<Void> end(AmqpMessage message) {
return delegate.end(messageConverter.toMutinyMessage(message))
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public AmqpSender send(AmqpMessage message) {
delegate.send(messageConverter.toMutinyMessage(message));
return this;
}
@Override
public Mono<Void> sendWithAck(AmqpMessage message) {
return delegate.sendWithAck(messageConverter.toMutinyMessage(message))
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public AmqpConnection connection() {
return new SnowdropAmqpConnection(delegate.connection(), messageConverter);
}
@Override
public String address() {
return delegate.address();
}
@Override
public Mono<Void> close() {
return delegate.close()
.convert()
.with(UniReactorConverters.toMono());
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpClient.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpClient.java | package dev.snowdrop.vertx.amqp;
import java.time.Duration;
import io.smallrye.mutiny.converters.uni.UniReactorConverters;
import org.springframework.beans.factory.DisposableBean;
import reactor.core.publisher.Mono;
class SnowdropAmqpClient implements AmqpClient, DisposableBean {
private final io.vertx.mutiny.amqp.AmqpClient delegate;
private final MessageConverter messageConverter;
SnowdropAmqpClient(io.vertx.mutiny.amqp.AmqpClient delegate, MessageConverter messageConverter) {
this.delegate = delegate;
this.messageConverter = messageConverter;
}
@Override
public Mono<AmqpConnection> connect() {
return delegate.connect()
.convert()
.with(UniReactorConverters.toMono())
.map(delegateConnection -> new SnowdropAmqpConnection(delegateConnection, messageConverter));
}
@Override
public Mono<AmqpSender> createSender(String address) {
return delegate.createSender(address)
.convert()
.with(UniReactorConverters.toMono())
.map(delegateSender -> new SnowdropAmqpSender(delegateSender, messageConverter));
}
@Override
public Mono<AmqpSender> createSender(String address, AmqpSenderOptions options) {
return delegate.createSender(address, options.toVertxAmqpSenderOptions())
.convert()
.with(UniReactorConverters.toMono())
.map(delegateSender -> new SnowdropAmqpSender(delegateSender, messageConverter));
}
@Override
public Mono<AmqpReceiver> createReceiver(String address) {
return delegate.createReceiver(address)
.convert()
.with(UniReactorConverters.toMono())
.map(delegateReceiver -> new SnowdropAmqpReceiver(delegateReceiver, messageConverter));
}
@Override
public Mono<AmqpReceiver> createReceiver(String address, AmqpReceiverOptions options) {
return delegate.createReceiver(address, options.toVertxAmqpReceiverOptions())
.convert()
.with(UniReactorConverters.toMono())
.map(delegateReceiver -> new SnowdropAmqpReceiver(delegateReceiver, messageConverter));
}
@Override
public Mono<Void> close() {
return delegate.close()
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public void destroy() {
close().block(Duration.ofSeconds(10)); // TODO should this be configurable?
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpMessage.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpMessage.java | package dev.snowdrop.vertx.amqp;
import java.io.StringReader;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
class SnowdropAmqpMessage implements AmqpMessage {
private final io.vertx.amqp.AmqpMessage delegate;
private final DataBufferFactory dataBufferFactory;
SnowdropAmqpMessage(io.vertx.amqp.AmqpMessage delegate) {
this.delegate = delegate;
this.dataBufferFactory = new DefaultDataBufferFactory();
}
@Override
public boolean isDurable() {
return delegate.isDurable();
}
@Override
public boolean isFirstAcquirer() {
return delegate.isFirstAcquirer();
}
@Override
public int priority() {
return delegate.priority();
}
@Override
public int deliveryCount() {
return delegate.deliveryCount();
}
@Override
public long ttl() {
return delegate.ttl();
}
@Override
public String id() {
return delegate.id();
}
@Override
public String address() {
return delegate.address();
}
@Override
public String replyTo() {
return delegate.replyTo();
}
@Override
public String correlationId() {
return delegate.correlationId();
}
@Override
public boolean isBodyNull() {
return delegate.isBodyNull();
}
@Override
public boolean bodyAsBoolean() {
return delegate.bodyAsBoolean();
}
@Override
public byte bodyAsByte() {
return delegate.bodyAsByte();
}
@Override
public short bodyAsShort() {
return delegate.bodyAsShort();
}
@Override
public int bodyAsInteger() {
return delegate.bodyAsInteger();
}
@Override
public long bodyAsLong() {
return delegate.bodyAsLong();
}
@Override
public float bodyAsFloat() {
return delegate.bodyAsFloat();
}
@Override
public double bodyAsDouble() {
return delegate.bodyAsFloat();
}
@Override
public char bodyAsChar() {
return delegate.bodyAsChar();
}
@Override
public Instant bodyAsTimestamp() {
return delegate.bodyAsTimestamp();
}
@Override
public UUID bodyAsUUID() {
return delegate.bodyAsUUID();
}
@Override
public DataBuffer bodyAsBinary() {
return dataBufferFactory.wrap(delegate.bodyAsBinary().getBytes());
}
@Override
public String bodyAsString() {
return delegate.bodyAsString();
}
@Override
public String bodyAsSymbol() {
return delegate.bodyAsSymbol();
}
@Override
public <T> List<T> bodyAsList() {
return delegate.bodyAsList();
}
@Override
public <K, V> Map<K, V> bodyAsMap() {
return delegate.bodyAsMap();
}
@Override
public JsonObject bodyAsJsonObject() {
return Json.createParser(new StringReader(delegate.bodyAsJsonObject().toString())).getObject();
}
@Override
public JsonArray bodyAsJsonArray() {
return Json.createParser(new StringReader(delegate.bodyAsJsonArray().toString())).getArray();
}
@Override
public String subject() {
return delegate.subject();
}
@Override
public String contentType() {
return delegate.contentType();
}
@Override
public String contentEncoding() {
return delegate.contentEncoding();
}
@Override
public long expiryTime() {
return delegate.expiryTime();
}
@Override
public long creationTime() {
return delegate.creationTime();
}
@Override
public String groupId() {
return delegate.groupId();
}
@Override
public String replyToGroupId() {
return delegate.replyToGroupId();
}
@Override
public long groupSequence() {
return delegate.groupSequence();
}
@Override
public io.vertx.amqp.AmqpMessage toVertxAmqpMessage() {
return delegate;
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpReceiver.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpReceiver.java | package dev.snowdrop.vertx.amqp;
import dev.snowdrop.vertx.streams.ReadStream;
import reactor.core.publisher.Mono;
public interface AmqpReceiver extends ReadStream<AmqpMessage> {
AmqpConnection connection();
String address();
Mono<Void> close();
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpMessageBuilder.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpMessageBuilder.java | package dev.snowdrop.vertx.amqp;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.json.JsonArray;
import javax.json.JsonObject;
import org.springframework.core.io.buffer.DataBuffer;
public interface AmqpMessageBuilder {
static AmqpMessageBuilder create() {
return new SnowdropAmqpMessageBuilder();
}
AmqpMessage build();
AmqpMessageBuilder priority(short priority);
AmqpMessageBuilder durable(boolean durable);
AmqpMessageBuilder ttl(long ttl);
AmqpMessageBuilder firstAcquirer(boolean firstAcquirer);
AmqpMessageBuilder deliveryCount(int deliveryCount);
AmqpMessageBuilder id(String id);
AmqpMessageBuilder address(String address);
AmqpMessageBuilder replyTo(String replyTo);
AmqpMessageBuilder correlationId(String correlationId);
AmqpMessageBuilder withBody(String value);
AmqpMessageBuilder withSymbolAsBody(String value);
AmqpMessageBuilder subject(String subject);
AmqpMessageBuilder contentType(String contentType);
AmqpMessageBuilder contentEncoding(String contentEncoding);
AmqpMessageBuilder expiryTime(long expiry);
AmqpMessageBuilder creationTime(long creationTime);
AmqpMessageBuilder groupId(String groupId);
AmqpMessageBuilder replyToGroupId(String replyToGroupId);
AmqpMessageBuilder applicationProperties(Map<String, Object> applicationProperties);
AmqpMessageBuilder withBooleanAsBody(boolean value);
AmqpMessageBuilder withByteAsBody(byte value);
AmqpMessageBuilder withShortAsBody(short value);
AmqpMessageBuilder withIntegerAsBody(int value);
AmqpMessageBuilder withLongAsBody(long value);
AmqpMessageBuilder withFloatAsBody(float value);
AmqpMessageBuilder withDoubleAsBody(double value);
AmqpMessageBuilder withCharAsBody(char value);
AmqpMessageBuilder withInstantAsBody(Instant value);
AmqpMessageBuilder withUuidAsBody(UUID value);
AmqpMessageBuilder withListAsBody(List list);
AmqpMessageBuilder withMapAsBody(Map map);
AmqpMessageBuilder withBufferAsBody(DataBuffer value);
AmqpMessageBuilder withJsonObjectAsBody(JsonObject jsonObject);
AmqpMessageBuilder withJsonArrayAsBody(JsonArray jsonArray);
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpSenderOptions.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpSenderOptions.java | package dev.snowdrop.vertx.amqp;
public class AmqpSenderOptions {
private final io.vertx.amqp.AmqpSenderOptions delegate = new io.vertx.amqp.AmqpSenderOptions();
public String getLinkName() {
return delegate.getLinkName();
}
public AmqpSenderOptions setLinkName(String linkName) {
delegate.setLinkName(linkName);
return this;
}
public boolean isDynamic() {
return delegate.isDynamic();
}
public AmqpSenderOptions setDynamic(boolean dynamic) {
delegate.setDynamic(dynamic);
return this;
}
public boolean isAutoDrained() {
return delegate.isAutoDrained();
}
public AmqpSenderOptions setAutoDrained(boolean autoDrained) {
delegate.setAutoDrained(autoDrained);
return this;
}
io.vertx.amqp.AmqpSenderOptions toVertxAmqpSenderOptions() {
return delegate;
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpReceiver.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/SnowdropAmqpReceiver.java | package dev.snowdrop.vertx.amqp;
import io.smallrye.mutiny.converters.multi.MultiReactorConverters;
import io.smallrye.mutiny.converters.uni.UniReactorConverters;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
class SnowdropAmqpReceiver implements AmqpReceiver {
private final io.vertx.mutiny.amqp.AmqpReceiver delegate;
private final MessageConverter messageConverter;
SnowdropAmqpReceiver(io.vertx.mutiny.amqp.AmqpReceiver delegate, MessageConverter messageConverter) {
this.delegate = delegate;
this.messageConverter = messageConverter;
}
@Override
public Mono<AmqpMessage> mono() {
return delegate.toMulti()
.convert()
.with(MultiReactorConverters.toMono())
.map(messageConverter::toSnowdropMessage);
}
@Override
public Flux<AmqpMessage> flux() {
return delegate.toMulti()
.convert()
.with(MultiReactorConverters.toFlux())
.map(messageConverter::toSnowdropMessage);
}
@Override
public String address() {
return delegate.address();
}
@Override
public AmqpConnection connection() {
return new SnowdropAmqpConnection(delegate.connection(), messageConverter);
}
@Override
public Mono<Void> close() {
return delegate.close()
.convert()
.with(UniReactorConverters.toMono());
}
@Override
public io.vertx.core.streams.ReadStream vertxReadStream() {
return delegate.getDelegate();
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpMessage.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpMessage.java | package dev.snowdrop.vertx.amqp;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.json.JsonArray;
import javax.json.JsonObject;
import org.springframework.core.io.buffer.DataBuffer;
public interface AmqpMessage {
static AmqpMessageBuilder create() {
return new SnowdropAmqpMessageBuilder();
}
boolean isDurable();
boolean isFirstAcquirer();
int priority();
int deliveryCount();
long ttl();
String id();
String address();
String replyTo();
String correlationId();
boolean isBodyNull();
boolean bodyAsBoolean();
byte bodyAsByte();
short bodyAsShort();
int bodyAsInteger();
long bodyAsLong();
float bodyAsFloat();
double bodyAsDouble();
char bodyAsChar();
Instant bodyAsTimestamp();
UUID bodyAsUUID();
DataBuffer bodyAsBinary();
String bodyAsString();
String bodyAsSymbol();
<T> List<T> bodyAsList();
<K, V> Map<K, V> bodyAsMap();
JsonObject bodyAsJsonObject();
JsonArray bodyAsJsonArray();
String subject();
String contentType();
String contentEncoding();
long expiryTime();
long creationTime();
String groupId();
String replyToGroupId();
long groupSequence();
io.vertx.amqp.AmqpMessage toVertxAmqpMessage();
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpConnection.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpConnection.java | package dev.snowdrop.vertx.amqp;
import java.util.function.Consumer;
import reactor.core.publisher.Mono;
public interface AmqpConnection {
AmqpConnection exceptionHandler(Consumer<Throwable> handler);
Mono<AmqpSender> createSender(String address);
Mono<AmqpSender> createSender(String address, AmqpSenderOptions options);
Mono<AmqpSender> createAnonymousSender();
Mono<AmqpReceiver> createReceiver(String address);
Mono<AmqpReceiver> createReceiver(String address, AmqpReceiverOptions options);
Mono<AmqpReceiver> createDynamicReceiver();
Mono<Void> close();
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpSender.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpSender.java | package dev.snowdrop.vertx.amqp;
import java.util.function.Consumer;
import dev.snowdrop.vertx.streams.WriteStream;
import reactor.core.publisher.Mono;
public interface AmqpSender extends WriteStream<AmqpMessage> {
AmqpSender exceptionHandler(Consumer<Throwable> handler);
AmqpSender drainHandler(Consumer<Void> handler);
AmqpSender setWriteQueueMaxSize(int maxSize);
AmqpSender send(AmqpMessage message);
Mono<Void> sendWithAck(AmqpMessage message);
AmqpConnection connection();
String address();
Mono<Void> close();
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpReceiverOptions.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpReceiverOptions.java | package dev.snowdrop.vertx.amqp;
import java.util.List;
public class AmqpReceiverOptions {
private final io.vertx.amqp.AmqpReceiverOptions delegate = new io.vertx.amqp.AmqpReceiverOptions();
public String getLinkName() {
return delegate.getLinkName();
}
public AmqpReceiverOptions setLinkName(String linkName) {
delegate.setLinkName(linkName);
return this;
}
public boolean isDynamic() {
return delegate.isDynamic();
}
public AmqpReceiverOptions setDynamic(boolean dynamic) {
delegate.setDynamic(dynamic);
return this;
}
public String getQos() {
return delegate.getQos();
}
public AmqpReceiverOptions setQos(String qos) {
delegate.setQos(qos);
return this;
}
public List<String> getCapabilities() {
return delegate.getCapabilities();
}
public AmqpReceiverOptions setCapabilities(List<String> capabilities) {
delegate.setCapabilities(capabilities);
return this;
}
public AmqpReceiverOptions addCapability(String capability) {
delegate.addCapability(capability);
return this;
}
public boolean isDurable() {
return delegate.isDurable();
}
public AmqpReceiverOptions setDurable(boolean durable) {
delegate.setDurable(durable);
return this;
}
public int getMaxBufferedMessages() {
return delegate.getMaxBufferedMessages();
}
public AmqpReceiverOptions setMaxBufferedMessages(int maxBufferedMessages) {
delegate.setMaxBufferedMessages(maxBufferedMessages);
return this;
}
io.vertx.amqp.AmqpReceiverOptions toVertxAmqpReceiverOptions() {
return delegate;
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/MessageConverter.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/MessageConverter.java | package dev.snowdrop.vertx.amqp;
class MessageConverter {
io.vertx.mutiny.amqp.AmqpMessage toMutinyMessage(dev.snowdrop.vertx.amqp.AmqpMessage snowdropMessage) {
return new io.vertx.mutiny.amqp.AmqpMessage(snowdropMessage.toVertxAmqpMessage());
}
dev.snowdrop.vertx.amqp.AmqpMessage toSnowdropMessage(io.vertx.mutiny.amqp.AmqpMessage mutinyMessage) {
return new dev.snowdrop.vertx.amqp.SnowdropAmqpMessage(mutinyMessage.getDelegate());
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
snowdrop/vertx-spring-boot | https://github.com/snowdrop/vertx-spring-boot/blob/f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff/vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpAutoConfiguration.java | vertx-spring-boot-starter-amqp/src/main/java/dev/snowdrop/vertx/amqp/AmqpAutoConfiguration.java | package dev.snowdrop.vertx.amqp;
import io.vertx.amqp.AmqpClientOptions;
import io.vertx.core.Vertx;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableConfigurationProperties(AmqpProperties.class)
@ConditionalOnBean(Vertx.class)
@ConditionalOnProperty(prefix = AmqpProperties.PROPERTIES_PREFIX, value = "enabled", matchIfMissing = true)
public class AmqpAutoConfiguration {
@Bean
public AmqpClient amqpClient(Vertx vertx, AmqpProperties properties) {
AmqpPropertiesConverter propertiesConverter = new AmqpPropertiesConverter();
AmqpClientOptions options = propertiesConverter.toAmqpClientOptions(properties);
return new SnowdropAmqpClient(getMutinyAmqpClient(vertx, options), new MessageConverter());
}
private io.vertx.mutiny.core.Vertx getMutinyVertx(Vertx vertx) {
return new io.vertx.mutiny.core.Vertx(vertx);
}
private io.vertx.mutiny.amqp.AmqpClient getMutinyAmqpClient(Vertx vertx, AmqpClientOptions options) {
return io.vertx.mutiny.amqp.AmqpClient.create(getMutinyVertx(vertx), options);
}
}
| java | Apache-2.0 | f6c0be4d6e09d03044f8ab7e9a07d00148fa96ff | 2026-01-05T02:40:52.865792Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/LongRunningJobMonitorTest.java | src/test/java/com/coreoz/wisp/LongRunningJobMonitorTest.java | package com.coreoz.wisp;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.Test;
public class LongRunningJobMonitorTest {
@Test
public void detectLongRunningJob__check_running_job_limits_detection() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-11L);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isTrue();
job = newJob();
job.lastExecutionStartedTimeInMillis(-12L);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isTrue();
job = newJob();
job.lastExecutionStartedTimeInMillis(-10L);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
job = newJob();
job.lastExecutionStartedTimeInMillis(-9L);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
}
@Test
public void detectLongRunningJob__check_that_a_job_long_execution_is_detected_only_once() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-100L);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isTrue();
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
}
@Test
public void detectLongRunningJob__check_that_a_job_with_a_null_running_time_or_thread_is_not_detected() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
job.lastExecutionStartedTimeInMillis(-100L);
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
job.lastExecutionStartedTimeInMillis(null);
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(0, job)).isFalse();
}
@Test
public void detectLongRunningJob__check_that_a_job_not_being_run_is_not_detected_as_too_long() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null);
Job job = newJob();
job.status(JobStatus.SCHEDULED);
job.lastExecutionStartedTimeInMillis(0L); // running for a long time...
job.threadRunningJob(Thread.currentThread());
assertThat(detector.detectLongRunningJob(System.currentTimeMillis(), job)).isFalse();
job.status(JobStatus.DONE);
assertThat(detector.detectLongRunningJob(System.currentTimeMillis(), job)).isFalse();
job.status(JobStatus.READY);
assertThat(detector.detectLongRunningJob(System.currentTimeMillis(), job)).isFalse();
}
@Test
public void cleanUpLongJobIfItHasFinishedExecuting__check_that_a_job_not_detected_is_not_cleaned() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null);
Job job = newJob();
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isNull();
}
@Test
public void cleanUpLongJobIfItHasFinishedExecuting__check_that_a_detected_same_running_job_is_not_cleaned() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-100L);
job.threadRunningJob(Thread.currentThread());
detector.detectLongRunningJob(0, job);
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isNull();
}
@Test
public void cleanUpLongJobIfItHasFinishedExecuting__check_that_the_exact_job_execution_time_is_logged_when_job_execution_is_incremented_by_one() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-100L);
job.threadRunningJob(Thread.currentThread());
detector.detectLongRunningJob(0, job);
job.executionsCount(1);
job.lastExecutionEndedTimeInMillis(-50L);
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isEqualTo(50L);
}
@Test
public void cleanUpLongJobIfItHasFinishedExecuting__check_that_the_approximate_job_execution_time_is_logged_when_job_execution_is_incremented_by_more_than_one() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-100L);
job.threadRunningJob(Thread.currentThread());
detector.detectLongRunningJob(0, job);
job.executionsCount(2);
job.lastExecutionEndedTimeInMillis(-50L);
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isEqualTo(100L);
}
@Test
public void cleanUpLongJobIfItHasFinishedExecuting__check_that_a_clean_job_execution_is_really_cleaned() {
LongRunningJobMonitor detector = new LongRunningJobMonitor(null, Duration.ofMillis(10));
Job job = newJob();
job.lastExecutionStartedTimeInMillis(-100L);
job.threadRunningJob(Thread.currentThread());
detector.detectLongRunningJob(0, job);
job.executionsCount(1);
job.lastExecutionEndedTimeInMillis(-50L);
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isEqualTo(50L);
assertThat(detector.cleanUpLongJobIfItHasFinishedExecuting(0, job)).isNull();
}
private Job newJob() {
return new Job(
JobStatus.RUNNING,
-1L,
0,
null,
null,
"job name",
null,
null
);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/SchedulerShutdownTest.java | src/test/java/com/coreoz/wisp/SchedulerShutdownTest.java | package com.coreoz.wisp;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.Test;
import com.coreoz.wisp.Utils.SingleJob;
import com.coreoz.wisp.schedule.Schedules;
public class SchedulerShutdownTest {
@Test
public void shutdown_should_be_immediate_if_no_job_is_running() {
Scheduler scheduler = new Scheduler();
long beforeShutdown = System.currentTimeMillis();
scheduler.gracefullyShutdown();
assertThat(System.currentTimeMillis() - beforeShutdown).isLessThan(20L);
}
@Test
public void second_shutdown_should_still_wait_for_its_timeout() throws InterruptedException {
Scheduler scheduler = new Scheduler();
scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
// so the job can start executing
Thread.sleep(20L);
try {
scheduler.gracefullyShutdown(Duration.ofMillis(20)); // this will throw the exception
throw new InterruptedException(); // so the compiler is happy
} catch (InterruptedException e) {
// as excepted
}
long beforeSecondShutdown = System.currentTimeMillis();
scheduler.gracefullyShutdown();
assertThat(System.currentTimeMillis() - beforeSecondShutdown).isGreaterThan(100L);
}
@Test
public void ready_job_should_finish_without_being_executed_during_shutdown() throws InterruptedException {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
// so the job can start executing
Thread.sleep(20L);
SingleJob jobThatExecuteInTwoseconds = new SingleJob() {
@Override
public void run() {
try {
Thread.sleep(2000);
super.run();
} catch (InterruptedException e) {
throw new RuntimeException("Should not be interrupted", e);
}
}
};
Job jobThatWillNotBeExecuted = scheduler.schedule(jobThatExecuteInTwoseconds, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
// so the job can be ready to be executed
Thread.sleep(20L);
assertThat(jobThatWillNotBeExecuted.status()).isEqualTo(JobStatus.READY);
long beforeShutdown = System.currentTimeMillis();
scheduler.gracefullyShutdown();
assertThat(System.currentTimeMillis() - beforeShutdown).isLessThan(200L);
assertThat(jobThatWillNotBeExecuted.executionsCount()).isZero();
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/Utils.java | src/test/java/com/coreoz/wisp/Utils.java | package com.coreoz.wisp;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public class Utils {
public static final Runnable TASK_THAT_SLEEPS_FOR_200MS = () -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
throw new RuntimeException("Should not be interrupted", e);
}
};
public static class SingleJob implements Runnable {
AtomicInteger countExecuted = new AtomicInteger(0);
@Override
public void run() {
countExecuted.incrementAndGet();
synchronized (this) {
notifyAll();
}
}
}
public static void waitOn(Object lockOn, Supplier<Boolean> condition, long maxWait) {
long currentTime = System.currentTimeMillis();
long waitUntil = currentTime + maxWait;
while(!condition.get() && waitUntil > currentTime) {
synchronized (lockOn) {
try {
lockOn.wait(5);
} catch (InterruptedException e) {
}
}
currentTime = System.currentTimeMillis();
}
}
// a do nothing runnable
private static Runnable doNothing = () -> {};
public static Runnable doNothing() {
return doNothing;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/SchedulerTest.java | src/test/java/com/coreoz/wisp/SchedulerTest.java | package com.coreoz.wisp;
import static com.coreoz.wisp.Utils.waitOn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicBoolean;
import com.coreoz.wisp.schedule.Schedule;
import org.assertj.core.data.Offset;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.wisp.Utils.SingleJob;
import com.coreoz.wisp.schedule.Schedules;
import com.coreoz.wisp.stats.SchedulerStats;
import com.coreoz.wisp.time.SystemTimeProvider;
public class SchedulerTest {
private static final Logger logger = LoggerFactory.getLogger(SchedulerTest.class);
@Test
public void check_that_two_job_cannot_be_scheduled_with_the_same_name() {
Scheduler scheduler = new Scheduler();
scheduler.schedule("job", Utils.doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
try {
scheduler.schedule("job", Utils.doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
fail();
} catch (IllegalArgumentException e) {
// as expected
}
scheduler.gracefullyShutdown();
}
@Test
public void should_run_a_single_job() throws InterruptedException {
Scheduler scheduler = new Scheduler();
SingleJob singleJob = new SingleJob();
scheduler.schedule(
"test",
singleJob,
Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofMillis(1)))
);
waitOn(singleJob, () -> singleJob.countExecuted.get() > 0, 10000);
scheduler.gracefullyShutdown();
assertThat(singleJob.countExecuted.get()).isEqualTo(1);
}
@Test
public void check_racing_conditions() throws InterruptedException {
for(int i = 1; i <= 10000; i++) {
should_run_each_job_once();
logger.info("iteration {} done", i);
}
for(int i = 1; i <= 100; i++) {
should_not_launch_job_early();
logger.info("iteration {} done", i);
}
}
@Test
public void should_run_each_job_once() throws InterruptedException {
Scheduler scheduler = new Scheduler(1);
SingleJob job1 = new SingleJob();
SingleJob job2 = new SingleJob();
SingleJob job3 = new SingleJob();
scheduler.schedule(
"job1",
job1,
Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofMillis(1)))
);
scheduler.schedule(
"job2",
job2,
Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofMillis(1)))
);
scheduler.schedule(
"job3",
job3,
Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofMillis(1)))
);
Thread thread1 = new Thread(() -> {
waitOn(job1, () -> job1.countExecuted.get() > 0, 10000);
});
thread1.start();
Thread thread2 = new Thread(() -> {
waitOn(job2, () -> job2.countExecuted.get() > 0, 10000);
});
thread2.start();
Thread thread3 = new Thread(() -> {
waitOn(job3, () -> job3.countExecuted.get() > 0, 10000);
});
thread3.start();
thread1.join();
thread2.join();
thread3.join();
SchedulerStats stats = scheduler.stats();
scheduler.gracefullyShutdown();
assertThat(job1.countExecuted.get()).isEqualTo(1);
assertThat(job2.countExecuted.get()).isEqualTo(1);
assertThat(job3.countExecuted.get()).isEqualTo(1);
// ensure that the initial thread limit is not exceeded
assertThat(
stats.getThreadPoolStats().getActiveThreads()
+ stats.getThreadPoolStats().getIdleThreads()
)
.isLessThanOrEqualTo(1);
}
@Test
public void should_not_launch_job_early() throws InterruptedException {
SystemTimeProvider timeProvider = new SystemTimeProvider();
Scheduler scheduler = new Scheduler(SchedulerConfig
.builder()
.maxThreads(1)
.timeProvider(timeProvider)
.build()
);
SingleJob job1 = new SingleJob();
long beforeExecutionTime = timeProvider.currentTime();
Duration jobIntervalTime = Duration.ofMillis(40);
Job job = scheduler.schedule(
"job1",
job1,
Schedules.executeOnce(Schedules.fixedDelaySchedule(jobIntervalTime))
);
Thread thread1 = new Thread(() -> {
waitOn(job1, () -> job1.countExecuted.get() > 0, 10000);
});
thread1.start();
thread1.join();
scheduler.gracefullyShutdown();
assertThat(job.lastExecutionEndedTimeInMillis() - beforeExecutionTime)
.isGreaterThanOrEqualTo(jobIntervalTime.toMillis());
}
@Test
public void should_not_execute_past_job() throws InterruptedException {
Scheduler scheduler = new Scheduler();
SingleJob job1 = new SingleJob();
scheduler.schedule(
"job1",
job1,
Schedules.fixedDelaySchedule(Duration.ofMillis(-1000))
);
Thread thread1 = new Thread(() -> {
waitOn(job1, () -> job1.countExecuted.get() > 0, 500);
});
thread1.start();
thread1.join();
scheduler.gracefullyShutdown();
assertThat(job1.countExecuted.get()).isEqualTo(0);
}
@Test
public void should_shutdown_instantly_if_no_job_is_running__races_test() {
for(int i=0; i<10000; i++) {
should_shutdown_instantly_if_no_job_is_running();
}
}
@Test
public void should_shutdown_instantly_if_no_job_is_running() {
Scheduler scheduler = new Scheduler();
scheduler.schedule("job1", () -> {}, Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofSeconds(60))));
scheduler.schedule("job2", () -> {}, Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofSeconds(20))));
long beforeShutdownTime = System.currentTimeMillis();
scheduler.gracefullyShutdown();
assertThat(System.currentTimeMillis() - beforeShutdownTime).isLessThan(Duration.ofSeconds(5).toMillis());
}
@Test
public void exception_in_schedule_should_not_alter_scheduler__races_test()
throws InterruptedException {
for(int i=0; i<1000; i++) {
exception_in_schedule_should_not_alter_scheduler();
}
}
@Test
public void exception_in_schedule_should_not_alter_scheduler() throws InterruptedException {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
AtomicBoolean isJob1ExecutedAfterJob2 = new AtomicBoolean(false);
SingleJob job2 = new SingleJob();
SingleJob job1 = new SingleJob() {
@Override
public void run() {
super.run();
if(job2.countExecuted.get() > 0) {
isJob1ExecutedAfterJob2.set(true);
}
}
};
scheduler.schedule("job1", job1, Schedules.fixedDelaySchedule(Duration.ofMillis(3)));
scheduler.schedule("job2", job2, (currentTimeInMillis, executionsCount, lastExecutionTimeInMillis) -> {
if(executionsCount == 0) {
return currentTimeInMillis;
}
throw new RuntimeException("Expected exception");
});
Thread thread1 = new Thread(() -> {
waitOn(job1, () -> isJob1ExecutedAfterJob2.get(), 10000);
});
thread1.start();
thread1.join();
Thread thread2 = new Thread(() -> {
waitOn(job2, () -> job2.countExecuted.get() > 0, 10000);
});
thread2.start();
thread2.join();
scheduler.gracefullyShutdown();
assertThat(isJob1ExecutedAfterJob2.get()).isTrue();
}
@Test
public void exception_in_job_should_not_prevent_the_job_from_being_executed_again() throws InterruptedException {
Scheduler scheduler = new Scheduler();
Runnable runnable = () -> { throw new RuntimeException("Excepted exception"); };
Job job = scheduler.schedule(
runnable,
Schedules.afterInitialDelay(
Schedules.fixedDelaySchedule(Duration.ofMillis(5)),
Duration.ZERO
)
);
Thread.sleep(150L);
scheduler.gracefullyShutdown();
assertThat(job.executionsCount()).isGreaterThan(1);
}
@Test
public void check_that_a_scheduled_job_has_the_right_status() {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.doNothing(), Schedules.fixedDelaySchedule(Duration.ofSeconds(1)));
assertThat(job.status()).isEqualTo(JobStatus.SCHEDULED);
scheduler.gracefullyShutdown();
assertThat(job.status()).isEqualTo(JobStatus.DONE);
}
@Test
public void check_that_a_running_job_has_the_right_status() throws InterruptedException {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(40L);
assertThat(job.status()).isEqualTo(JobStatus.RUNNING);
scheduler.gracefullyShutdown();
assertThat(job.status()).isEqualTo(JobStatus.DONE);
}
@Test
public void check_that_a_long_running_job_does_not_prevent_other_jobs_to_run() throws InterruptedException {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(10)));
Thread.sleep(25L);
scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
long countBeforeSleep = job.executionsCount();
Thread.sleep(50L);
scheduler.gracefullyShutdown();
assertThat(job.executionsCount() - countBeforeSleep).isGreaterThan(3);
}
@Test
public void check_that_metrics_are_correctly_updated_during_and_after_a_job_execution() throws InterruptedException {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(25L);
assertThat(job.executionsCount()).isZero();
assertThat(job.lastExecutionEndedTimeInMillis()).isNull();
assertThat(job.lastExecutionStartedTimeInMillis()).isCloseTo(System.currentTimeMillis(), Offset.offset(200L));
assertThat(job.threadRunningJob()).isNotNull();
scheduler.gracefullyShutdown();
assertThat(job.executionsCount()).isOne();
assertThat(job.lastExecutionEndedTimeInMillis()).isNotNull();
assertThat(job.lastExecutionStartedTimeInMillis()).isNotNull();
assertThat(job.threadRunningJob()).isNull();
}
@Test
public void remove__verify_that_a_done_job_is_correctly_removed() {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.doNothing(), Schedule.willNeverBeExecuted);
assertThat(scheduler.jobStatus()).contains(job);
scheduler.remove(job.name());
assertThat(scheduler.jobStatus()).isEmpty();
}
@Test(expected = IllegalArgumentException.class)
public void remove__verify_that_a_non_existent_job_name_raises_an_illegal_argument_exception() {
Scheduler scheduler = new Scheduler();
scheduler.remove("does not exist");
}
@Test(expected = IllegalArgumentException.class)
public void remove__verify_that_a_non_done_job_name_raises_an_illegal_argument_exception() {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule(Utils.doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1000)));
scheduler.remove(job.name());
}
@Test(expected = NullPointerException.class)
public void should_fail_if_time_provider_is_null() {
new Scheduler(SchedulerConfig.builder().maxThreads(1).timeProvider(null).build());
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/SchedulerThreadPoolTest.java | src/test/java/com/coreoz/wisp/SchedulerThreadPoolTest.java | package com.coreoz.wisp;
import static com.coreoz.wisp.Utils.waitOn;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.Test;
import com.coreoz.wisp.Utils.SingleJob;
import com.coreoz.wisp.schedule.Schedules;
import com.coreoz.wisp.stats.SchedulerStats;
public class SchedulerThreadPoolTest {
@Test
public void thread_pool_should_scale_down_when_no_more_tasks_need_executing() throws InterruptedException {
Scheduler scheduler = new Scheduler(
SchedulerConfig
.builder()
.threadsKeepAliveTime(Duration.ofMillis(50))
.build()
);
runTwoConcurrentJobsForAtLeastFiftyIterations(scheduler);
scheduler.cancel("job1");
scheduler.cancel("job2");
Thread.sleep(80L);
SchedulerStats stats = scheduler.stats();
scheduler.gracefullyShutdown();
assertThat(
stats.getThreadPoolStats().getActiveThreads()
+ stats.getThreadPoolStats().getIdleThreads()
)
.isLessThanOrEqualTo(0);
assertThat(stats.getThreadPoolStats().getLargestPoolSize()).isGreaterThanOrEqualTo(1);
}
@Test
public void should_not_create_more_threads_than_jobs_scheduled_over_time__races_test()
throws InterruptedException {
for(int i=0; i<100; i++) {
should_not_create_more_threads_than_jobs_scheduled_over_time();
}
}
@Test
public void should_not_create_more_threads_than_jobs_scheduled_over_time() throws InterruptedException {
Scheduler scheduler = new Scheduler();
runTwoConcurrentJobsForAtLeastFiftyIterations(scheduler);
SchedulerStats stats = scheduler.stats();
scheduler.gracefullyShutdown();
assertThat(
stats.getThreadPoolStats().getActiveThreads()
+ stats.getThreadPoolStats().getIdleThreads()
)
// 1 thread for each task => 2
// but since most of the thread pool logic is delegated to ThreadPoolExecutor
// we do not have precise control on how much threads will be created.
// So we mostly want to check that not all threads of the pool are created.
.isLessThanOrEqualTo(5);
}
@Test
public void should_provide_accurate_pool_size_stats() throws InterruptedException {
Scheduler scheduler = new Scheduler();
scheduler.schedule(() -> {
try {
Thread.sleep(100);
} catch (Exception e) {
// do not care any exception
}
},
Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ZERO))
);
Thread.sleep(30L);
SchedulerStats stats = scheduler.stats();
scheduler.gracefullyShutdown();
assertThat(stats.getThreadPoolStats().getActiveThreads()).isEqualTo(1);
assertThat(stats.getThreadPoolStats().getIdleThreads()).isEqualTo(0);
assertThat(stats.getThreadPoolStats().getMinThreads()).isEqualTo(0);
assertThat(stats.getThreadPoolStats().getMaxThreads()).isEqualTo(10);
assertThat(stats.getThreadPoolStats().getLargestPoolSize()).isEqualTo(1);
}
private void runTwoConcurrentJobsForAtLeastFiftyIterations(Scheduler scheduler)
throws InterruptedException {
SingleJob job1 = new SingleJob();
SingleJob job2 = new SingleJob();
scheduler.schedule("job1", job1, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
scheduler.schedule("job2", job2, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread thread1 = new Thread(() -> {
waitOn(job1, () -> job1.countExecuted.get() > 50, 100);
});
thread1.start();
thread1.join();
Thread thread2 = new Thread(() -> {
waitOn(job2, () -> job2.countExecuted.get() > 50, 100);
});
thread2.start();
thread2.join();
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/SchedulerCancelTest.java | src/test/java/com/coreoz/wisp/SchedulerCancelTest.java | package com.coreoz.wisp;
import static com.coreoz.wisp.Utils.doNothing;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.time.Duration;
import java.util.Queue;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;
import com.coreoz.wisp.Utils.SingleJob;
import com.coreoz.wisp.schedule.Schedules;
import lombok.Value;
/**
* Tests about {@link Scheduler#cancel(String)} only
*/
public class SchedulerCancelTest {
@Test
public void cancel_should_throw_IllegalArgumentException_if_the_job_name_does_not_exist() {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
try {
scheduler.cancel("job that does not exist");
fail("Should not accept to cancel a job that does not exist");
} catch (IllegalArgumentException e) {
// as expected :)
}
scheduler.gracefullyShutdown();
}
@Test
public void cancel_should_returned_a_job_with_the_done_status() throws Exception {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
scheduler.schedule("doNothing", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(100)));
Job job = scheduler.cancel("doNothing").toCompletableFuture().get(1, TimeUnit.SECONDS);
assertThat(job).isNotNull();
assertThat(job.status()).isEqualTo(JobStatus.DONE);
assertThat(scheduler.jobStatus().size()).isEqualTo(1);
assertThat(job.name()).isEqualTo("doNothing");
assertThat(job.runnable()).isSameAs(doNothing());
scheduler.gracefullyShutdown();
assertThat(job.executionsCount()).isEqualTo(0);
}
@Test
public void second_cancel_should_return_either_the_first_promise_or_either_a_completed_future() throws Exception {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
scheduler.schedule("job", Utils.TASK_THAT_SLEEPS_FOR_200MS, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
// so the job can start executing
Thread.sleep(20L);
CompletionStage<Job> cancelFuture = scheduler.cancel("job");
CompletionStage<Job> otherCancelFuture = scheduler.cancel("job");
assertThat(cancelFuture).isSameAs(otherCancelFuture);
cancelFuture.toCompletableFuture().get(1, TimeUnit.SECONDS);
CompletionStage<Job> lastCancelFuture = scheduler.cancel("job");
assertThat(lastCancelFuture.toCompletableFuture().isDone()).isTrue();
scheduler.gracefullyShutdown();
}
@Test
public void cancelled_job_should_be_schedulable_again() throws Exception {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
scheduler.schedule("doNothing", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(100)));
scheduler.cancel("doNothing").toCompletableFuture().get(1, TimeUnit.SECONDS);
Job job = scheduler.schedule("doNothing", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(100)));
assertThat(job).isNotNull();
assertThat(job.status()).isEqualTo(JobStatus.SCHEDULED);
assertThat(job.name()).isEqualTo("doNothing");
assertThat(job.runnable()).isSameAs(doNothing());
scheduler.gracefullyShutdown();
}
@Test
public void cancelling_a_job_should_wait_until_it_is_terminated_and_other_jobs_should_continue_running()
throws InterruptedException, ExecutionException, TimeoutException {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
SingleJob jobProcess1 = new SingleJob();
SingleJob jobProcess2 = new SingleJob() {
@Override
public void run() {
try {
Thread.sleep(200);
super.run();
} catch (InterruptedException e) {
throw new RuntimeException("Should not be interrupted", e);
}
}
};
Job job1 = scheduler.schedule(jobProcess1, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Job job2 = scheduler.schedule(jobProcess2, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(20);
int job1ExecutionsCount = job1.executionsCount();
assertThat(job2.executionsCount()).isEqualTo(0);
scheduler.cancel(job2.name()).toCompletableFuture().get(1, TimeUnit.SECONDS);
Thread.sleep(60);
scheduler.gracefullyShutdown();
assertThat(job2.executionsCount()).isEqualTo(1);
assertThat(jobProcess2.countExecuted.get()).isEqualTo(1);
// after job 2 is cancelled, job 1 should have been executed at least 3 times
assertThat(job1.executionsCount()).isGreaterThan(job1ExecutionsCount + 3);
}
@Test
public void a_job_should_be_cancelled_immediatly_if_it_has_the_status_ready() throws InterruptedException, ExecutionException, TimeoutException {
Scheduler scheduler = new Scheduler(SchedulerConfig.builder().maxThreads(1).build());
SingleJob jobProcess1 = new SingleJob();
SingleJob jobProcess2 = new SingleJob() {
@Override
public void run() {
try {
Thread.sleep(300);
super.run();
} catch (InterruptedException e) {
throw new RuntimeException("Should not be interrupted", e);
}
}
};
Job job1 = scheduler.schedule("Job 1", jobProcess1, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
scheduler.schedule("Job 2", jobProcess2, Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(30);
assertThat(job1.status()).isEqualTo(JobStatus.READY);
long timeBeforeCancel = System.currentTimeMillis();
scheduler.cancel(job1.name()).toCompletableFuture().get(1, TimeUnit.SECONDS);
assertThat(timeBeforeCancel - System.currentTimeMillis()).isLessThan(50L);
scheduler.gracefullyShutdown();
}
@Test
public void cancelling_a_job_should_wait_until_it_is_terminated_and_other_jobs_should_continue_running__races_test()
throws Exception {
for(int i=0; i<10; i++) {
cancelling_a_job_should_wait_until_it_is_terminated_and_other_jobs_should_continue_running();
}
}
@Test
public void scheduling_a_done_job_should_keep_its_previous_stats() throws InterruptedException, ExecutionException, TimeoutException {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule("job", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(25L);
scheduler.cancel("job").toCompletableFuture().get(1, TimeUnit.SECONDS);
Job newJob = scheduler.schedule("job", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
scheduler.gracefullyShutdown();
assertThat(newJob.executionsCount()).isGreaterThanOrEqualTo(job.executionsCount());
assertThat(newJob.lastExecutionEndedTimeInMillis()).isNotNull();
}
@Test
public void check_that_a_done_job_scheduled_again_keeps_its_scheduler_stats() throws InterruptedException, ExecutionException, TimeoutException {
Scheduler scheduler = new Scheduler();
Job job = scheduler.schedule("job", doNothing(), Schedules.fixedDelaySchedule(Duration.ofMillis(1)));
Thread.sleep(25L);
scheduler.cancel("job").toCompletableFuture().get(1, TimeUnit.SECONDS);
int beforeScheduledAgainCount = job.executionsCount();
assertThat(beforeScheduledAgainCount).as("First job must have enough time to execute").isGreaterThan(0);
Queue<ScheduledExecution> scheduledExecutions = new ConcurrentLinkedQueue<>();
scheduler.schedule("job", doNothing(), (long currentTimeInMillis, int executionsCount, Long lastExecutionEndedTimeInMillis) -> {
scheduledExecutions.add(ScheduledExecution.of(currentTimeInMillis, executionsCount, lastExecutionEndedTimeInMillis));
return currentTimeInMillis;
});
Thread.sleep(25L);
scheduler.gracefullyShutdown();
for(ScheduledExecution scheduledExecution : scheduledExecutions) {
assertThat(scheduledExecution.executionsCount).isGreaterThanOrEqualTo(beforeScheduledAgainCount);
assertThat(scheduledExecution.lastExecutionEndedTimeInMillis).isNotNull();
assertThat(scheduledExecution.lastExecutionEndedTimeInMillis).isLessThanOrEqualTo(scheduledExecution.currentTimeInMillis);
}
}
@Value(staticConstructor = "of")
private static final class ScheduledExecution {
private long currentTimeInMillis;
private int executionsCount;
private Long lastExecutionEndedTimeInMillis;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/OnceScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/OnceScheduleTest.java | package com.coreoz.wisp.schedule;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.Test;
import com.coreoz.wisp.Scheduler;
import com.coreoz.wisp.Utils;
public class OnceScheduleTest {
@Test
public void should_not_rely_only_on_job_executions_count() {
Schedule onceAfter5ms = Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ofMillis(5)));
assertThat(onceAfter5ms.nextExecutionInMillis(0, 2, null)).isEqualTo(5);
assertThat(onceAfter5ms.nextExecutionInMillis(0, 2, null)).isEqualTo(5);
assertThat(onceAfter5ms.nextExecutionInMillis(0, 3, null)).isEqualTo(Schedule.WILL_NOT_BE_EXECUTED_AGAIN);
}
@Test
public void check_that_scheduler_really_execute_job_once() throws InterruptedException {
Scheduler scheduler = new Scheduler();
scheduler.schedule("job", Utils.doNothing(), Schedules.executeOnce(Schedules.fixedDelaySchedule(Duration.ZERO)));
Thread.sleep(100);
scheduler.gracefullyShutdown();
assertThat(scheduler.findJob("job").get().executionsCount()).isEqualTo(1);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/FixedFrequencyScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/FixedFrequencyScheduleTest.java | package com.coreoz.wisp.schedule;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
public class FixedFrequencyScheduleTest {
@Test
public void test_next_execution_rounded() {
assertThat(Schedules.fixedFrequencySchedule(Duration.ofHours(2))
.nextExecutionInMillis(TimeUnit.SECONDS.toMillis(8), 0, 0L))
.isEqualTo(TimeUnit.HOURS.toMillis(2));
}
@Test
public void test_next_execution_too_much() {
assertThat(Schedules.fixedFrequencySchedule(Duration.ofHours(2))
.nextExecutionInMillis(TimeUnit.HOURS.toMillis(3), 0, 0L))
.isEqualTo(TimeUnit.HOURS.toMillis(4));
}
@Test
public void test_next_execution_not_rounded() {
assertThat(Schedules.fixedFrequencySchedule(Duration.ofHours(2))
.nextExecutionInMillis(TimeUnit.HOURS.toMillis(4), 0, 0L))
.isEqualTo(TimeUnit.HOURS.toMillis(6));
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/AfterInitialDelayScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/AfterInitialDelayScheduleTest.java | package com.coreoz.wisp.schedule;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import org.junit.Test;
import com.coreoz.wisp.Scheduler;
import com.coreoz.wisp.Utils;
public class AfterInitialDelayScheduleTest {
@Test
public void first_execution_should_depends_only_on_the_first_delay() {
Schedule after1msDelay = Schedules.afterInitialDelay(null, Duration.ofMillis(1));
assertThat(after1msDelay.nextExecutionInMillis(0, 0, null)).isEqualTo(1);
}
@Test
public void should_not_rely_only_on_job_executions_count() {
Schedule every5ms = Schedules.fixedDelaySchedule(Duration.ofMillis(5));
Schedule afterUnusedDelay = Schedules.afterInitialDelay(every5ms, Duration.ZERO);
assertThat(afterUnusedDelay.nextExecutionInMillis(0, 2, null)).isEqualTo(0);
assertThat(afterUnusedDelay.nextExecutionInMillis(0, 2, null)).isEqualTo(0);
assertThat(afterUnusedDelay.nextExecutionInMillis(0, 3, null)).isEqualTo(5);
}
@Test
public void check_that_scheduler_really_rely_on_initial_delay() throws InterruptedException {
Scheduler scheduler = new Scheduler();
scheduler.schedule("job", Utils.doNothing(), Schedules.afterInitialDelay(Schedules.fixedDelaySchedule(Duration.ofDays(1)), Duration.ZERO));
Thread.sleep(100);
scheduler.gracefullyShutdown();
assertThat(scheduler.findJob("job").get().executionsCount()).isEqualTo(1);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/FixedHourScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/FixedHourScheduleTest.java | package com.coreoz.wisp.schedule;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
public class FixedHourScheduleTest {
@Test
public void should_parse_time_without_seconds() {
LocalTime executionTime = new FixedHourSchedule("12:31").executionTime();
assertThat(executionTime.getHour()).isEqualTo(12);
assertThat(executionTime.getMinute()).isEqualTo(31);
assertThat(executionTime.getSecond()).isEqualTo(0);
}
@Test
public void should_parse_time_with_seconds() {
LocalTime executionTime = new FixedHourSchedule("03:31:09").executionTime();
assertThat(executionTime.getHour()).isEqualTo(3);
assertThat(executionTime.getMinute()).isEqualTo(31);
assertThat(executionTime.getSecond()).isEqualTo(9);
}
@Test
public void should_calcule_next_execution_from_epoch() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime augustMidnight = LocalDate
.of(2016, 8, 31)
.atStartOfDay()
.atZone(ectZone);
long midnight = augustMidnight.toEpochSecond() * 1000;
assertThat(
new FixedHourSchedule("00:00:00", ectZone).nextExecutionInMillis(midnight, 0, null)
).isEqualTo(midnight);
}
@Test
public void should_calcule_next_execution_from_midnight() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime augustMidnight = LocalDate
.of(2016, 8, 31)
.atStartOfDay()
.atZone(ectZone);
long midnight = augustMidnight.toEpochSecond() * 1000;
assertThat(
new FixedHourSchedule("00:00:00", ectZone).durationUntilNextExecutionInMillis(midnight, null)
).isEqualTo(0);
assertThat(
new FixedHourSchedule("00:00:01", ectZone).durationUntilNextExecutionInMillis(midnight, null)
).isEqualTo(1000);
}
@Test
public void should_calcule_next_execution_from_midday() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime augustMidday = LocalDate
.of(2016, 8, 31)
.atTime(12, 0)
.atZone(ectZone);
long midday = augustMidday.toEpochSecond() * 1000;
assertThat(
new FixedHourSchedule("12:00:00", ectZone).durationUntilNextExecutionInMillis(midday, null)
).isEqualTo(0);
assertThat(
new FixedHourSchedule("12:00:01", ectZone).durationUntilNextExecutionInMillis(midday, null)
).isEqualTo(1000);
assertThat(
new FixedHourSchedule("11:59:59", ectZone).durationUntilNextExecutionInMillis(midday, null)
).isEqualTo(24 * 60 * 60 * 1000 - 1000);
assertThat(
new FixedHourSchedule("00:00:00", ectZone).durationUntilNextExecutionInMillis(midday, null)
).isEqualTo(12 * 60 * 60 * 1000);
}
@Test
public void should_calcule_next_execution_with_dst() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime midnight = LocalDate
.of(2016, 10, 30)
.atStartOfDay()
.atZone(ectZone);
long midnightMillis = midnight.toEpochSecond() * 1000;
assertThat(new FixedHourSchedule("02:00:00", ectZone).durationUntilNextExecutionInMillis(midnightMillis, null)).isEqualTo(2 * 60 * 60 * 1000);
assertThat(new FixedHourSchedule("03:00:00", ectZone).durationUntilNextExecutionInMillis(midnightMillis, null)).isEqualTo(4 * 60 * 60 * 1000);
}
@Test
public void should_calcule_next_execution_during_time_change() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime oneSecBeforeTimeChange = LocalDate
.of(2016, 10, 30)
.atTime(1, 59, 59)
.atZone(ectZone);
long oneSecBeforeTimeChangeMillis = oneSecBeforeTimeChange.toEpochSecond() * 1000;
long oneSecAfterTimeChangeMillis = (oneSecBeforeTimeChange.toEpochSecond() + 2) * 1000;
assertThat(
new FixedHourSchedule("02:00:00", ectZone)
.durationUntilNextExecutionInMillis(oneSecBeforeTimeChangeMillis, null)
).isEqualTo(1000);
assertThat(
new FixedHourSchedule("02:00:00", ectZone)
.durationUntilNextExecutionInMillis(oneSecAfterTimeChangeMillis, null)
).isEqualTo(25 * 60 * 60 * 1000 - 1000);
}
@Test
public void should_not_return_current_time_if_last_execution_equals_current_time() {
ZoneId ectZone = ZoneId.of("Europe/Paris");
ZonedDateTime augustMidnight = LocalDate
.of(2016, 8, 31)
.atStartOfDay()
.atZone(ectZone);
long midnight = augustMidnight.toEpochSecond() * 1000;
assertThat(
new FixedHourSchedule("00:00:00", ectZone).durationUntilNextExecutionInMillis(midnight, midnight)
).isEqualTo(24 * 60 * 60 * 1000);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/cron/CronScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/cron/CronScheduleTest.java | package com.coreoz.wisp.schedule.cron;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
public class CronScheduleTest {
@Test
public void should_calcule_the_next_execution_time_based_on_a_unix_cron_expression() {
CronSchedule everyMinuteScheduler = CronSchedule.parseUnixCron("* * * * *");
assertThat(everyMinuteScheduler.nextExecutionInMillis(0, 0, null))
.isEqualTo(Duration.ofMinutes(1).toMillis());
}
@Test
public void should_calcule_the_next_execution_time_based_on_a_quartz_cron_expression() {
CronSchedule everyMinuteScheduler = CronSchedule.parseQuartzCron("0 * * * * ? *");
assertThat(everyMinuteScheduler.nextExecutionInMillis(0, 0, null))
.isEqualTo(Duration.ofMinutes(1).toMillis());
}
@Test
public void should_not_executed_daily_jobs_twice_a_day() {
CronSchedule everyMinuteScheduler = CronSchedule.parseQuartzCron("0 0 12 * * ? *");
ZonedDateTime augustMidday = LocalDate
.of(2016, 8, 31)
.atTime(12, 0)
.atZone(ZoneId.systemDefault());
long midday = augustMidday.toEpochSecond() * 1000;
assertThat(everyMinuteScheduler.nextExecutionInMillis(midday-1, 0, null))
.isEqualTo(midday);
assertThat(everyMinuteScheduler.nextExecutionInMillis(midday, 0, null))
.isEqualTo(midday + Duration.ofDays(1).toMillis());
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/test/java/com/coreoz/wisp/schedule/cron/CronExpressionScheduleTest.java | src/test/java/com/coreoz/wisp/schedule/cron/CronExpressionScheduleTest.java | package com.coreoz.wisp.schedule.cron;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Test;
public class CronExpressionScheduleTest {
@Test
public void should_calcule_the_next_execution_time_based_on_a_unix_cron_expression() {
CronExpressionSchedule everyMinuteScheduler = CronExpressionSchedule.parse("* * * * *");
// To ease calculations, next execution time are calculated from the timestamp "0".
// So here, the absolute timestamp for an execution in 1 minute will be 60
assertThat(everyMinuteScheduler.nextExecutionInMillis(0, 0, null))
.isEqualTo(Duration.ofMinutes(1).toMillis());
}
@Test
public void should_calcule_the_next_execution_time_based_on_a_unix_cron_expression_with_seconds() {
CronExpressionSchedule everyMinuteScheduler = CronExpressionSchedule.parseWithSeconds("29 * * * * *");
assertThat(everyMinuteScheduler.nextExecutionInMillis(0, 0, null))
// the first iteration will be the absolute timestamp "29"
.isEqualTo(Duration.ofSeconds(29).toMillis());
assertThat(everyMinuteScheduler.nextExecutionInMillis(29000 , 1, null))
// the second iteration will be the absolute timestamp "89"
.isEqualTo(Duration.ofSeconds(60 + 29).toMillis());
}
@Test
public void should_not_executed_daily_jobs_twice_a_day() {
CronExpressionSchedule everyMinuteScheduler = CronExpressionSchedule.parse("0 12 * * *");
ZonedDateTime augustMidday = LocalDate
.of(2016, 8, 31)
.atTime(12, 0)
.atZone(ZoneId.systemDefault());
long midday = augustMidday.toEpochSecond() * 1000;
assertThat(everyMinuteScheduler.nextExecutionInMillis(midday-1, 0, null))
.isEqualTo(midday);
assertThat(everyMinuteScheduler.nextExecutionInMillis(midday, 0, null))
.isEqualTo(midday + Duration.ofDays(1).toMillis());
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/Scheduler.java | src/main/java/com/coreoz/wisp/Scheduler.java | package com.coreoz.wisp;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.wisp.schedule.Schedule;
import com.coreoz.wisp.stats.SchedulerStats;
import com.coreoz.wisp.stats.ThreadPoolStats;
import com.coreoz.wisp.time.SystemTimeProvider;
import com.coreoz.wisp.time.TimeProvider;
import lombok.SneakyThrows;
/**
* A {@code Scheduler} instance reference a group of jobs
* and is responsible to schedule these jobs at the expected time.<br/>
* <br/>
* A job is executed only once at a time.
* The scheduler will never execute the same job twice at a time.
*/
public final class Scheduler implements AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(Scheduler.class);
/**
* @deprecated Default values are available in {@link SchedulerConfig}
* It will be deleted in version 3.0.0.
*/
@Deprecated
public static final int DEFAULT_THREAD_POOL_SIZE = 10;
/**
* @deprecated This value is not used anymore
* It will be deleted in version 3.0.0.
*/
@Deprecated
public static final long DEFAULT_MINIMUM_DELAY_IN_MILLIS_TO_REPLACE_JOB = 10L;
private final ThreadPoolExecutor threadPoolExecutor;
private final TimeProvider timeProvider;
private final AtomicBoolean launcherNotifier;
// jobs
private final Map<String, Job> indexedJobsByName;
private final ArrayList<Job> nextExecutionsOrder;
private final Map<String, CompletableFuture<Job>> cancelHandles;
private volatile boolean shuttingDown;
// constructors
/**
* Create a scheduler with the defaults defined at {@link SchedulerConfig}
*/
public Scheduler() {
this(SchedulerConfig.builder().build());
}
/**
* Create a scheduler with the defaults defined at {@link SchedulerConfig}
* and with a max number of worker threads
* @param maxThreads The maximum number of worker threads that can be created for the scheduler.
* @throws IllegalArgumentException if {@code maxThreads <= 0}
*/
public Scheduler(int maxThreads) {
this(SchedulerConfig.builder().maxThreads(maxThreads).build());
}
/**
* Create a scheduler according to the configuration
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code SchedulerConfig#getMinThreads() < 0}<br>
* {@code SchedulerConfig#getThreadsKeepAliveTime() < 0}<br>
* {@code SchedulerConfig#getMaxThreads() <= 0}<br>
* {@code SchedulerConfig#getMaxThreads() < SchedulerConfig#getMinThreads()}
* @throws NullPointerException if {@code SchedulerConfig#getTimeProvider()} is {@code null}
*/
public Scheduler(SchedulerConfig config) {
if(config.getTimeProvider() == null) {
throw new NullPointerException("The timeProvider cannot be null");
}
this.indexedJobsByName = new ConcurrentHashMap<>();
this.nextExecutionsOrder = new ArrayList<>();
this.timeProvider = config.getTimeProvider();
this.launcherNotifier = new AtomicBoolean(true);
this.cancelHandles = new ConcurrentHashMap<>();
this.threadPoolExecutor = new ScalingThreadPoolExecutor(
config.getMinThreads(),
config.getMaxThreads(),
config.getThreadsKeepAliveTime().toMillis(),
TimeUnit.MILLISECONDS,
config.getThreadFactory().get()
);
// run job launcher thread
Thread launcherThread = new Thread(this::launcher, "Wisp Monitor");
if (launcherThread.isDaemon()) {
launcherThread.setDaemon(false);
}
launcherThread.start();
}
/**
* @deprecated Use {@link #Scheduler(SchedulerConfig)} to specify multiple configuration values.
* It will be deleted in version 3.0.0.
* @throws IllegalArgumentException if {@code maxThreads <= 0}
*/
@Deprecated
public Scheduler(int maxThreads, long minimumDelayInMillisToReplaceJob) {
this(maxThreads, minimumDelayInMillisToReplaceJob, new SystemTimeProvider());
}
/**
* @deprecated Use {@link #Scheduler(SchedulerConfig)} to specify multiple configuration values.
* It will be deleted in version 3.0.0.
* @throws IllegalArgumentException if {@code maxThreads <= 0}
* @throws NullPointerException if {@code timeProvider} is {@code null}
*/
@Deprecated
public Scheduler(int maxThreads, long minimumDelayInMillisToReplaceJob,
TimeProvider timeProvider) {
this(SchedulerConfig
.builder()
.maxThreads(maxThreads)
.timeProvider(timeProvider)
.build()
);
}
// public API
/**
* Schedule the executions of a process.
*
* @param runnable The process to be executed at a schedule
* @param when The {@link Schedule} at which the process will be executed
* @return The corresponding {@link Job} created.
* @throws NullPointerException if {@code runnable} or {@code when} are {@code null}
* @throws IllegalArgumentException if the same instance of {@code runnable} is
* scheduled twice whereas the corresponding job status is not {@link JobStatus#DONE}
*/
public Job schedule(Runnable runnable, Schedule when) {
return schedule(null, runnable, when);
}
/**
* Schedule the executions of a process.<br>
* <br>
* If a job already exists with the same name and has the status {@link JobStatus#DONE},
* then the created job will inherit the stats of the existing done job:
* {@link Job#executionsCount()} and {@link Job#lastExecutionTimeInMillis()}
*
* @param nullableName The name of the created job
* @param runnable The process to be executed at a schedule
* @param when The {@link Schedule} at which the process will be executed
* @return The corresponding {@link Job} created.
* @throws NullPointerException if {@code runnable} or {@code when} are {@code null}
* @throws IllegalArgumentException if the same {@code nullableName} is
* scheduled twice whereas the corresponding job status is not {@link JobStatus#DONE}
*/
public Job schedule(String nullableName, Runnable runnable, Schedule when) {
Objects.requireNonNull(runnable, "Runnable must not be null");
Objects.requireNonNull(when, "Schedule must not be null");
String name = nullableName == null ? runnable.toString() : nullableName;
Job job = prepareJob(name, runnable, when);
long currentTimeInMillis = timeProvider.currentTime();
if(when.nextExecutionInMillis(
currentTimeInMillis,
job.executionsCount(),
job.lastExecutionEndedTimeInMillis()
) < currentTimeInMillis) {
logger.warn("The job '{}' is scheduled at a paste date: it will never be executed", name);
}
logger.info("Scheduling job '{}' to run {}", job.name(), job.schedule());
scheduleNextExecution(job);
return job;
}
/**
* Fetch the status of all the jobs that has been registered on the {@code Scheduler}
* including the {@link JobStatus#DONE} jobs
*/
public Collection<Job> jobStatus() {
return indexedJobsByName.values();
}
/**
* Find a job by its name
*/
public Optional<Job> findJob(String name) {
return Optional.ofNullable(indexedJobsByName.get(name));
}
/**
* Issue a cancellation order for a job and
* returns immediately a promise that enables to follow the job cancellation status<br>
* <br>
* If the job is running, the scheduler will wait until it is finished to remove it
* from the jobs pool.
* If the job is not running, the job will just be removed from the pool.<br>
* After the job is cancelled, the job has the status {@link JobStatus#DONE}.
*
* @param jobName The job name to cancel
* @return The promise that succeed when the job is correctly cancelled
* and will not be executed again. If the job is running when <code>cancel(String)</code>
* is called, the promise will succeed when the job has finished executing.
* @throws IllegalArgumentException if there is no job corresponding to the job name.
*/
public CompletionStage<Job> cancel(String jobName) {
Job job = findJob(jobName).orElseThrow(IllegalArgumentException::new);
synchronized (this) {
JobStatus jobStatus = job.status();
if(jobStatus == JobStatus.DONE) {
return CompletableFuture.completedFuture(job);
}
CompletableFuture<Job> existingHandle = cancelHandles.get(jobName);
if(existingHandle != null) {
return existingHandle;
}
job.schedule(Schedule.willNeverBeExecuted);
if(jobStatus == JobStatus.READY && threadPoolExecutor.remove(job.runningJob())) {
scheduleNextExecution(job);
return CompletableFuture.completedFuture(job);
}
if(jobStatus == JobStatus.RUNNING
// if the job status is/was READY but could not be removed from the thread pool,
// then we have to wait for it to finish
|| jobStatus == JobStatus.READY) {
CompletableFuture<Job> promise = new CompletableFuture<>();
cancelHandles.put(jobName, promise);
return promise;
} else {
for (Iterator<Job> iterator = nextExecutionsOrder.iterator(); iterator.hasNext();) {
Job nextJob = iterator.next();
if(nextJob == job) {
iterator.remove();
job.status(JobStatus.DONE);
return CompletableFuture.completedFuture(job);
}
}
throw new IllegalStateException(
"Cannot find the job " + job + " in " + nextExecutionsOrder
+ ". Please open an issue on https://github.com/Coreoz/Wisp/issues"
);
}
}
}
/**
* Remove a terminated job, so with the status {@link JobStatus#DONE}),
* from the monitored jobs. The monitored jobs are the ones
* still referenced using {@link #jobStatus()}.<br>
* <br>
* This can be useful to avoid memory leak in case many jobs
* with a short lifespan are created.
* @param jobName The job name to remove
* @throws IllegalArgumentException If there is no job corresponding to the job name or if the job is not on the status {@link JobStatus#DONE})
*/
public void remove(String jobName) {
Job jobToRemove = indexedJobsByName.get(jobName);
if (jobToRemove == null) {
throw new IllegalArgumentException("There is no existing job with the name " + jobName);
}
if(jobToRemove.status() != JobStatus.DONE) {
throw new IllegalArgumentException("Job is not terminated. Need to call the cancel() method before trying to remove it?");
}
indexedJobsByName.remove(jobName);
}
/**
* Wait until the current running jobs are executed
* and cancel jobs that are planned to be executed.
* There is a 10 seconds timeout
* @throws InterruptedException if the shutdown lasts more than 10 seconds
*/
public void gracefullyShutdown() {
gracefullyShutdown(Duration.ofSeconds(10));
}
/**
* Wait until the current running jobs are executed
* and cancel jobs that are planned to be executed.
* @param timeout The maximum time to wait
* @throws InterruptedException if the shutdown lasts more than 10 seconds
*/
@SneakyThrows
public void gracefullyShutdown(Duration timeout) {
logger.info("Shutting down...");
if(!shuttingDown) {
synchronized (this) {
shuttingDown = true;
threadPoolExecutor.shutdown();
}
// stops jobs that have not yet started to be executed
for(Job job : jobStatus()) {
Runnable runningJob = job.runningJob();
if(runningJob != null) {
threadPoolExecutor.remove(runningJob);
}
job.status(JobStatus.DONE);
}
synchronized (launcherNotifier) {
launcherNotifier.set(false);
launcherNotifier.notify();
}
}
threadPoolExecutor.awaitTermination(timeout.toMillis(), TimeUnit.MILLISECONDS);
}
/**
* Fetch statistics about the current {@code Scheduler}
*/
public SchedulerStats stats() {
int activeThreads = threadPoolExecutor.getActiveCount();
return SchedulerStats.of(ThreadPoolStats.of(
threadPoolExecutor.getCorePoolSize(),
threadPoolExecutor.getMaximumPoolSize(),
activeThreads,
threadPoolExecutor.getPoolSize() - activeThreads,
threadPoolExecutor.getLargestPoolSize()
));
}
// internal
private Job prepareJob(String name, Runnable runnable, Schedule when) {
// lock needed to make sure 2 jobs with the same name are not submitted at the same time
synchronized (indexedJobsByName) {
Job lastJob = findJob(name).orElse(null);
if(lastJob != null && lastJob.status() != JobStatus.DONE) {
throw new IllegalArgumentException("A job is already scheduled with the name:" + name);
}
Job job = new Job(
JobStatus.SCHEDULED,
0L,
lastJob != null ? lastJob.executionsCount() : 0,
lastJob != null ? lastJob.lastExecutionStartedTimeInMillis() : null,
lastJob != null ? lastJob.lastExecutionEndedTimeInMillis() : null,
name,
when,
runnable
);
indexedJobsByName.put(name, job);
return job;
}
}
private synchronized void scheduleNextExecution(Job job) {
// clean up
job.runningJob(null);
// next execution time calculation
long currentTimeInMillis = timeProvider.currentTime();
try {
job.nextExecutionTimeInMillis(
job.schedule().nextExecutionInMillis(
currentTimeInMillis, job.executionsCount(), job.lastExecutionEndedTimeInMillis()
)
);
} catch (Throwable t) {
logger.error(
"An exception was raised during the job next execution time calculation,"
+ " therefore the job '{}' will not be executed again.",
job.name(),
t
);
job.nextExecutionTimeInMillis(Schedule.WILL_NOT_BE_EXECUTED_AGAIN);
}
// next execution planning
if(job.nextExecutionTimeInMillis() >= currentTimeInMillis) {
job.status(JobStatus.SCHEDULED);
nextExecutionsOrder.add(job);
nextExecutionsOrder.sort(Comparator.comparing(
Job::nextExecutionTimeInMillis
));
synchronized (launcherNotifier) {
launcherNotifier.set(false);
launcherNotifier.notify();
}
} else {
logger.info(
"Job '{}' will not be executed again since its next execution time, {}ms, is planned in the past",
job.name(),
Instant.ofEpochMilli(job.nextExecutionTimeInMillis())
);
job.status(JobStatus.DONE);
CompletableFuture<Job> cancelHandle = cancelHandles.remove(job.name());
if(cancelHandle != null) {
cancelHandle.complete(job);
}
}
}
/**
* The daemon that will be in charge of placing the jobs in the thread pool
* when they are ready to be executed.
*/
@SneakyThrows
private void launcher() {
while(!shuttingDown) {
Long timeBeforeNextExecution = null;
synchronized (this) {
if(nextExecutionsOrder.size() > 0) {
timeBeforeNextExecution = nextExecutionsOrder.get(0).nextExecutionTimeInMillis()
- timeProvider.currentTime();
}
}
if(timeBeforeNextExecution == null || timeBeforeNextExecution > 0L) {
synchronized (launcherNotifier) {
if(shuttingDown) {
return;
}
// If someone has notified the launcher
// then the launcher must check again the next job to execute.
// We must be sure not to miss any changes that would have
// happened after the timeBeforeNextExecution calculation.
if(launcherNotifier.get()) {
if(timeBeforeNextExecution == null) {
launcherNotifier.wait();
} else {
launcherNotifier.wait(timeBeforeNextExecution);
}
}
launcherNotifier.set(true);
}
} else {
synchronized (this) {
if(shuttingDown) {
return;
}
if(nextExecutionsOrder.size() > 0) {
Job jobToRun = nextExecutionsOrder.remove(0);
jobToRun.status(JobStatus.READY);
jobToRun.runningJob(() -> runJob(jobToRun));
if(threadPoolExecutor.getActiveCount() == threadPoolExecutor.getMaximumPoolSize()) {
logger.warn(
"Job thread pool is full, either tasks take too much time to execute"
+ " or either the thread pool is too small"
);
}
threadPoolExecutor.execute(jobToRun.runningJob());
}
}
}
}
}
/**
* The wrapper around a job that will be executed in the thread pool.
* It is especially in charge of logging, changing the job status
* and checking for the next job to be executed.
* @param jobToRun the job to execute
*/
private void runJob(Job jobToRun) {
long startExecutionTime = timeProvider.currentTime();
long timeBeforeNextExecution = jobToRun.nextExecutionTimeInMillis() - startExecutionTime;
if(timeBeforeNextExecution < 0) {
logger.debug("Job '{}' execution is {}ms late", jobToRun.name(), -timeBeforeNextExecution);
}
jobToRun.status(JobStatus.RUNNING);
jobToRun.lastExecutionStartedTimeInMillis(startExecutionTime);
jobToRun.threadRunningJob(Thread.currentThread());
try {
jobToRun.runnable().run();
} catch(Throwable t) {
logger.error("Error during job '{}' execution", jobToRun.name(), t);
}
jobToRun.executionsCount(jobToRun.executionsCount() + 1);
jobToRun.lastExecutionEndedTimeInMillis(timeProvider.currentTime());
jobToRun.threadRunningJob(null);
if(logger.isDebugEnabled()) {
logger.debug(
"Job '{}' executed in {}ms", jobToRun.name(),
timeProvider.currentTime() - startExecutionTime
);
}
if(shuttingDown) {
return;
}
synchronized (this) {
scheduleNextExecution(jobToRun);
}
}
@Override
public void close() {
gracefullyShutdown();
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/SchedulerConfig.java | src/main/java/com/coreoz/wisp/SchedulerConfig.java | package com.coreoz.wisp;
import java.time.Duration;
import java.util.concurrent.ThreadFactory;
import java.util.function.Supplier;
import com.coreoz.wisp.time.SystemTimeProvider;
import com.coreoz.wisp.time.TimeProvider;
import lombok.Builder;
import lombok.Getter;
/**
* The configuration used by the scheduler
*/
@Getter
@Builder
public class SchedulerConfig {
public static final TimeProvider DEFAULT_TIME_PROVIDER = new SystemTimeProvider();
private static final Duration NON_EXPIRABLE_THREADS = Duration.ofMillis(Long.MAX_VALUE);
/**
* The minimum number of threads that will live in the jobs threads pool.
*/
@Builder.Default private final int minThreads = 0;
/**
* The maximum number of threads that will live in the jobs threads pool.
*/
@Builder.Default private final int maxThreads = 10;
/**
* The time after which idle threads will be removed from the threads pool.
* By default the thread pool does not scale down (duration = infinity ~ {@link Long#MAX_VALUE}ms)
*/
@Builder.Default private final Duration threadsKeepAliveTime = NON_EXPIRABLE_THREADS;
/**
* The time provider that will be used by the scheduler
*/
@Builder.Default private final TimeProvider timeProvider = DEFAULT_TIME_PROVIDER;
/**
* The thread factory used to create worker threads on which jobs will be executed
*/
@Builder.Default private final Supplier<ThreadFactory> threadFactory = WispThreadFactory::new;
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/LongRunningJobMonitor.java | src/main/java/com/coreoz/wisp/LongRunningJobMonitor.java | package com.coreoz.wisp;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.coreoz.wisp.time.TimeProvider;
import lombok.AllArgsConstructor;
/**
* Detect jobs that are running for too long.
* When a job is running for too long, a warning message is being logged.
*/
public class LongRunningJobMonitor implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(LongRunningJobMonitor.class);
public static final Duration DEFAULT_THRESHOLD_DETECTION = Duration.ofMinutes(5);
private final Scheduler scheduler;
private final TimeProvider timeProvider;
private final long detectionThresholdInMillis;
private final Map<Job, LongRunningJobInfo> longRunningJobs;
/**
* Create a new {@link LongRunningJobMonitor}.
* @param scheduler The scheduler that will be monitored
* @param detectionThreshold The threshold after which a message will be logged if the job takes longer to execute
* @param timeProvider The time provider used to calculate long running jobs
*/
public LongRunningJobMonitor(Scheduler scheduler, Duration detectionThreshold, TimeProvider timeProvider) {
this.scheduler = scheduler;
this.timeProvider = timeProvider;
this.detectionThresholdInMillis = detectionThreshold.toMillis();
this.longRunningJobs = new HashMap<>();
}
/**
* Create a new {@link LongRunningJobMonitor}.
* @param scheduler The scheduler that will be monitored
* @param detectionThreshold The threshold after which a message will be logged if the job takes longer to execute
*/
public LongRunningJobMonitor(Scheduler scheduler, Duration detectionThreshold) {
this(scheduler, detectionThreshold, SchedulerConfig.DEFAULT_TIME_PROVIDER);
}
/**
* Create a new {@link LongRunningJobMonitor} with a 5 minutes detection threshold.
* @param scheduler The scheduler that will be monitored
*/
public LongRunningJobMonitor(Scheduler scheduler) {
this(scheduler, DEFAULT_THRESHOLD_DETECTION, SchedulerConfig.DEFAULT_TIME_PROVIDER);
}
/**
* Run the too long jobs detection on the {@link Scheduler}.
* This method is *not* thread safe.
*/
@Override
public void run() {
long currentTime = timeProvider.currentTime();
for(Job job : scheduler.jobStatus()) {
cleanUpLongJobIfItHasFinishedExecuting(currentTime, job);
detectLongRunningJob(currentTime, job);
}
}
/**
* Check whether a job is running for too long or not.
*
* @return true if the is running for too long, else false.
* Returned value is made available for testing purposes.
*/
boolean detectLongRunningJob(long currentTime, Job job) {
if(job.status() == JobStatus.RUNNING && !longRunningJobs.containsKey(job)) {
int jobExecutionsCount = job.executionsCount();
Long jobStartedtimeInMillis = job.lastExecutionStartedTimeInMillis();
Thread threadRunningJob = job.threadRunningJob();
if(jobStartedtimeInMillis != null
&& threadRunningJob != null
&& currentTime - jobStartedtimeInMillis > detectionThresholdInMillis) {
logger.warn(
"Job '{}' is still running after {}ms (detection threshold = {}ms), stack trace = {}",
job.name(),
currentTime - jobStartedtimeInMillis,
detectionThresholdInMillis,
Stream
.of(threadRunningJob.getStackTrace())
.map(StackTraceElement::toString)
.collect(Collectors.joining("\n "))
);
longRunningJobs.put(
job,
new LongRunningJobInfo(jobStartedtimeInMillis, jobExecutionsCount)
);
return true;
}
}
return false;
}
/**
* cleanup jobs that have finished executing after {@link #thresholdDetectionInMillis}
*/
Long cleanUpLongJobIfItHasFinishedExecuting(long currentTime, Job job) {
if(longRunningJobs.containsKey(job)
&& longRunningJobs.get(job).executionsCount != job.executionsCount()) {
Long jobLastExecutionTimeInMillis = job.lastExecutionEndedTimeInMillis();
int jobExecutionsCount = job.executionsCount();
LongRunningJobInfo jobRunningInfo = longRunningJobs.get(job);
long jobExecutionDuration = 0L;
if(jobExecutionsCount == jobRunningInfo.executionsCount + 1) {
jobExecutionDuration = jobLastExecutionTimeInMillis - jobRunningInfo.jobStartedtimeInMillis;
logger.info(
"Job '{}' has finished executing after {}ms",
job.name(),
jobExecutionDuration
);
} else {
jobExecutionDuration = currentTime - jobRunningInfo.jobStartedtimeInMillis;
logger.info(
"Job '{}' has finished executing after about {}ms",
job.name(),
jobExecutionDuration
);
}
longRunningJobs.remove(job);
return jobExecutionDuration;
}
return null;
}
@AllArgsConstructor
private static class LongRunningJobInfo {
final long jobStartedtimeInMillis;
final int executionsCount;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/WispThreadFactory.java | src/main/java/com/coreoz/wisp/WispThreadFactory.java | package com.coreoz.wisp;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The default {@link ThreadFactory} for Wisp {@link Scheduler}
*/
class WispThreadFactory implements ThreadFactory {
private static final AtomicInteger threadCounter = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "Wisp Scheduler Worker #" + threadCounter.getAndIncrement());
if (thread.isDaemon()) {
thread.setDaemon(false);
}
if (thread.getPriority() != Thread.NORM_PRIORITY) {
thread.setPriority(Thread.NORM_PRIORITY);
}
return thread;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/Job.java | src/main/java/com/coreoz/wisp/Job.java | package com.coreoz.wisp;
import java.time.Instant;
import com.coreoz.wisp.schedule.Schedule;
/**
* A {@code Job} is the association of a {@link Runnable} process
* and its running {@link Schedule}.<br/>
* <br/>
* A {@code Job} also contains information about its status and its running
* statistics.
*/
public class Job {
private JobStatus status;
private volatile long nextExecutionTimeInMillis;
private volatile int executionsCount;
private Long lastExecutionStartedTimeInMillis;
private Long lastExecutionEndedTimeInMillis;
private Thread threadRunningJob;
private final String name;
private Schedule schedule;
private final Runnable runnable;
private Runnable runningJob;
// public API
public JobStatus status() {
return status;
}
public long nextExecutionTimeInMillis() {
return nextExecutionTimeInMillis;
}
public int executionsCount() {
return executionsCount;
}
/**
* The timestamp of when the job has last been started.
*/
public Long lastExecutionStartedTimeInMillis() {
return lastExecutionStartedTimeInMillis;
}
/**
* The timestamp of when the job has last been started.
*
* @deprecated Use {@link #lastExecutionStartedTimeInMillis()}.
* This method will be deleted in version 3.0.0.
*/
@Deprecated
public Long timeInMillisSinceJobRunning() {
return lastExecutionStartedTimeInMillis;
}
/**
* The timestamp of when the job has last finished executing.
*/
public Long lastExecutionEndedTimeInMillis() {
return lastExecutionEndedTimeInMillis;
}
/**
* The timestamp of when the job has last finished executing.
* @deprecated Use {@link #lastExecutionEndedTimeInMillis()}.
* This method will be deleted in version 3.0.0.
*/
@Deprecated
public Long lastExecutionTimeInMillis() {
return lastExecutionEndedTimeInMillis;
}
public Thread threadRunningJob() {
return threadRunningJob;
}
public String name() {
return name;
}
public Schedule schedule() {
return schedule;
}
public Runnable runnable() {
return runnable;
}
// package API
Job(JobStatus status, long nextExecutionTimeInMillis, int executionsCount,
Long lastExecutionStartedTimeInMillis, Long lastExecutionEndedTimeInMillis,
String name, Schedule schedule, Runnable runnable) {
this.status = status;
this.nextExecutionTimeInMillis = nextExecutionTimeInMillis;
this.executionsCount = executionsCount;
this.lastExecutionStartedTimeInMillis = lastExecutionStartedTimeInMillis;
this.lastExecutionEndedTimeInMillis = lastExecutionEndedTimeInMillis;
this.name = name;
this.schedule = schedule;
this.runnable = runnable;
}
void status(JobStatus status) {
this.status = status;
}
void nextExecutionTimeInMillis(long nextExecutionTimeInMillis) {
this.nextExecutionTimeInMillis = nextExecutionTimeInMillis;
}
void executionsCount(int executionsCount) {
this.executionsCount = executionsCount;
}
void lastExecutionStartedTimeInMillis(Long lastExecutionStartedTimeInMillis) {
this.lastExecutionStartedTimeInMillis = lastExecutionStartedTimeInMillis;
}
void lastExecutionEndedTimeInMillis(Long lastExecutionEndedTimeInMillis) {
this.lastExecutionEndedTimeInMillis = lastExecutionEndedTimeInMillis;
}
void threadRunningJob(Thread threadRunningJob) {
this.threadRunningJob = threadRunningJob;
}
void schedule(Schedule schedule) {
this.schedule = schedule;
}
void runningJob(Runnable runningJob) {
this.runningJob = runningJob;
}
Runnable runningJob() {
return runningJob;
}
// toString
@Override
public String toString() {
return "Job " + name + " [" + status + "] - will run " + schedule
+ " - next execution at " + Instant.ofEpochMilli(nextExecutionTimeInMillis);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/JobStatus.java | src/main/java/com/coreoz/wisp/JobStatus.java | package com.coreoz.wisp;
/**
* Describe a {@link Job} state
*/
public enum JobStatus {
/**
* The job will not be run ever again
*/
DONE,
/**
* The job will be executed at his scheduled time
*/
SCHEDULED,
/**
* This is an intermediate status before {@link #RUNNING},
* it means that the job is placed on the thread pool executor
* and is waiting to be executed as soon as a thread is available.
* This status should not last more than a few µs/ms except if the
* thread pool is full and running tasks are not terminating.
*/
READY,
/**
* The job is currently running
*/
RUNNING,
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/ScalingThreadPoolExecutor.java | src/main/java/com/coreoz/wisp/ScalingThreadPoolExecutor.java | package com.coreoz.wisp;
import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TransferQueue;
/**
* A thread pool executor that will reuse newly created threads
* instead of building them when {@code maxPoolSize} is reached.<br>
* <br>
* Credits to Mohammad Nadeem.
* @see <a href="https://reachmnadeem.wordpress.com/2017/01/15/scalable-java-tpe/">
* https://reachmnadeem.wordpress.com/2017/01/15/scalable-java-tpe/
* </a>
*/
final class ScalingThreadPoolExecutor extends ThreadPoolExecutor {
ScalingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit keepAliveUnit, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, keepAliveUnit,
new DynamicBlockingQueue<>(new LinkedTransferQueue<Runnable>()), threadFactory, new ForceQueuePolicy());
}
@Override
public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
throw new IllegalArgumentException("Cant set rejection handler");
}
private static class ForceQueuePolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
try {
// Rejected work add to Queue.
executor.getQueue().put(r);
} catch (InterruptedException e) {
// should never happen since we never wait
throw new RejectedExecutionException(e);
}
}
}
private static class DynamicBlockingQueue<E> implements TransferQueue<E> {
private final TransferQueue<E> delegate;
public DynamicBlockingQueue(final TransferQueue<E> delegate) {
this.delegate = delegate;
}
@Override
public boolean offer(E o) {
return tryTransfer(o);
}
@Override
public boolean add(E o) {
if (this.delegate.add(o)) {
return true;
} else {// Not possible in our case
throw new IllegalStateException("Queue full");
}
}
@Override
public E remove() {
return this.delegate.remove();
}
@Override
public E poll() {
return this.delegate.poll();
}
@Override
public E element() {
return this.delegate.element();
}
@Override
public E peek() {
return this.delegate.peek();
}
@Override
public int size() {
return this.delegate.size();
}
@Override
public boolean isEmpty() {
return this.delegate.isEmpty();
}
@Override
public Iterator<E> iterator() {
return this.delegate.iterator();
}
@Override
public Object[] toArray() {
return this.delegate.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return this.delegate.toArray(a);
}
@Override
public boolean containsAll(Collection<?> c) {
return this.delegate.containsAll(c);
}
@Override
public boolean addAll(Collection<? extends E> c) {
return this.delegate.addAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return this.delegate.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return this.delegate.retainAll(c);
}
@Override
public void clear() {
this.delegate.clear();
}
@Override
public void put(E e) throws InterruptedException {
this.delegate.put(e);
}
@Override
public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return this.delegate.offer(e, timeout, unit);
}
@Override
public E take() throws InterruptedException {
return this.delegate.take();
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
return this.delegate.poll(timeout, unit);
}
@Override
public int remainingCapacity() {
return this.delegate.remainingCapacity();
}
@Override
public boolean remove(Object o) {
return this.delegate.remove(o);
}
@Override
public boolean contains(Object o) {
return this.delegate.contains(o);
}
@Override
public int drainTo(Collection<? super E> c) {
return this.delegate.drainTo(c);
}
@Override
public int drainTo(Collection<? super E> c, int maxElements) {
return this.delegate.drainTo(c, maxElements);
}
@Override
public boolean tryTransfer(E e) {
return this.delegate.tryTransfer(e);
}
@Override
public void transfer(E e) throws InterruptedException {
this.delegate.transfer(e);
}
@Override
public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException {
return this.delegate.tryTransfer(e, timeout, unit);
}
@Override
public boolean hasWaitingConsumer() {
return this.delegate.hasWaitingConsumer();
}
@Override
public int getWaitingConsumerCount() {
return this.delegate.getWaitingConsumerCount();
}
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/stats/SchedulerStats.java | src/main/java/com/coreoz/wisp/stats/SchedulerStats.java | package com.coreoz.wisp.stats;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor(staticName = "of")
public class SchedulerStats {
private final ThreadPoolStats threadPoolStats;
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/stats/ThreadPoolStats.java | src/main/java/com/coreoz/wisp/stats/ThreadPoolStats.java | package com.coreoz.wisp.stats;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor(staticName = "of")
public class ThreadPoolStats {
private final int minThreads;
private final int maxThreads;
private final int activeThreads;
private final int idleThreads;
private final int largestPoolSize;
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/time/SystemTimeProvider.java | src/main/java/com/coreoz/wisp/time/SystemTimeProvider.java | package com.coreoz.wisp.time;
public class SystemTimeProvider implements TimeProvider {
@Override
public long currentTime() {
return System.currentTimeMillis();
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/time/TimeProvider.java | src/main/java/com/coreoz/wisp/time/TimeProvider.java | package com.coreoz.wisp.time;
/**
* The time provider that will be used by the scheduler to plan jobs
*/
public interface TimeProvider {
/**
* Returns the current time in milliseconds
*/
long currentTime();
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/FixedFrequencySchedule.java | src/main/java/com/coreoz/wisp/schedule/FixedFrequencySchedule.java | package com.coreoz.wisp.schedule;
import java.time.Duration;
public class FixedFrequencySchedule implements Schedule {
private final Duration frequency;
public FixedFrequencySchedule(Duration frequency) {
this.frequency = frequency;
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionEndedTimeInMillis) {
return currentTimeInMillis + frequency.toMillis() - (currentTimeInMillis % frequency.toMillis());
}
@Override
public String toString() {
return "every " + frequency.toMillis() + "ms";
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/AfterInitialDelaySchedule.java | src/main/java/com/coreoz/wisp/schedule/AfterInitialDelaySchedule.java | package com.coreoz.wisp.schedule;
import java.time.Duration;
public class AfterInitialDelaySchedule implements Schedule {
private final Schedule baseSchedule;
private final Duration initialDelay;
private Integer initialExecutionsCount;
private boolean hasNotBeenExecuted;
public AfterInitialDelaySchedule(Schedule baseSchedule, Duration initialDelay) {
this.baseSchedule = baseSchedule;
this.initialDelay = initialDelay;
this.initialExecutionsCount = null;
this.hasNotBeenExecuted = true;
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
if(initialExecutionsCount == null) {
initialExecutionsCount = executionsCount;
}
if(initialExecutionsCount >= executionsCount) {
return initialDelay.toMillis() + currentTimeInMillis;
}
hasNotBeenExecuted = false;
return baseSchedule.nextExecutionInMillis(currentTimeInMillis, executionsCount, lastExecutionTimeInMillis);
}
public Schedule baseSchedule() {
return baseSchedule;
}
@Override
public String toString() {
if(hasNotBeenExecuted) {
return "first after " + initialDelay + ", then " + baseSchedule;
}
return baseSchedule.toString();
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/FixedHourSchedule.java | src/main/java/com/coreoz/wisp/schedule/FixedHourSchedule.java | package com.coreoz.wisp.schedule;
import java.time.Instant;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class FixedHourSchedule implements Schedule {
private final LocalTime executionTime;
private final ZoneId zoneId;
/**
* Parse time in the form of "hh:mm" or "hh:mm:ss"
*/
public FixedHourSchedule(String every) {
this(LocalTime.parse(every));
}
/**
* Parse time in the form of "hh:mm" or "hh:mm:ss"
*/
public FixedHourSchedule(String every, ZoneId zoneId) {
this(LocalTime.parse(every), zoneId);
}
public FixedHourSchedule(LocalTime every) {
this(every, ZoneId.systemDefault());
}
public FixedHourSchedule(LocalTime every, ZoneId zoneId) {
this.executionTime = every;
this.zoneId = zoneId;
}
public LocalTime executionTime() {
return executionTime;
}
public ZoneId zoneId() {
return zoneId;
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
return durationUntilNextExecutionInMillis(currentTimeInMillis, lastExecutionTimeInMillis)
+ currentTimeInMillis;
}
long durationUntilNextExecutionInMillis(long currentTimeInMillis, Long lastExecutionTimeInMillis) {
ZonedDateTime currentDateTime = Instant
.ofEpochMilli(currentTimeInMillis)
.atZone(zoneId);
return currentDateTime
.until(
nextExecutionDateTime(
currentDateTime,
lastExecutionTimeInMillis != null && lastExecutionTimeInMillis == currentTimeInMillis
),
ChronoUnit.MILLIS
);
}
private ZonedDateTime nextExecutionDateTime(ZonedDateTime currentDateTime, boolean nextExecutionShouldBeNextDay) {
if(!nextExecutionShouldBeNextDay && currentDateTime.toLocalTime().compareTo(executionTime) <= 0) {
return executionTime.atDate(currentDateTime.toLocalDate()).atZone(zoneId);
}
return executionTime.atDate(currentDateTime.toLocalDate()).plusDays(1).atZone(zoneId);
}
@Override
public String toString() {
return "at " + executionTime + " " + zoneId;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/FixedDelaySchedule.java | src/main/java/com/coreoz/wisp/schedule/FixedDelaySchedule.java | package com.coreoz.wisp.schedule;
import java.time.Duration;
public class FixedDelaySchedule implements Schedule {
private final Duration frequency;
public FixedDelaySchedule(Duration frequency) {
this.frequency = frequency;
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
return currentTimeInMillis + frequency.toMillis();
}
@Override
public String toString() {
return "every " + frequency.toMillis() + "ms";
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/Schedules.java | src/main/java/com/coreoz/wisp/schedule/Schedules.java | package com.coreoz.wisp.schedule;
import java.time.Duration;
/**
* Static helpers to build {@link Schedule}
*/
public class Schedules {
/**
* Execute a job at a fixed delay after each execution
*/
public static Schedule fixedDelaySchedule(Duration duration) {
return new FixedDelaySchedule(duration);
}
/**
* Execute a job at a fixed frequency which is guaranteed to be within 1ms of accuracy independent of system load
*/
public static Schedule fixedFrequencySchedule(Duration duration) {
return new FixedFrequencySchedule(duration);
}
/**
* Execute a job at the same time once a day.
* The time format must be "hh:mm" or "hh:mm:ss"
*/
public static Schedule executeAt(String time) {
return new FixedHourSchedule(time);
}
// composition schedules
public static Schedule executeOnce(Schedule schedule) {
return new OnceSchedule(schedule);
}
public static Schedule afterInitialDelay(Schedule schedule, Duration initialDelay) {
return new AfterInitialDelaySchedule(schedule, initialDelay);
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/OnceSchedule.java | src/main/java/com/coreoz/wisp/schedule/OnceSchedule.java | package com.coreoz.wisp.schedule;
public class OnceSchedule implements Schedule {
private final Schedule baseSchedule;
private Integer initialExecutionsCount;
public OnceSchedule(Schedule baseSchedule) {
this.baseSchedule = baseSchedule;
this.initialExecutionsCount = null;
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
if(initialExecutionsCount == null) {
initialExecutionsCount = executionsCount;
}
if(initialExecutionsCount < executionsCount) {
return WILL_NOT_BE_EXECUTED_AGAIN;
}
return baseSchedule.nextExecutionInMillis(currentTimeInMillis, executionsCount, lastExecutionTimeInMillis);
}
public Schedule baseSchedule() {
return baseSchedule;
}
@Override
public String toString() {
return "once, " + baseSchedule;
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/Schedule.java | src/main/java/com/coreoz/wisp/schedule/Schedule.java | package com.coreoz.wisp.schedule;
/**
* Provide the time of the next executions of a job.
* The implementations should be thread-safe.
* Moreover the same instance of a schedule should be usable on multiple jobs.
*/
public interface Schedule {
/**
* If the {@link #nextExecutionInMillis(long, int, Long)} returned value is {@code -1},
* then the corresponding job will not be executed again.
*/
static final long WILL_NOT_BE_EXECUTED_AGAIN = -1L;
/**
* A schedule that will always return {@link #WILL_NOT_BE_EXECUTED_AGAIN}.
*/
static final Schedule willNeverBeExecuted = (c, e, l) -> Schedule.WILL_NOT_BE_EXECUTED_AGAIN;
/**
* Compute the next execution time for a job.
* This method should be thread-safe.
*
* @param currentTimeInMillis The current time in milliseconds. This time must be used if
* a next execution is planned for the job
* @param executionsCount The number of times a job has already been executed
* @param lastExecutionEndedTimeInMillis The time at which the job has last been executed; will be null
* if the job has never been executed
* @return The time in milliseconds at which the job should execute next.
* This time must be relative to {@code currentTimeInMillis}.
* If the returned value is negative, the job will not be executed again.
*/
long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionEndedTimeInMillis);
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/cron/CronExpressionSchedule.java | src/main/java/com/coreoz/wisp/schedule/cron/CronExpressionSchedule.java | package com.coreoz.wisp.schedule.cron;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import com.coreoz.wisp.schedule.Schedule;
import fc.cron.CronExpression;
/**
* A {@link Schedule} based on a <a href="https://en.wikipedia.org/wiki/Cron#CRON_expression">
* Cron expression</a>.<br>
* <br>
* This class depends on <a href="https://github.com/frode-carlsen/cron">Cron library</a>,
* so this dependency has to be in the classpath in order to be able to use {@link CronExpressionSchedule}.
* Since the Cron library is marked as optional in Wisp, it has to be
* <a href="https://github.com/Coreoz/Wisp#cron">explicitly referenced in the project dependency configuration</a>
* (pom.xml, build.gradle, build.sbt etc.).<br>
* <br>
* See also {@link CronExpression} for format details and implementation.
*/
public class CronExpressionSchedule implements Schedule {
private final CronExpression cronExpression;
private final ZoneId zoneId;
public CronExpressionSchedule(CronExpression cronExpression, ZoneId zoneId) {
this.cronExpression = cronExpression;
this.zoneId = zoneId;
}
public CronExpressionSchedule(CronExpression cronExpression) {
this(cronExpression, ZoneId.systemDefault());
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
Instant currentInstant = Instant.ofEpochMilli(currentTimeInMillis);
try {
return cronExpression.nextTimeAfter(ZonedDateTime.ofInstant(
currentInstant,
zoneId
)).toEpochSecond() * 1000L;
} catch (IllegalArgumentException e) {
return Schedule.WILL_NOT_BE_EXECUTED_AGAIN;
}
}
@Override
public String toString() {
return cronExpression.toString();
}
/**
* Create a {@link Schedule} from a cron expression based on the Unix format,
* e.g. 1 * * * * for each minute.
*/
public static CronExpressionSchedule parse(String cronExpression) {
return new CronExpressionSchedule(CronExpression.createWithoutSeconds(cronExpression));
}
/**
* Create a {@link Schedule} from a cron expression based on the Unix format, but accepting a second field as the first one,
* e.g. 29 * * * * * for each minute at the second 29, for instance 12:05:29.
*/
public static CronExpressionSchedule parseWithSeconds(String cronExpression) {
return new CronExpressionSchedule(CronExpression.create(cronExpression));
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
Coreoz/Wisp | https://github.com/Coreoz/Wisp/blob/1076065124550231680c5ece56dbb281eeedcc1c/src/main/java/com/coreoz/wisp/schedule/cron/CronSchedule.java | src/main/java/com/coreoz/wisp/schedule/cron/CronSchedule.java | package com.coreoz.wisp.schedule.cron;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Locale;
import com.coreoz.wisp.schedule.Schedule;
import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.model.Cron;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
/**
* A {@link Schedule} based on a <a href="https://en.wikipedia.org/wiki/Cron#CRON_expression">
* cron expression</a>.<br/>
* <br/>
* This class depends on <a href="https://github.com/jmrozanec/cron-utils">cron-utils</a>,
* so this dependency have to be in the classpath in order to be able to use {@link CronSchedule}.
* Since cron-utils is marked as optional, it has to be explicitly referenced in the
* project dependency configuration (pom.xml, build.gradle, build.sbt etc.).
*
* @deprecated Use {@link CronExpressionScheduleTest} instead.
* This class has been deprecated to move away from cron-utils. See
* <a href="https://github.com/Coreoz/Wisp/issues/14">issue #14</a> for details.
*/
@Deprecated
public class CronSchedule implements Schedule {
private static final CronParser UNIX_CRON_PARSER = new CronParser(
CronDefinitionBuilder.instanceDefinitionFor(CronType.UNIX)
);
private static final CronParser QUARTZ_CRON_PARSER = new CronParser(
CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
);
private static final CronDescriptor ENGLISH_DESCRIPTOR = CronDescriptor.instance(Locale.ENGLISH);
private final ExecutionTime cronExpression;
private final String description;
private final ZoneId zoneId;
public CronSchedule(Cron cronExpression, ZoneId zoneId) {
this.cronExpression = ExecutionTime.forCron(cronExpression);
this.description = ENGLISH_DESCRIPTOR.describe(cronExpression);
this.zoneId = zoneId;
}
public CronSchedule(Cron cronExpression) {
this(cronExpression, ZoneId.systemDefault());
}
@Override
public long nextExecutionInMillis(long currentTimeInMillis, int executionsCount, Long lastExecutionTimeInMillis) {
Instant currentInstant = Instant.ofEpochMilli(currentTimeInMillis);
return cronExpression.timeToNextExecution(ZonedDateTime.ofInstant(
currentInstant,
zoneId
))
.map(durationBetweenNextExecution ->
currentInstant.plus(durationBetweenNextExecution).toEpochMilli()
)
.orElse(Schedule.WILL_NOT_BE_EXECUTED_AGAIN);
}
@Override
public String toString() {
return description;
}
/**
* Create a {@link Schedule} from a cron expression based on the Unix format,
* e.g. 1 * * * * for each minute.
*
* @deprecated Use {@link CronExpressionScheduleTest#parse(String)} instead
*/
@Deprecated
public static CronSchedule parseUnixCron(String cronExpression) {
return new CronSchedule(UNIX_CRON_PARSER.parse(cronExpression));
}
/**
* Create a {@link Schedule} from a cron expression based on the Quartz format,
* e.g. 0 * * * * ? * for each minute.
*
* @deprecated Use {@link CronExpressionScheduleTest#parse(String)}
* or {@link CronExpressionScheduleTest#parseWithSeconds(String)} instead
*/
@Deprecated
public static CronSchedule parseQuartzCron(String cronExpression) {
return new CronSchedule(QUARTZ_CRON_PARSER.parse(cronExpression));
}
}
| java | Apache-2.0 | 1076065124550231680c5ece56dbb281eeedcc1c | 2026-01-05T02:40:54.981061Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/.mvn/wrapper/MavenWrapperDownloader.java | fullstack/.mvn/wrapper/MavenWrapperDownloader.java | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL =
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: : " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/service/MailServiceIntTest.java | fullstack/src/test/java/org/ehcache/sample/service/MailServiceIntTest.java | package org.ehcache.sample.service;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.domain.User;
import io.github.jhipster.config.JHipsterProperties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailSendException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.spring5.SpringTemplateEngine;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.ByteArrayOutputStream;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class MailServiceIntTest {
@Autowired
private JHipsterProperties jHipsterProperties;
@Autowired
private MessageSource messageSource;
@Autowired
private SpringTemplateEngine templateEngine;
@Spy
private JavaMailSenderImpl javaMailSender;
@Captor
private ArgumentCaptor<MimeMessage> messageCaptor;
private MailService mailService;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(javaMailSender).send(any(MimeMessage.class));
mailService = new MailService(jHipsterProperties, javaMailSender, messageSource, templateEngine);
}
@Test
public void testSendEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent().toString()).isEqualTo("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
public void testSendHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent()).isInstanceOf(String.class);
assertThat(message.getContent().toString()).isEqualTo("testContent");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendMultipartEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, false);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
@Test
public void testSendMultipartHtmlEmail() throws Exception {
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", true, true);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
MimeMultipart mp = (MimeMultipart) message.getContent();
MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
ByteArrayOutputStream aos = new ByteArrayOutputStream();
part.writeTo(aos);
assertThat(message.getSubject()).isEqualTo("testSubject");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo("john.doe@example.com");
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent()).isInstanceOf(Multipart.class);
assertThat(aos.toString()).isEqualTo("\r\ntestContent");
assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendEmailFromTemplate() throws Exception {
User user = new User();
user.setLogin("john");
user.setEmail("john.doe@example.com");
user.setLangKey("en");
mailService.sendEmailFromTemplate(user, "mail/testEmail", "email.test.title");
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getSubject()).isEqualTo("test title");
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent().toString()).isEqualToNormalizingNewlines("<html>test title, http://127.0.0.1:8080, john</html>\n");
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendActivationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendActivationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testCreationEmail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendCreationEmail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendPasswordResetMail() throws Exception {
User user = new User();
user.setLangKey(Constants.DEFAULT_LANGUAGE);
user.setLogin("john");
user.setEmail("john.doe@example.com");
mailService.sendPasswordResetMail(user);
verify(javaMailSender).send(messageCaptor.capture());
MimeMessage message = messageCaptor.getValue();
assertThat(message.getAllRecipients()[0].toString()).isEqualTo(user.getEmail());
assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
assertThat(message.getContent().toString()).isNotEmpty();
assertThat(message.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
@Test
public void testSendEmailWithException() throws Exception {
doThrow(MailSendException.class).when(javaMailSender).send(any(MimeMessage.class));
mailService.sendEmail("john.doe@example.com", "testSubject", "testContent", false, false);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/service/UserServiceIntTest.java | fullstack/src/test/java/org/ehcache/sample/service/UserServiceIntTest.java | package org.ehcache.sample.service;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.UserRepository;
import org.ehcache.sample.service.dto.UserDTO;
import org.ehcache.sample.service.util.RandomUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.auditing.AuditingHandler;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
/**
* Test class for the UserResource REST controller.
*
* @see UserService
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
@Transactional
public class UserServiceIntTest {
@Autowired
private UserRepository userRepository;
@Autowired
private UserService userService;
@Autowired
private AuditingHandler auditingHandler;
@Mock
DateTimeProvider dateTimeProvider;
private User user;
@Before
public void init() {
user = new User();
user.setLogin("johndoe");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setEmail("johndoe@localhost");
user.setFirstName("john");
user.setLastName("doe");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
when(dateTimeProvider.getNow()).thenReturn(Optional.of(LocalDateTime.now()));
auditingHandler.setDateTimeProvider(dateTimeProvider);
}
@Test
@Transactional
public void assertThatUserMustExistToResetPassword() {
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset("invalid.login@localhost");
assertThat(maybeUser).isNotPresent();
maybeUser = userService.requestPasswordReset(user.getEmail());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getEmail()).isEqualTo(user.getEmail());
assertThat(maybeUser.orElse(null).getResetDate()).isNotNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNotNull();
}
@Test
@Transactional
public void assertThatOnlyActivatedUserCanRequestPasswordReset() {
user.setActivated(false);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.requestPasswordReset(user.getLogin());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatResetKeyMustNotBeOlderThan24Hours() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatResetKeyMustBeValid() {
Instant daysAgo = Instant.now().minus(25, ChronoUnit.HOURS);
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey("1234");
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isNotPresent();
userRepository.delete(user);
}
@Test
@Transactional
public void assertThatUserCanResetPassword() {
String oldPassword = user.getPassword();
Instant daysAgo = Instant.now().minus(2, ChronoUnit.HOURS);
String resetKey = RandomUtil.generateResetKey();
user.setActivated(true);
user.setResetDate(daysAgo);
user.setResetKey(resetKey);
userRepository.saveAndFlush(user);
Optional<User> maybeUser = userService.completePasswordReset("johndoe2", user.getResetKey());
assertThat(maybeUser).isPresent();
assertThat(maybeUser.orElse(null).getResetDate()).isNull();
assertThat(maybeUser.orElse(null).getResetKey()).isNull();
assertThat(maybeUser.orElse(null).getPassword()).isNotEqualTo(oldPassword);
userRepository.delete(user);
}
@Test
@Transactional
public void testFindNotActivatedUsersByCreationDateBefore() {
Instant now = Instant.now();
when(dateTimeProvider.getNow()).thenReturn(Optional.of(now.minus(4, ChronoUnit.DAYS)));
user.setActivated(false);
User dbUser = userRepository.saveAndFlush(user);
dbUser.setCreatedDate(now.minus(4, ChronoUnit.DAYS));
userRepository.saveAndFlush(user);
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
assertThat(users).isNotEmpty();
userService.removeNotActivatedUsers();
users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(now.minus(3, ChronoUnit.DAYS));
assertThat(users).isEmpty();
}
@Test
@Transactional
public void assertThatAnonymousUserIsNotGet() {
user.setLogin(Constants.ANONYMOUS_USER);
if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
userRepository.saveAndFlush(user);
}
final PageRequest pageable = PageRequest.of(0, (int) userRepository.count());
final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
assertThat(allManagedUsers.getContent().stream()
.noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
.isTrue();
}
@Test
@Transactional
public void testRemoveNotActivatedUsers() {
// custom "now" for audit to use as creation date
when(dateTimeProvider.getNow()).thenReturn(Optional.of(Instant.now().minus(30, ChronoUnit.DAYS)));
user.setActivated(false);
userRepository.saveAndFlush(user);
assertThat(userRepository.findOneByLogin("johndoe")).isPresent();
userService.removeNotActivatedUsers();
assertThat(userRepository.findOneByLogin("johndoe")).isNotPresent();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/repository/CustomAuditEventRepositoryIntTest.java | fullstack/src/test/java/org/ehcache/sample/repository/CustomAuditEventRepositoryIntTest.java | package org.ehcache.sample.repository;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.config.audit.AuditEventConverter;
import org.ehcache.sample.domain.PersistentAuditEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.ehcache.sample.repository.CustomAuditEventRepository.EVENT_DATA_COLUMN_MAX_LENGTH;
/**
* Test class for the CustomAuditEventRepository class.
*
* @see CustomAuditEventRepository
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
@Transactional
public class CustomAuditEventRepositoryIntTest {
@Autowired
private PersistenceAuditEventRepository persistenceAuditEventRepository;
@Autowired
private AuditEventConverter auditEventConverter;
private CustomAuditEventRepository customAuditEventRepository;
private PersistentAuditEvent testUserEvent;
private PersistentAuditEvent testOtherUserEvent;
private PersistentAuditEvent testOldUserEvent;
@Before
public void setup() {
customAuditEventRepository = new CustomAuditEventRepository(persistenceAuditEventRepository, auditEventConverter);
persistenceAuditEventRepository.deleteAll();
Instant oneHourAgo = Instant.now().minusSeconds(3600);
testUserEvent = new PersistentAuditEvent();
testUserEvent.setPrincipal("test-user");
testUserEvent.setAuditEventType("test-type");
testUserEvent.setAuditEventDate(oneHourAgo);
Map<String, String> data = new HashMap<>();
data.put("test-key", "test-value");
testUserEvent.setData(data);
testOldUserEvent = new PersistentAuditEvent();
testOldUserEvent.setPrincipal("test-user");
testOldUserEvent.setAuditEventType("test-type");
testOldUserEvent.setAuditEventDate(oneHourAgo.minusSeconds(10000));
testOtherUserEvent = new PersistentAuditEvent();
testOtherUserEvent.setPrincipal("other-test-user");
testOtherUserEvent.setAuditEventType("test-type");
testOtherUserEvent.setAuditEventDate(oneHourAgo);
}
@Test
public void addAuditEvent() {
Map<String, Object> data = new HashMap<>();
data.put("test-key", "test-value");
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal());
assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType());
assertThat(persistentAuditEvent.getData()).containsKey("test-key");
assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("test-value");
assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp());
}
@Test
public void addAuditEventTruncateLargeData() {
Map<String, Object> data = new HashMap<>();
StringBuilder largeData = new StringBuilder();
for (int i = 0; i < EVENT_DATA_COLUMN_MAX_LENGTH + 10; i++) {
largeData.append("a");
}
data.put("test-key", largeData);
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getPrincipal()).isEqualTo(event.getPrincipal());
assertThat(persistentAuditEvent.getAuditEventType()).isEqualTo(event.getType());
assertThat(persistentAuditEvent.getData()).containsKey("test-key");
String actualData = persistentAuditEvent.getData().get("test-key");
assertThat(actualData.length()).isEqualTo(EVENT_DATA_COLUMN_MAX_LENGTH);
assertThat(actualData).isSubstringOf(largeData);
assertThat(persistentAuditEvent.getAuditEventDate()).isEqualTo(event.getTimestamp());
}
@Test
public void testAddEventWithWebAuthenticationDetails() {
HttpSession session = new MockHttpSession(null, "test-session-id");
MockHttpServletRequest request = new MockHttpServletRequest();
request.setSession(session);
request.setRemoteAddr("1.2.3.4");
WebAuthenticationDetails details = new WebAuthenticationDetails(request);
Map<String, Object> data = new HashMap<>();
data.put("test-key", details);
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getData().get("remoteAddress")).isEqualTo("1.2.3.4");
assertThat(persistentAuditEvent.getData().get("sessionId")).isEqualTo("test-session-id");
}
@Test
public void testAddEventWithNullData() {
Map<String, Object> data = new HashMap<>();
data.put("test-key", null);
AuditEvent event = new AuditEvent("test-user", "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(1);
PersistentAuditEvent persistentAuditEvent = persistentAuditEvents.get(0);
assertThat(persistentAuditEvent.getData().get("test-key")).isEqualTo("null");
}
@Test
public void addAuditEventWithAnonymousUser() {
Map<String, Object> data = new HashMap<>();
data.put("test-key", "test-value");
AuditEvent event = new AuditEvent(Constants.ANONYMOUS_USER, "test-type", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(0);
}
@Test
public void addAuditEventWithAuthorizationFailureType() {
Map<String, Object> data = new HashMap<>();
data.put("test-key", "test-value");
AuditEvent event = new AuditEvent("test-user", "AUTHORIZATION_FAILURE", data);
customAuditEventRepository.add(event);
List<PersistentAuditEvent> persistentAuditEvents = persistenceAuditEventRepository.findAll();
assertThat(persistentAuditEvents).hasSize(0);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/repository/timezone/DateTimeWrapper.java | fullstack/src/test/java/org/ehcache/sample/repository/timezone/DateTimeWrapper.java | package org.ehcache.sample.repository.timezone;
import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;
@Entity
@Table(name = "jhi_date_time_wrapper")
public class DateTimeWrapper implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "instant")
private Instant instant;
@Column(name = "local_date_time")
private LocalDateTime localDateTime;
@Column(name = "offset_date_time")
private OffsetDateTime offsetDateTime;
@Column(name = "zoned_date_time")
private ZonedDateTime zonedDateTime;
@Column(name = "local_time")
private LocalTime localTime;
@Column(name = "offset_time")
private OffsetTime offsetTime;
@Column(name = "local_date")
private LocalDate localDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Instant getInstant() {
return instant;
}
public void setInstant(Instant instant) {
this.instant = instant;
}
public LocalDateTime getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(LocalDateTime localDateTime) {
this.localDateTime = localDateTime;
}
public OffsetDateTime getOffsetDateTime() {
return offsetDateTime;
}
public void setOffsetDateTime(OffsetDateTime offsetDateTime) {
this.offsetDateTime = offsetDateTime;
}
public ZonedDateTime getZonedDateTime() {
return zonedDateTime;
}
public void setZonedDateTime(ZonedDateTime zonedDateTime) {
this.zonedDateTime = zonedDateTime;
}
public LocalTime getLocalTime() {
return localTime;
}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public OffsetTime getOffsetTime() {
return offsetTime;
}
public void setOffsetTime(OffsetTime offsetTime) {
this.offsetTime = offsetTime;
}
public LocalDate getLocalDate() {
return localDate;
}
public void setLocalDate(LocalDate localDate) {
this.localDate = localDate;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DateTimeWrapper dateTimeWrapper = (DateTimeWrapper) o;
return !(dateTimeWrapper.getId() == null || getId() == null) && Objects.equals(getId(), dateTimeWrapper.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "TimeZoneTest{" +
"id=" + id +
", instant=" + instant +
", localDateTime=" + localDateTime +
", offsetDateTime=" + offsetDateTime +
", zonedDateTime=" + zonedDateTime +
'}';
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/repository/timezone/DateTimeWrapperRepository.java | fullstack/src/test/java/org/ehcache/sample/repository/timezone/DateTimeWrapperRepository.java | package org.ehcache.sample.repository.timezone;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
/**
* Spring Data JPA repository for the DateTimeWrapper entity.
*/
@Repository
public interface DateTimeWrapperRepository extends JpaRepository<DateTimeWrapper, Long> {
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/security/DomainUserDetailsServiceIntTest.java | fullstack/src/test/java/org/ehcache/sample/security/DomainUserDetailsServiceIntTest.java | package org.ehcache.sample.security;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.UserRepository;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Locale;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for DomainUserDetailsService.
*
* @see DomainUserDetailsService
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
@Transactional
public class DomainUserDetailsServiceIntTest {
private static final String USER_ONE_LOGIN = "test-user-one";
private static final String USER_ONE_EMAIL = "test-user-one@localhost";
private static final String USER_TWO_LOGIN = "test-user-two";
private static final String USER_TWO_EMAIL = "test-user-two@localhost";
private static final String USER_THREE_LOGIN = "test-user-three";
private static final String USER_THREE_EMAIL = "test-user-three@localhost";
@Autowired
private UserRepository userRepository;
@Autowired
private UserDetailsService domainUserDetailsService;
private User userOne;
private User userTwo;
private User userThree;
@Before
public void init() {
userOne = new User();
userOne.setLogin(USER_ONE_LOGIN);
userOne.setPassword(RandomStringUtils.random(60));
userOne.setActivated(true);
userOne.setEmail(USER_ONE_EMAIL);
userOne.setFirstName("userOne");
userOne.setLastName("doe");
userOne.setLangKey("en");
userRepository.save(userOne);
userTwo = new User();
userTwo.setLogin(USER_TWO_LOGIN);
userTwo.setPassword(RandomStringUtils.random(60));
userTwo.setActivated(true);
userTwo.setEmail(USER_TWO_EMAIL);
userTwo.setFirstName("userTwo");
userTwo.setLastName("doe");
userTwo.setLangKey("en");
userRepository.save(userTwo);
userThree = new User();
userThree.setLogin(USER_THREE_LOGIN);
userThree.setPassword(RandomStringUtils.random(60));
userThree.setActivated(false);
userThree.setEmail(USER_THREE_EMAIL);
userThree.setFirstName("userThree");
userThree.setLastName("doe");
userThree.setLangKey("en");
userRepository.save(userThree);
}
@Test
@Transactional
public void assertThatUserCanBeFoundByLogin() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
@Transactional
public void assertThatUserCanBeFoundByLoginIgnoreCase() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_LOGIN.toUpperCase(Locale.ENGLISH));
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test
@Transactional
public void assertThatUserCanBeFoundByEmail() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_TWO_LOGIN);
}
@Test(expected = UsernameNotFoundException.class)
@Transactional
public void assertThatUserCanNotBeFoundByEmailIgnoreCase() {
domainUserDetailsService.loadUserByUsername(USER_TWO_EMAIL.toUpperCase(Locale.ENGLISH));
}
@Test
@Transactional
public void assertThatEmailIsPrioritizedOverLogin() {
UserDetails userDetails = domainUserDetailsService.loadUserByUsername(USER_ONE_EMAIL);
assertThat(userDetails).isNotNull();
assertThat(userDetails.getUsername()).isEqualTo(USER_ONE_LOGIN);
}
@Test(expected = UserNotActivatedException.class)
@Transactional
public void assertThatUserNotActivatedExceptionIsThrownForNotActivatedUsers() {
domainUserDetailsService.loadUserByUsername(USER_THREE_LOGIN);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/security/SecurityUtilsUnitTest.java | fullstack/src/test/java/org/ehcache/sample/security/SecurityUtilsUnitTest.java | package org.ehcache.sample.security;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the SecurityUtils utility class.
*
* @see SecurityUtils
*/
public class SecurityUtilsUnitTest {
@Test
public void testgetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
Optional<String> login = SecurityUtils.getCurrentUserLogin();
assertThat(login).contains("admin");
}
@Test
public void testgetCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "token"));
SecurityContextHolder.setContext(securityContext);
Optional<String> jwt = SecurityUtils.getCurrentUserJWT();
assertThat(jwt).contains("token");
}
@Test
public void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
public void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
@Test
public void testIsCurrentUserInRole() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("user", "user", authorities));
SecurityContextHolder.setContext(securityContext);
assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.USER)).isTrue();
assertThat(SecurityUtils.isCurrentUserInRole(AuthoritiesConstants.ADMIN)).isFalse();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/security/jwt/JWTFilterTest.java | fullstack/src/test/java/org/ehcache/sample/security/jwt/JWTFilterTest.java | package org.ehcache.sample.security.jwt;
import org.ehcache.sample.security.AuthoritiesConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class JWTFilterTest {
private TokenProvider tokenProvider;
private JWTFilter jwtFilter;
@Before
public void setup() {
JHipsterProperties jHipsterProperties = new JHipsterProperties();
tokenProvider = new TokenProvider(jHipsterProperties);
ReflectionTestUtils.setField(tokenProvider, "key",
Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")));
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
jwtFilter = new JWTFilter(tokenProvider);
SecurityContextHolder.getContext().setAuthentication(null);
}
@Test
public void testJWTFilter() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication().getName()).isEqualTo("test-user");
assertThat(SecurityContextHolder.getContext().getAuthentication().getCredentials().toString()).isEqualTo(jwt);
}
@Test
public void testJWTFilterInvalidToken() throws Exception {
String jwt = "wrong_jwt";
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterMissingAuthorization() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterMissingToken() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer ");
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
@Test
public void testJWTFilterWrongScheme() throws Exception {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
"test-user",
"test-password",
Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER))
);
String jwt = tokenProvider.createToken(authentication, false);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt);
request.setRequestURI("/api/test");
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterChain filterChain = new MockFilterChain();
jwtFilter.doFilter(request, response, filterChain);
assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value());
assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/security/jwt/TokenProviderTest.java | fullstack/src/test/java/org/ehcache/sample/security/jwt/TokenProviderTest.java | package org.ehcache.sample.security.jwt;
import org.ehcache.sample.security.AuthoritiesConstants;
import java.security.Key;
import java.util.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.test.util.ReflectionTestUtils;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import static org.assertj.core.api.Assertions.assertThat;
public class TokenProviderTest {
private final long ONE_MINUTE = 60000;
private Key key;
private JHipsterProperties jHipsterProperties;
private TokenProvider tokenProvider;
@Before
public void setup() {
jHipsterProperties = Mockito.mock(JHipsterProperties.class);
tokenProvider = new TokenProvider(jHipsterProperties);
key = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("fd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
ReflectionTestUtils.setField(tokenProvider, "key", key);
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", ONE_MINUTE);
}
@Test
public void testReturnFalseWhenJWThasInvalidSignature() {
boolean isTokenValid = tokenProvider.validateToken(createTokenWithDifferentSignature());
assertThat(isTokenValid).isEqualTo(false);
}
@Test
public void testReturnFalseWhenJWTisMalformed() {
Authentication authentication = createAuthentication();
String token = tokenProvider.createToken(authentication, false);
String invalidToken = token.substring(1);
boolean isTokenValid = tokenProvider.validateToken(invalidToken);
assertThat(isTokenValid).isEqualTo(false);
}
@Test
public void testReturnFalseWhenJWTisExpired() {
ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", -ONE_MINUTE);
Authentication authentication = createAuthentication();
String token = tokenProvider.createToken(authentication, false);
boolean isTokenValid = tokenProvider.validateToken(token);
assertThat(isTokenValid).isEqualTo(false);
}
@Test
public void testReturnFalseWhenJWTisUnsupported() {
String unsupportedToken = createUnsupportedToken();
boolean isTokenValid = tokenProvider.validateToken(unsupportedToken);
assertThat(isTokenValid).isEqualTo(false);
}
@Test
public void testReturnFalseWhenJWTisInvalid() {
boolean isTokenValid = tokenProvider.validateToken("");
assertThat(isTokenValid).isEqualTo(false);
}
private Authentication createAuthentication() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
return new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities);
}
private String createUnsupportedToken() {
return Jwts.builder()
.setPayload("payload")
.signWith(key, SignatureAlgorithm.HS512)
.compact();
}
private String createTokenWithDifferentSignature() {
Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64
.decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8"));
return Jwts.builder()
.setSubject("anonymous")
.signWith(otherKey, SignatureAlgorithm.HS512)
.setExpiration(new Date(new Date().getTime() + ONE_MINUTE))
.compact();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/config/WebConfigurerTestController.java | fullstack/src/test/java/org/ehcache/sample/config/WebConfigurerTestController.java | package org.ehcache.sample.config;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebConfigurerTestController {
@GetMapping("/api/test-cors")
public void testCorsOnApiPath() {
}
@GetMapping("/test/test-cors")
public void testCorsOnOtherPath() {
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/config/WebConfigurerTest.java | fullstack/src/test/java/org/ehcache/sample/config/WebConfigurerTest.java | package org.ehcache.sample.config;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.servlet.InstrumentedFilter;
import com.codahale.metrics.servlets.MetricsServlet;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.web.filter.CachingHttpHeadersFilter;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowOptions;
import org.apache.commons.io.FilenameUtils;
import org.h2.server.web.WebServlet;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.xnio.OptionMap;
import javax.servlet.*;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.options;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Unit tests for the WebConfigurer class.
*
* @see WebConfigurer
*/
public class WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.class))
.when(servletContext).addFilter(anyString(), any(Filter.class));
doReturn(mock(ServletRegistration.Dynamic.class))
.when(servletContext).addServlet(anyString(), any(Servlet.class));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
assertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
assertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.class));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.class));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.class));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.class));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDocumentRoot() != null) {
assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
options("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"))
.andExpect(header().string(HttpHeaders.VARY, "Origin"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/test/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController())
.addFilters(webConfigurer.corsFilter())
.build();
mockMvc.perform(
get("/api/test-cors")
.header(HttpHeaders.ORIGIN, "other.domain.com"))
.andExpect(status().isOk())
.andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/config/timezone/HibernateTimeZoneTest.java | fullstack/src/test/java/org/ehcache/sample/config/timezone/HibernateTimeZoneTest.java | package org.ehcache.sample.config.timezone;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.repository.timezone.DateTimeWrapper;
import org.ehcache.sample.repository.timezone.DateTimeWrapperRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.time.*;
import java.time.format.DateTimeFormatter;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for the UTC Hibernate configuration.
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class HibernateTimeZoneTest {
@Autowired
private DateTimeWrapperRepository dateTimeWrapperRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
private DateTimeWrapper dateTimeWrapper;
private DateTimeFormatter dateTimeFormatter;
private DateTimeFormatter timeFormatter;
private DateTimeFormatter dateFormatter;
@Before
public void setup() {
dateTimeWrapper = new DateTimeWrapper();
dateTimeWrapper.setInstant(Instant.parse("2014-11-12T05:50:00.0Z"));
dateTimeWrapper.setLocalDateTime(LocalDateTime.parse("2014-11-12T07:50:00.0"));
dateTimeWrapper.setOffsetDateTime(OffsetDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setZonedDateTime(ZonedDateTime.parse("2011-12-14T08:30:00.0Z"));
dateTimeWrapper.setLocalTime(LocalTime.parse("14:30:00"));
dateTimeWrapper.setOffsetTime(OffsetTime.parse("14:30:00+02:00"));
dateTimeWrapper.setLocalDate(LocalDate.parse("2016-09-10"));
dateTimeFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss.S")
.withZone(ZoneId.of("UTC"));
timeFormatter = DateTimeFormatter
.ofPattern("HH:mm:ss")
.withZone(ZoneId.of("UTC"));
dateFormatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd");
}
@Test
@Transactional
public void storeInstantWithUtcConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("instant", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeFormatter.format(dateTimeWrapper.getInstant());
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeLocalDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalDateTime()
.atZone(ZoneId.systemDefault())
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeOffsetDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetDateTime()
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeZoneDateTimeWithUtcConfigShouldBeStoredOnGMTTimeZone() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("zoned_date_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getZonedDateTime()
.format(dateTimeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeLocalTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeOffsetTimeWithUtcConfigShouldBeStoredOnGMTTimeZoneAccordingToHis1stJan1970Value() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("offset_time", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getOffsetTime()
.toLocalTime()
.atDate(LocalDate.of(1970, Month.JANUARY, 1))
.atZone(ZoneId.systemDefault())
.format(timeFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
@Test
@Transactional
public void storeLocalDateWithUtcConfigShouldBeStoredWithoutTransformation() {
dateTimeWrapperRepository.saveAndFlush(dateTimeWrapper);
String request = generateSqlRequest("local_date", dateTimeWrapper.getId());
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(request);
String expectedValue = dateTimeWrapper
.getLocalDate()
.format(dateFormatter);
assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(resultSet, expectedValue);
}
private String generateSqlRequest(String fieldName, long id) {
return format("SELECT %s FROM jhi_date_time_wrapper where id=%d", fieldName, id);
}
private void assertThatDateStoredValueIsEqualToInsertDateValueOnGMTTimeZone(SqlRowSet sqlRowSet, String expectedValue) {
while (sqlRowSet.next()) {
String dbValue = sqlRowSet.getString(1);
assertThat(dbValue).isNotNull();
assertThat(dbValue).isEqualTo(expectedValue);
}
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/AuditResourceIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/AuditResourceIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.config.audit.AuditEventConverter;
import org.ehcache.sample.domain.PersistentAuditEvent;
import org.ehcache.sample.repository.PersistenceAuditEventRepository;
import org.ehcache.sample.service.AuditEventService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AuditResource REST controller.
*
* @see AuditResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
@Transactional
public class AuditResourceIntTest {
private static final String SAMPLE_PRINCIPAL = "SAMPLE_PRINCIPAL";
private static final String SAMPLE_TYPE = "SAMPLE_TYPE";
private static final Instant SAMPLE_TIMESTAMP = Instant.parse("2015-08-04T10:11:30Z");
private static final long SECONDS_PER_DAY = 60 * 60 * 24;
@Autowired
private PersistenceAuditEventRepository auditEventRepository;
@Autowired
private AuditEventConverter auditEventConverter;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private FormattingConversionService formattingConversionService;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
private PersistentAuditEvent auditEvent;
private MockMvc restAuditMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
AuditEventService auditEventService =
new AuditEventService(auditEventRepository, auditEventConverter);
AuditResource auditResource = new AuditResource(auditEventService);
this.restAuditMockMvc = MockMvcBuilders.standaloneSetup(auditResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setConversionService(formattingConversionService)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void initTest() {
auditEventRepository.deleteAll();
auditEvent = new PersistentAuditEvent();
auditEvent.setAuditEventType(SAMPLE_TYPE);
auditEvent.setPrincipal(SAMPLE_PRINCIPAL);
auditEvent.setAuditEventDate(SAMPLE_TIMESTAMP);
}
@Test
public void getAllAudits() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get all the audits
restAuditMockMvc.perform(get("/management/audits"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
public void getAudit() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Get the audit
restAuditMockMvc.perform(get("/management/audits/{id}", auditEvent.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.principal").value(SAMPLE_PRINCIPAL));
}
@Test
public void getAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will contain the audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
String toDate = SAMPLE_TIMESTAMP.plusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
// Get the audit
restAuditMockMvc.perform(get("/management/audits?fromDate="+fromDate+"&toDate="+toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].principal").value(hasItem(SAMPLE_PRINCIPAL)));
}
@Test
public void getNonExistingAuditsByDate() throws Exception {
// Initialize the database
auditEventRepository.save(auditEvent);
// Generate dates for selecting audits by date, making sure the period will not contain the sample audit
String fromDate = SAMPLE_TIMESTAMP.minusSeconds(2*SECONDS_PER_DAY).toString().substring(0, 10);
String toDate = SAMPLE_TIMESTAMP.minusSeconds(SECONDS_PER_DAY).toString().substring(0, 10);
// Query audits but expect no results
restAuditMockMvc.perform(get("/management/audits?fromDate=" + fromDate + "&toDate=" + toDate))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(header().string("X-Total-Count", "0"));
}
@Test
public void getNonExistingAudit() throws Exception {
// Get the audit
restAuditMockMvc.perform(get("/management/audits/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void testPersistentAuditEventEquals() throws Exception {
TestUtil.equalsVerifier(PersistentAuditEvent.class);
PersistentAuditEvent auditEvent1 = new PersistentAuditEvent();
auditEvent1.setId(1L);
PersistentAuditEvent auditEvent2 = new PersistentAuditEvent();
auditEvent2.setId(auditEvent1.getId());
assertThat(auditEvent1).isEqualTo(auditEvent2);
auditEvent2.setId(2L);
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
auditEvent1.setId(null);
assertThat(auditEvent1).isNotEqualTo(auditEvent2);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/UserJWTControllerIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/UserJWTControllerIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.UserRepository;
import org.ehcache.sample.security.jwt.TokenProvider;
import org.ehcache.sample.web.rest.errors.ExceptionTranslator;
import org.ehcache.sample.web.rest.vm.LoginVM;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
/**
* Test class for the UserJWTController REST controller.
*
* @see UserJWTController
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class UserJWTControllerIntTest {
@Autowired
private TokenProvider tokenProvider;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private ExceptionTranslator exceptionTranslator;
private MockMvc mockMvc;
@Before
public void setup() {
UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager);
this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
@Transactional
public void testAuthorize() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller");
user.setEmail("user-jwt-controller@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller");
login.setPassword("test");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
@Transactional
public void testAuthorizeWithRememberMe() throws Exception {
User user = new User();
user.setLogin("user-jwt-controller-remember-me");
user.setEmail("user-jwt-controller-remember-me@example.com");
user.setActivated(true);
user.setPassword(passwordEncoder.encode("test"));
userRepository.saveAndFlush(user);
LoginVM login = new LoginVM();
login.setUsername("user-jwt-controller-remember-me");
login.setPassword("test");
login.setRememberMe(true);
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id_token").isString())
.andExpect(jsonPath("$.id_token").isNotEmpty())
.andExpect(header().string("Authorization", not(nullValue())))
.andExpect(header().string("Authorization", not(isEmptyString())));
}
@Test
@Transactional
public void testAuthorizeFails() throws Exception {
LoginVM login = new LoginVM();
login.setUsername("wrong-user");
login.setPassword("wrong password");
mockMvc.perform(post("/api/authenticate")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(login)))
.andExpect(status().isUnauthorized())
.andExpect(jsonPath("$.id_token").doesNotExist())
.andExpect(header().doesNotExist("Authorization"));
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/TestUtil.java | fullstack/src/test/java/org/ehcache/sample/web/rest/TestUtil.java | package org.ehcache.sample.web.rest;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Utility class for testing REST controllers.
*/
public class TestUtil {
/** MediaType for JSON UTF8 */
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), StandardCharsets.UTF_8);
/**
* Convert an object to JSON byte array.
*
* @param object
* the object to convert
* @return the JSON byte array
* @throws IOException
*/
public static byte[] convertObjectToJsonBytes(Object object)
throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
JavaTimeModule module = new JavaTimeModule();
mapper.registerModule(module);
return mapper.writeValueAsBytes(object);
}
/**
* Create a byte array with a specific size filled with specified data.
*
* @param size the size of the byte array
* @param data the data to put in the byte array
* @return the JSON byte array
*/
public static byte[] createByteArray(int size, String data) {
byte[] byteArray = new byte[size];
for (int i = 0; i < size; i++) {
byteArray[i] = Byte.parseByte(data, 2);
}
return byteArray;
}
/**
* A matcher that tests that the examined string represents the same instant as the reference datetime.
*/
public static class ZonedDateTimeMatcher extends TypeSafeDiagnosingMatcher<String> {
private final ZonedDateTime date;
public ZonedDateTimeMatcher(ZonedDateTime date) {
this.date = date;
}
@Override
protected boolean matchesSafely(String item, Description mismatchDescription) {
try {
if (!date.isEqual(ZonedDateTime.parse(item))) {
mismatchDescription.appendText("was ").appendValue(item);
return false;
}
return true;
} catch (DateTimeParseException e) {
mismatchDescription.appendText("was ").appendValue(item)
.appendText(", which could not be parsed as a ZonedDateTime");
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("a String representing the same Instant as ").appendValue(date);
}
}
/**
* Creates a matcher that matches when the examined string reprensents the same instant as the reference datetime
* @param date the reference datetime against which the examined string is checked
*/
public static ZonedDateTimeMatcher sameInstant(ZonedDateTime date) {
return new ZonedDateTimeMatcher(date);
}
/**
* Verifies the equals/hashcode contract on the domain object.
*/
public static <T> void equalsVerifier(Class<T> clazz) throws Exception {
T domainObject1 = clazz.getConstructor().newInstance();
assertThat(domainObject1.toString()).isNotNull();
assertThat(domainObject1).isEqualTo(domainObject1);
assertThat(domainObject1.hashCode()).isEqualTo(domainObject1.hashCode());
// Test with an instance of another class
Object testOtherObject = new Object();
assertThat(domainObject1).isNotEqualTo(testOtherObject);
assertThat(domainObject1).isNotEqualTo(null);
// Test with an instance of the same class
T domainObject2 = clazz.getConstructor().newInstance();
assertThat(domainObject1).isNotEqualTo(domainObject2);
// HashCodes are equals because the objects are not persisted yet
assertThat(domainObject1.hashCode()).isEqualTo(domainObject2.hashCode());
}
/**
* Create a FormattingConversionService which use ISO date format, instead of the localized one.
* @return the FormattingConversionService
*/
public static FormattingConversionService createFormattingConversionService() {
DefaultFormattingConversionService dfcs = new DefaultFormattingConversionService ();
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(dfcs);
return dfcs;
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/UserResourceIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/UserResourceIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.domain.Authority;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.UserRepository;
import org.ehcache.sample.security.AuthoritiesConstants;
import org.ehcache.sample.service.MailService;
import org.ehcache.sample.service.UserService;
import org.ehcache.sample.service.dto.UserDTO;
import org.ehcache.sample.service.mapper.UserMapper;
import org.ehcache.sample.web.rest.errors.ExceptionTranslator;
import org.ehcache.sample.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.CacheManager;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the UserResource REST controller.
*
* @see UserResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class UserResourceIntTest {
private static final String DEFAULT_LOGIN = "johndoe";
private static final String UPDATED_LOGIN = "jhipster";
private static final Long DEFAULT_ID = 1L;
private static final String DEFAULT_PASSWORD = "passjohndoe";
private static final String UPDATED_PASSWORD = "passjhipster";
private static final String DEFAULT_EMAIL = "johndoe@localhost";
private static final String UPDATED_EMAIL = "jhipster@localhost";
private static final String DEFAULT_FIRSTNAME = "john";
private static final String UPDATED_FIRSTNAME = "jhipsterFirstName";
private static final String DEFAULT_LASTNAME = "doe";
private static final String UPDATED_LASTNAME = "jhipsterLastName";
private static final String DEFAULT_IMAGEURL = "http://placehold.it/50x50";
private static final String UPDATED_IMAGEURL = "http://placehold.it/40x40";
private static final String DEFAULT_LANGKEY = "en";
private static final String UPDATED_LANGKEY = "fr";
@Autowired
private UserRepository userRepository;
@Autowired
private MailService mailService;
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
@Autowired
private CacheManager cacheManager;
private MockMvc restUserMockMvc;
private User user;
@Before
public void setup() {
cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).clear();
cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE).clear();
UserResource userResource = new UserResource(userService, userRepository, mailService);
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
/**
* Create a User.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which has a required relationship to the User entity.
*/
public static User createEntity(EntityManager em) {
User user = new User();
user.setLogin(DEFAULT_LOGIN + RandomStringUtils.randomAlphabetic(5));
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setEmail(RandomStringUtils.randomAlphabetic(5) + DEFAULT_EMAIL);
user.setFirstName(DEFAULT_FIRSTNAME);
user.setLastName(DEFAULT_LASTNAME);
user.setImageUrl(DEFAULT_IMAGEURL);
user.setLangKey(DEFAULT_LANGKEY);
return user;
}
@Before
public void initTest() {
user = createEntity(em);
user.setLogin(DEFAULT_LOGIN);
user.setEmail(DEFAULT_EMAIL);
}
@Test
@Transactional
public void createUser() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
// Create the User
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin(DEFAULT_LOGIN);
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isCreated());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate + 1);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
}
@Test
@Transactional
public void createUserWithExistingId() throws Exception {
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(1L);
managedUserVM.setLogin(DEFAULT_LOGIN);
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// An entity with an existing ID cannot be created, so this API call must fail
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void createUserWithExistingLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin(DEFAULT_LOGIN);// this login should already be used
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail("anothermail@localhost");
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void createUserWithExistingEmail() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeCreate = userRepository.findAll().size();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setLogin("anotherlogin");
managedUserVM.setPassword(DEFAULT_PASSWORD);
managedUserVM.setFirstName(DEFAULT_FIRSTNAME);
managedUserVM.setLastName(DEFAULT_LASTNAME);
managedUserVM.setEmail(DEFAULT_EMAIL);// this email should already be used
managedUserVM.setActivated(true);
managedUserVM.setImageUrl(DEFAULT_IMAGEURL);
managedUserVM.setLangKey(DEFAULT_LANGKEY);
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Create the User
restUserMockMvc.perform(post("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllUsers() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
// Get all the users
restUserMockMvc.perform(get("/api/users?sort=id,desc")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].login").value(hasItem(DEFAULT_LOGIN)))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRSTNAME)))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LASTNAME)))
.andExpect(jsonPath("$.[*].email").value(hasItem(DEFAULT_EMAIL)))
.andExpect(jsonPath("$.[*].imageUrl").value(hasItem(DEFAULT_IMAGEURL)))
.andExpect(jsonPath("$.[*].langKey").value(hasItem(DEFAULT_LANGKEY)));
}
@Test
@Transactional
public void getUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
// Get the user
restUserMockMvc.perform(get("/api/users/{login}", user.getLogin()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value(user.getLogin()))
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRSTNAME))
.andExpect(jsonPath("$.lastName").value(DEFAULT_LASTNAME))
.andExpect(jsonPath("$.email").value(DEFAULT_EMAIL))
.andExpect(jsonPath("$.imageUrl").value(DEFAULT_IMAGEURL))
.andExpect(jsonPath("$.langKey").value(DEFAULT_LANGKEY));
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNotNull();
}
@Test
@Transactional
public void getNonExistingUser() throws Exception {
restUserMockMvc.perform(get("/api/users/unknown"))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(updatedUser.getLogin());
managedUserVM.setPassword(UPDATED_PASSWORD);
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
managedUserVM.setLastName(UPDATED_LASTNAME);
managedUserVM.setEmail(UPDATED_EMAIL);
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
managedUserVM.setLangKey(UPDATED_LANGKEY);
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
}
@Test
@Transactional
public void updateUserLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeUpdate = userRepository.findAll().size();
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(UPDATED_LOGIN);
managedUserVM.setPassword(UPDATED_PASSWORD);
managedUserVM.setFirstName(UPDATED_FIRSTNAME);
managedUserVM.setLastName(UPDATED_LASTNAME);
managedUserVM.setEmail(UPDATED_EMAIL);
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(UPDATED_IMAGEURL);
managedUserVM.setLangKey(UPDATED_LANGKEY);
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isOk());
// Validate the User in the database
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeUpdate);
User testUser = userList.get(userList.size() - 1);
assertThat(testUser.getLogin()).isEqualTo(UPDATED_LOGIN);
assertThat(testUser.getFirstName()).isEqualTo(UPDATED_FIRSTNAME);
assertThat(testUser.getLastName()).isEqualTo(UPDATED_LASTNAME);
assertThat(testUser.getEmail()).isEqualTo(UPDATED_EMAIL);
assertThat(testUser.getImageUrl()).isEqualTo(UPDATED_IMAGEURL);
assertThat(testUser.getLangKey()).isEqualTo(UPDATED_LANGKEY);
}
@Test
@Transactional
public void updateUserExistingEmail() throws Exception {
// Initialize the database with 2 users
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.saveAndFlush(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin(updatedUser.getLogin());
managedUserVM.setPassword(updatedUser.getPassword());
managedUserVM.setFirstName(updatedUser.getFirstName());
managedUserVM.setLastName(updatedUser.getLastName());
managedUserVM.setEmail("jhipster@localhost");// this email should already be used by anotherUser
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(updatedUser.getImageUrl());
managedUserVM.setLangKey(updatedUser.getLangKey());
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
public void updateUserExistingLogin() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("jhipster");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
anotherUser.setEmail("jhipster@localhost");
anotherUser.setFirstName("java");
anotherUser.setLastName("hipster");
anotherUser.setImageUrl("");
anotherUser.setLangKey("en");
userRepository.saveAndFlush(anotherUser);
// Update the user
User updatedUser = userRepository.findById(user.getId()).get();
ManagedUserVM managedUserVM = new ManagedUserVM();
managedUserVM.setId(updatedUser.getId());
managedUserVM.setLogin("jhipster");// this login should already be used by anotherUser
managedUserVM.setPassword(updatedUser.getPassword());
managedUserVM.setFirstName(updatedUser.getFirstName());
managedUserVM.setLastName(updatedUser.getLastName());
managedUserVM.setEmail(updatedUser.getEmail());
managedUserVM.setActivated(updatedUser.getActivated());
managedUserVM.setImageUrl(updatedUser.getImageUrl());
managedUserVM.setLangKey(updatedUser.getLangKey());
managedUserVM.setCreatedBy(updatedUser.getCreatedBy());
managedUserVM.setCreatedDate(updatedUser.getCreatedDate());
managedUserVM.setLastModifiedBy(updatedUser.getLastModifiedBy());
managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate());
managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(put("/api/users")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(managedUserVM)))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
public void deleteUser() throws Exception {
// Initialize the database
userRepository.saveAndFlush(user);
int databaseSizeBeforeDelete = userRepository.findAll().size();
// Delete the user
restUserMockMvc.perform(delete("/api/users/{login}", user.getLogin())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
assertThat(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE).get(user.getLogin())).isNull();
// Validate the database is empty
List<User> userList = userRepository.findAll();
assertThat(userList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void getAllAuthorities() throws Exception {
restUserMockMvc.perform(get("/api/users/authorities")
.accept(TestUtil.APPLICATION_JSON_UTF8)
.contentType(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$").isArray())
.andExpect(jsonPath("$").value(hasItems(AuthoritiesConstants.USER, AuthoritiesConstants.ADMIN)));
}
@Test
@Transactional
public void testUserEquals() throws Exception {
TestUtil.equalsVerifier(User.class);
User user1 = new User();
user1.setId(1L);
User user2 = new User();
user2.setId(user1.getId());
assertThat(user1).isEqualTo(user2);
user2.setId(2L);
assertThat(user1).isNotEqualTo(user2);
user1.setId(null);
assertThat(user1).isNotEqualTo(user2);
}
@Test
public void testUserFromId() {
assertThat(userMapper.userFromId(DEFAULT_ID).getId()).isEqualTo(DEFAULT_ID);
assertThat(userMapper.userFromId(null)).isNull();
}
@Test
public void testUserDTOtoUser() {
UserDTO userDTO = new UserDTO();
userDTO.setId(DEFAULT_ID);
userDTO.setLogin(DEFAULT_LOGIN);
userDTO.setFirstName(DEFAULT_FIRSTNAME);
userDTO.setLastName(DEFAULT_LASTNAME);
userDTO.setEmail(DEFAULT_EMAIL);
userDTO.setActivated(true);
userDTO.setImageUrl(DEFAULT_IMAGEURL);
userDTO.setLangKey(DEFAULT_LANGKEY);
userDTO.setCreatedBy(DEFAULT_LOGIN);
userDTO.setLastModifiedBy(DEFAULT_LOGIN);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
User user = userMapper.userDTOToUser(userDTO);
assertThat(user.getId()).isEqualTo(DEFAULT_ID);
assertThat(user.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(user.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(user.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(user.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(user.getActivated()).isEqualTo(true);
assertThat(user.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(user.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(user.getCreatedBy()).isNull();
assertThat(user.getCreatedDate()).isNotNull();
assertThat(user.getLastModifiedBy()).isNull();
assertThat(user.getLastModifiedDate()).isNotNull();
assertThat(user.getAuthorities()).extracting("name").containsExactly(AuthoritiesConstants.USER);
}
@Test
public void testUserToUserDTO() {
user.setId(DEFAULT_ID);
user.setCreatedBy(DEFAULT_LOGIN);
user.setCreatedDate(Instant.now());
user.setLastModifiedBy(DEFAULT_LOGIN);
user.setLastModifiedDate(Instant.now());
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.USER);
authorities.add(authority);
user.setAuthorities(authorities);
UserDTO userDTO = userMapper.userToUserDTO(user);
assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID);
assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME);
assertThat(userDTO.getLastName()).isEqualTo(DEFAULT_LASTNAME);
assertThat(userDTO.getEmail()).isEqualTo(DEFAULT_EMAIL);
assertThat(userDTO.isActivated()).isEqualTo(true);
assertThat(userDTO.getImageUrl()).isEqualTo(DEFAULT_IMAGEURL);
assertThat(userDTO.getLangKey()).isEqualTo(DEFAULT_LANGKEY);
assertThat(userDTO.getCreatedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getCreatedDate()).isEqualTo(user.getCreatedDate());
assertThat(userDTO.getLastModifiedBy()).isEqualTo(DEFAULT_LOGIN);
assertThat(userDTO.getLastModifiedDate()).isEqualTo(user.getLastModifiedDate());
assertThat(userDTO.getAuthorities()).containsExactly(AuthoritiesConstants.USER);
assertThat(userDTO.toString()).isNotNull();
}
@Test
public void testAuthorityEquals() {
Authority authorityA = new Authority();
assertThat(authorityA).isEqualTo(authorityA);
assertThat(authorityA).isNotEqualTo(null);
assertThat(authorityA).isNotEqualTo(new Object());
assertThat(authorityA.hashCode()).isEqualTo(0);
assertThat(authorityA.toString()).isNotNull();
Authority authorityB = new Authority();
assertThat(authorityA).isEqualTo(authorityB);
authorityB.setName(AuthoritiesConstants.ADMIN);
assertThat(authorityA).isNotEqualTo(authorityB);
authorityA.setName(AuthoritiesConstants.USER);
assertThat(authorityA).isNotEqualTo(authorityB);
authorityB.setName(AuthoritiesConstants.USER);
assertThat(authorityA).isEqualTo(authorityB);
assertThat(authorityA.hashCode()).isEqualTo(authorityB.hashCode());
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/ActorResourceIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/ActorResourceIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.domain.Actor;
import org.ehcache.sample.repository.ActorRepository;
import org.ehcache.sample.service.ActorService;
import org.ehcache.sample.web.rest.errors.ExceptionTranslator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
import static org.ehcache.sample.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the ActorResource REST controller.
*
* @see ActorResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class ActorResourceIntTest {
private static final String DEFAULT_FIRST_NAME = "AAAAAAAAAA";
private static final String UPDATED_FIRST_NAME = "BBBBBBBBBB";
private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA";
private static final String UPDATED_LAST_NAME = "BBBBBBBBBB";
private static final LocalDate DEFAULT_BIRTH_DATE = LocalDate.ofEpochDay(0L);
private static final LocalDate UPDATED_BIRTH_DATE = LocalDate.now(ZoneId.systemDefault());
private static final String DEFAULT_BIRTH_LOCATION = "AAAAAAAAAA";
private static final String UPDATED_BIRTH_LOCATION = "BBBBBBBBBB";
@Autowired
private ActorRepository actorRepository;
@Autowired
private ActorService actorService;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private EntityManager em;
private MockMvc restActorMockMvc;
private Actor actor;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final ActorResource actorResource = new ActorResource(actorService);
this.restActorMockMvc = MockMvcBuilders.standaloneSetup(actorResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Actor createEntity(EntityManager em) {
Actor actor = new Actor()
.firstName(DEFAULT_FIRST_NAME)
.lastName(DEFAULT_LAST_NAME)
.birthDate(DEFAULT_BIRTH_DATE)
.birthLocation(DEFAULT_BIRTH_LOCATION);
return actor;
}
@Before
public void initTest() {
actor = createEntity(em);
}
@Test
@Transactional
public void createActor() throws Exception {
int databaseSizeBeforeCreate = actorRepository.findAll().size();
// Create the Actor
restActorMockMvc.perform(post("/api/actors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(actor)))
.andExpect(status().isCreated());
// Validate the Actor in the database
List<Actor> actorList = actorRepository.findAll();
assertThat(actorList).hasSize(databaseSizeBeforeCreate + 1);
Actor testActor = actorList.get(actorList.size() - 1);
assertThat(testActor.getFirstName()).isEqualTo(DEFAULT_FIRST_NAME);
assertThat(testActor.getLastName()).isEqualTo(DEFAULT_LAST_NAME);
assertThat(testActor.getBirthDate()).isEqualTo(DEFAULT_BIRTH_DATE);
assertThat(testActor.getBirthLocation()).isEqualTo(DEFAULT_BIRTH_LOCATION);
}
@Test
@Transactional
public void createActorWithExistingId() throws Exception {
int databaseSizeBeforeCreate = actorRepository.findAll().size();
// Create the Actor with an existing ID
actor.setId(1L);
// An entity with an existing ID cannot be created, so this API call must fail
restActorMockMvc.perform(post("/api/actors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(actor)))
.andExpect(status().isBadRequest());
// Validate the Actor in the database
List<Actor> actorList = actorRepository.findAll();
assertThat(actorList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
public void getAllActors() throws Exception {
// Initialize the database
actorRepository.saveAndFlush(actor);
// Get all the actorList
restActorMockMvc.perform(get("/api/actors?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(actor.getId().intValue())))
.andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME.toString())))
.andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME.toString())))
.andExpect(jsonPath("$.[*].birthDate").value(hasItem(DEFAULT_BIRTH_DATE.toString())))
.andExpect(jsonPath("$.[*].birthLocation").value(hasItem(DEFAULT_BIRTH_LOCATION.toString())));
}
@Test
@Transactional
public void getActor() throws Exception {
// Initialize the database
actorRepository.saveAndFlush(actor);
// Get the actor
restActorMockMvc.perform(get("/api/actors/{id}", actor.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.id").value(actor.getId().intValue()))
.andExpect(jsonPath("$.firstName").value(DEFAULT_FIRST_NAME.toString()))
.andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME.toString()))
.andExpect(jsonPath("$.birthDate").value(DEFAULT_BIRTH_DATE.toString()))
.andExpect(jsonPath("$.birthLocation").value(DEFAULT_BIRTH_LOCATION.toString()));
}
@Test
@Transactional
public void getNonExistingActor() throws Exception {
// Get the actor
restActorMockMvc.perform(get("/api/actors/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateActor() throws Exception {
// Initialize the database
actorService.save(actor);
int databaseSizeBeforeUpdate = actorRepository.findAll().size();
// Update the actor
Actor updatedActor = actorRepository.findById(actor.getId()).get();
// Disconnect from session so that the updates on updatedActor are not directly saved in db
em.detach(updatedActor);
updatedActor
.firstName(UPDATED_FIRST_NAME)
.lastName(UPDATED_LAST_NAME)
.birthDate(UPDATED_BIRTH_DATE)
.birthLocation(UPDATED_BIRTH_LOCATION);
restActorMockMvc.perform(put("/api/actors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedActor)))
.andExpect(status().isOk());
// Validate the Actor in the database
List<Actor> actorList = actorRepository.findAll();
assertThat(actorList).hasSize(databaseSizeBeforeUpdate);
Actor testActor = actorList.get(actorList.size() - 1);
assertThat(testActor.getFirstName()).isEqualTo(UPDATED_FIRST_NAME);
assertThat(testActor.getLastName()).isEqualTo(UPDATED_LAST_NAME);
assertThat(testActor.getBirthDate()).isEqualTo(UPDATED_BIRTH_DATE);
assertThat(testActor.getBirthLocation()).isEqualTo(UPDATED_BIRTH_LOCATION);
}
@Test
@Transactional
public void updateNonExistingActor() throws Exception {
int databaseSizeBeforeUpdate = actorRepository.findAll().size();
// Create the Actor
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restActorMockMvc.perform(put("/api/actors")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(actor)))
.andExpect(status().isBadRequest());
// Validate the Actor in the database
List<Actor> actorList = actorRepository.findAll();
assertThat(actorList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
public void deleteActor() throws Exception {
// Initialize the database
actorService.save(actor);
int databaseSizeBeforeDelete = actorRepository.findAll().size();
// Get the actor
restActorMockMvc.perform(delete("/api/actors/{id}", actor.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate the database is empty
List<Actor> actorList = actorRepository.findAll();
assertThat(actorList).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void equalsVerifier() throws Exception {
TestUtil.equalsVerifier(Actor.class);
Actor actor1 = new Actor();
actor1.setId(1L);
Actor actor2 = new Actor();
actor2.setId(actor1.getId());
assertThat(actor1).isEqualTo(actor2);
actor2.setId(2L);
assertThat(actor1).isNotEqualTo(actor2);
actor1.setId(null);
assertThat(actor1).isNotEqualTo(actor2);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/AccountResourceIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/AccountResourceIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.domain.Authority;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.AuthorityRepository;
import org.ehcache.sample.repository.UserRepository;
import org.ehcache.sample.security.AuthoritiesConstants;
import org.ehcache.sample.service.MailService;
import org.ehcache.sample.service.UserService;
import org.ehcache.sample.service.dto.PasswordChangeDTO;
import org.ehcache.sample.service.dto.UserDTO;
import org.ehcache.sample.web.rest.errors.ExceptionTranslator;
import org.ehcache.sample.web.rest.vm.KeyAndPasswordVM;
import org.ehcache.sample.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Test class for the AccountResource REST controller.
*
* @see AccountResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class AccountResourceIntTest {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorityRepository authorityRepository;
@Autowired
private UserService userService;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private HttpMessageConverter<?>[] httpMessageConverters;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Mock
private UserService mockUserService;
@Mock
private MailService mockMailService;
private MockMvc restMvc;
private MockMvc restUserMockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
doNothing().when(mockMailService).sendActivationEmail(any());
AccountResource accountResource =
new AccountResource(userRepository, userService, mockMailService);
AccountResource accountUserMockResource =
new AccountResource(userRepository, mockUserService, mockMailService);
this.restMvc = MockMvcBuilders.standaloneSetup(accountResource)
.setMessageConverters(httpMessageConverters)
.setControllerAdvice(exceptionTranslator)
.build();
this.restUserMockMvc = MockMvcBuilders.standaloneSetup(accountUserMockResource)
.setControllerAdvice(exceptionTranslator)
.build();
}
@Test
public void testNonAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(""));
}
@Test
public void testAuthenticatedUser() throws Exception {
restUserMockMvc.perform(get("/api/authenticate")
.with(request -> {
request.setRemoteUser("test");
return request;
})
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string("test"));
}
@Test
public void testGetExistingAccount() throws Exception {
Set<Authority> authorities = new HashSet<>();
Authority authority = new Authority();
authority.setName(AuthoritiesConstants.ADMIN);
authorities.add(authority);
User user = new User();
user.setLogin("test");
user.setFirstName("john");
user.setLastName("doe");
user.setEmail("john.doe@jhipster.com");
user.setImageUrl("http://placehold.it/50x50");
user.setLangKey("en");
user.setAuthorities(authorities);
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.of(user));
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.login").value("test"))
.andExpect(jsonPath("$.firstName").value("john"))
.andExpect(jsonPath("$.lastName").value("doe"))
.andExpect(jsonPath("$.email").value("john.doe@jhipster.com"))
.andExpect(jsonPath("$.imageUrl").value("http://placehold.it/50x50"))
.andExpect(jsonPath("$.langKey").value("en"))
.andExpect(jsonPath("$.authorities").value(AuthoritiesConstants.ADMIN));
}
@Test
public void testGetUnknownAccount() throws Exception {
when(mockUserService.getUserWithAuthorities()).thenReturn(Optional.empty());
restUserMockMvc.perform(get("/api/account")
.accept(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(status().isInternalServerError());
}
@Test
@Transactional
public void testRegisterValid() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("test-register-valid");
validUser.setPassword("password");
validUser.setFirstName("Alice");
validUser.setLastName("Test");
validUser.setEmail("test-register-valid@example.com");
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isFalse();
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
assertThat(userRepository.findOneByLogin("test-register-valid").isPresent()).isTrue();
}
@Test
@Transactional
public void testRegisterInvalidLogin() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("funky-log!n");// <-- invalid
invalidUser.setPassword("password");
invalidUser.setFirstName("Funky");
invalidUser.setLastName("One");
invalidUser.setEmail("funky@example.com");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByEmailIgnoreCase("funky@example.com");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterInvalidEmail() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("password");
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("invalid");// <-- invalid
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterInvalidPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword("123");// password with only 3 digits
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("bob@example.com");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterNullPassword() throws Exception {
ManagedUserVM invalidUser = new ManagedUserVM();
invalidUser.setLogin("bob");
invalidUser.setPassword(null);// invalid null password
invalidUser.setFirstName("Bob");
invalidUser.setLastName("Green");
invalidUser.setEmail("bob@example.com");
invalidUser.setActivated(true);
invalidUser.setImageUrl("http://placehold.it/50x50");
invalidUser.setLangKey(Constants.DEFAULT_LANGUAGE);
invalidUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
restUserMockMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(invalidUser)))
.andExpect(status().isBadRequest());
Optional<User> user = userRepository.findOneByLogin("bob");
assertThat(user.isPresent()).isFalse();
}
@Test
@Transactional
public void testRegisterDuplicateLogin() throws Exception {
// First registration
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("alice");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Something");
firstUser.setEmail("alice@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Duplicate login, different email
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin(firstUser.getLogin());
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail("alice2@example.com");
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setCreatedBy(firstUser.getCreatedBy());
secondUser.setCreatedDate(firstUser.getCreatedDate());
secondUser.setLastModifiedBy(firstUser.getLastModifiedBy());
secondUser.setLastModifiedDate(firstUser.getLastModifiedDate());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// First user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
// Second (non activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser = userRepository.findOneByEmailIgnoreCase("alice2@example.com");
assertThat(testUser.isPresent()).isTrue();
testUser.get().setActivated(true);
userRepository.save(testUser.get());
// Second (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
public void testRegisterDuplicateEmail() throws Exception {
// First user
ManagedUserVM firstUser = new ManagedUserVM();
firstUser.setLogin("test-register-duplicate-email");
firstUser.setPassword("password");
firstUser.setFirstName("Alice");
firstUser.setLastName("Test");
firstUser.setEmail("test-register-duplicate-email@example.com");
firstUser.setImageUrl("http://placehold.it/50x50");
firstUser.setLangKey(Constants.DEFAULT_LANGUAGE);
firstUser.setAuthorities(Collections.singleton(AuthoritiesConstants.USER));
// Register first user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(firstUser)))
.andExpect(status().isCreated());
Optional<User> testUser1 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser1.isPresent()).isTrue();
// Duplicate email, different login
ManagedUserVM secondUser = new ManagedUserVM();
secondUser.setLogin("test-register-duplicate-email-2");
secondUser.setPassword(firstUser.getPassword());
secondUser.setFirstName(firstUser.getFirstName());
secondUser.setLastName(firstUser.getLastName());
secondUser.setEmail(firstUser.getEmail());
secondUser.setImageUrl(firstUser.getImageUrl());
secondUser.setLangKey(firstUser.getLangKey());
secondUser.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register second (non activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().isCreated());
Optional<User> testUser2 = userRepository.findOneByLogin("test-register-duplicate-email");
assertThat(testUser2.isPresent()).isFalse();
Optional<User> testUser3 = userRepository.findOneByLogin("test-register-duplicate-email-2");
assertThat(testUser3.isPresent()).isTrue();
// Duplicate email - with uppercase email address
ManagedUserVM userWithUpperCaseEmail = new ManagedUserVM();
userWithUpperCaseEmail.setId(firstUser.getId());
userWithUpperCaseEmail.setLogin("test-register-duplicate-email-3");
userWithUpperCaseEmail.setPassword(firstUser.getPassword());
userWithUpperCaseEmail.setFirstName(firstUser.getFirstName());
userWithUpperCaseEmail.setLastName(firstUser.getLastName());
userWithUpperCaseEmail.setEmail("TEST-register-duplicate-email@example.com");
userWithUpperCaseEmail.setImageUrl(firstUser.getImageUrl());
userWithUpperCaseEmail.setLangKey(firstUser.getLangKey());
userWithUpperCaseEmail.setAuthorities(new HashSet<>(firstUser.getAuthorities()));
// Register third (not activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userWithUpperCaseEmail)))
.andExpect(status().isCreated());
Optional<User> testUser4 = userRepository.findOneByLogin("test-register-duplicate-email-3");
assertThat(testUser4.isPresent()).isTrue();
assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com");
testUser4.get().setActivated(true);
userService.updateUser((new UserDTO(testUser4.get())));
// Register 4th (already activated) user
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(secondUser)))
.andExpect(status().is4xxClientError());
}
@Test
@Transactional
public void testRegisterAdminIsIgnored() throws Exception {
ManagedUserVM validUser = new ManagedUserVM();
validUser.setLogin("badguy");
validUser.setPassword("password");
validUser.setFirstName("Bad");
validUser.setLastName("Guy");
validUser.setEmail("badguy@example.com");
validUser.setActivated(true);
validUser.setImageUrl("http://placehold.it/50x50");
validUser.setLangKey(Constants.DEFAULT_LANGUAGE);
validUser.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/register")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(validUser)))
.andExpect(status().isCreated());
Optional<User> userDup = userRepository.findOneByLogin("badguy");
assertThat(userDup.isPresent()).isTrue();
assertThat(userDup.get().getAuthorities()).hasSize(1)
.containsExactly(authorityRepository.findById(AuthoritiesConstants.USER).get());
}
@Test
@Transactional
public void testActivateAccount() throws Exception {
final String activationKey = "some activation key";
User user = new User();
user.setLogin("activate-account");
user.setEmail("activate-account@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(false);
user.setActivationKey(activationKey);
userRepository.saveAndFlush(user);
restMvc.perform(get("/api/activate?key={activationKey}", activationKey))
.andExpect(status().isOk());
user = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(user.getActivated()).isTrue();
}
@Test
@Transactional
public void testActivateAccountWithWrongKey() throws Exception {
restMvc.perform(get("/api/activate?key=wrongActivationKey"))
.andExpect(status().isInternalServerError());
}
@Test
@Transactional
@WithMockUser("save-account")
public void testSaveAccount() throws Exception {
User user = new User();
user.setLogin("save-account");
user.setEmail("save-account@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-account@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(updatedUser.getFirstName()).isEqualTo(userDTO.getFirstName());
assertThat(updatedUser.getLastName()).isEqualTo(userDTO.getLastName());
assertThat(updatedUser.getEmail()).isEqualTo(userDTO.getEmail());
assertThat(updatedUser.getLangKey()).isEqualTo(userDTO.getLangKey());
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
assertThat(updatedUser.getImageUrl()).isEqualTo(userDTO.getImageUrl());
assertThat(updatedUser.getActivated()).isEqualTo(true);
assertThat(updatedUser.getAuthorities()).isEmpty();
}
@Test
@Transactional
@WithMockUser("save-invalid-email")
public void testSaveInvalidEmail() throws Exception {
User user = new User();
user.setLogin("save-invalid-email");
user.setEmail("save-invalid-email@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("invalid email");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
assertThat(userRepository.findOneByEmailIgnoreCase("invalid email")).isNotPresent();
}
@Test
@Transactional
@WithMockUser("save-existing-email")
public void testSaveExistingEmail() throws Exception {
User user = new User();
user.setLogin("save-existing-email");
user.setEmail("save-existing-email@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
User anotherUser = new User();
anotherUser.setLogin("save-existing-email2");
anotherUser.setEmail("save-existing-email2@example.com");
anotherUser.setPassword(RandomStringUtils.random(60));
anotherUser.setActivated(true);
userRepository.saveAndFlush(anotherUser);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email2@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("save-existing-email").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email@example.com");
}
@Test
@Transactional
@WithMockUser("save-existing-email-and-login")
public void testSaveExistingEmailAndLogin() throws Exception {
User user = new User();
user.setLogin("save-existing-email-and-login");
user.setEmail("save-existing-email-and-login@example.com");
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
userRepository.saveAndFlush(user);
UserDTO userDTO = new UserDTO();
userDTO.setLogin("not-used");
userDTO.setFirstName("firstname");
userDTO.setLastName("lastname");
userDTO.setEmail("save-existing-email-and-login@example.com");
userDTO.setActivated(false);
userDTO.setImageUrl("http://placehold.it/50x50");
userDTO.setLangKey(Constants.DEFAULT_LANGUAGE);
userDTO.setAuthorities(Collections.singleton(AuthoritiesConstants.ADMIN));
restMvc.perform(
post("/api/account")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(userDTO)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("save-existing-email-and-login").orElse(null);
assertThat(updatedUser.getEmail()).isEqualTo("save-existing-email-and-login@example.com");
}
@Test
@Transactional
@WithMockUser("change-password-wrong-existing-password")
public void testChangePasswordWrongExistingPassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-wrong-existing-password");
user.setEmail("change-password-wrong-existing-password@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO("1"+currentPassword, "new password"))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-wrong-existing-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isFalse();
assertThat(passwordEncoder.matches(currentPassword, updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password")
public void testChangePassword() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password");
user.setEmail("change-password@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new password"))))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin("change-password").orElse(null);
assertThat(passwordEncoder.matches("new password", updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
@WithMockUser("change-password-too-small")
public void testChangePasswordTooSmall() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-small");
user.setEmail("change-password-too-small@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, "new"))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-small").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-too-long")
public void testChangePasswordTooLong() throws Exception {
User user = new User();
String currentPassword = RandomStringUtils.random(60);
user.setPassword(passwordEncoder.encode(currentPassword));
user.setLogin("change-password-too-long");
user.setEmail("change-password-too-long@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(new PasswordChangeDTO(currentPassword, RandomStringUtils.random(101)))))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-too-long").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
@WithMockUser("change-password-empty")
public void testChangePasswordEmpty() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("change-password-empty");
user.setEmail("change-password-empty@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/change-password").content(RandomStringUtils.random(0)))
.andExpect(status().isBadRequest());
User updatedUser = userRepository.findOneByLogin("change-password-empty").orElse(null);
assertThat(updatedUser.getPassword()).isEqualTo(user.getPassword());
}
@Test
@Transactional
public void testRequestPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("password-reset@example.com"))
.andExpect(status().isOk());
}
@Test
@Transactional
public void testRequestPasswordResetUpperCaseEmail() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setActivated(true);
user.setLogin("password-reset");
user.setEmail("password-reset@example.com");
userRepository.saveAndFlush(user);
restMvc.perform(post("/api/account/reset-password/init")
.content("password-reset@EXAMPLE.COM"))
.andExpect(status().isOk());
}
@Test
public void testRequestPasswordResetWrongEmail() throws Exception {
restMvc.perform(
post("/api/account/reset-password/init")
.content("password-reset-wrong-email@example.com"))
.andExpect(status().isBadRequest());
}
@Test
@Transactional
public void testFinishPasswordReset() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset");
user.setEmail("finish-password-reset@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key");
userRepository.saveAndFlush(user);
KeyAndPasswordVM keyAndPassword = new KeyAndPasswordVM();
keyAndPassword.setKey(user.getResetKey());
keyAndPassword.setNewPassword("new password");
restMvc.perform(
post("/api/account/reset-password/finish")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(keyAndPassword)))
.andExpect(status().isOk());
User updatedUser = userRepository.findOneByLogin(user.getLogin()).orElse(null);
assertThat(passwordEncoder.matches(keyAndPassword.getNewPassword(), updatedUser.getPassword())).isTrue();
}
@Test
@Transactional
public void testFinishPasswordResetTooSmall() throws Exception {
User user = new User();
user.setPassword(RandomStringUtils.random(60));
user.setLogin("finish-password-reset-too-small");
user.setEmail("finish-password-reset-too-small@example.com");
user.setResetDate(Instant.now().plusSeconds(60));
user.setResetKey("reset key too small");
userRepository.saveAndFlush(user);
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | true |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/LogsResourceIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/LogsResourceIntTest.java | package org.ehcache.sample.web.rest;
import org.ehcache.sample.DemoApp;
import org.ehcache.sample.web.rest.vm.LoggerVM;
import ch.qos.logback.classic.AsyncAppender;
import ch.qos.logback.classic.LoggerContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the LogsResource REST controller.
*
* @see LogsResource
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class LogsResourceIntTest {
private MockMvc restLogsMockMvc;
@Before
public void setup() {
LogsResource logsResource = new LogsResource();
this.restLogsMockMvc = MockMvcBuilders
.standaloneSetup(logsResource)
.build();
}
@Test
public void getAllLogs() throws Exception {
restLogsMockMvc.perform(get("/management/logs"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE));
}
@Test
public void changeLogs() throws Exception {
LoggerVM logger = new LoggerVM();
logger.setLevel("INFO");
logger.setName("ROOT");
restLogsMockMvc.perform(put("/management/logs")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(logger)))
.andExpect(status().isNoContent());
}
@Test
public void testLogstashAppender() {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
assertThat(context.getLogger("ROOT").getAppender("ASYNC_LOGSTASH")).isInstanceOf(AsyncAppender.class);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/util/PaginationUtilUnitTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/util/PaginationUtilUnitTest.java | package org.ehcache.sample.web.rest.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpHeaders;
/**
* Tests based on parsing algorithm in app/components/util/pagination-util.service.js
*
* @see PaginationUtil
*/
public class PaginationUtilUnitTest {
@Test
public void generatePaginationHttpHeadersTest() {
String baseUrl = "/api/_search/example";
List<String> content = new ArrayList<>();
Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
List<String> strHeaders = headers.get(HttpHeaders.LINK);
assertNotNull(strHeaders);
assertTrue(strHeaders.size() == 1);
String headerData = strHeaders.get(0);
assertTrue(headerData.split(",").length == 4);
String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
+ "</api/_search/example?page=5&size=50>; rel=\"prev\","
+ "</api/_search/example?page=7&size=50>; rel=\"last\","
+ "</api/_search/example?page=0&size=50>; rel=\"first\"";
assertEquals(expectedData, headerData);
List<String> xTotalCountHeaders = headers.get("X-Total-Count");
assertTrue(xTotalCountHeaders.size() == 1);
assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/errors/ExceptionTranslatorTestController.java | fullstack/src/test/java/org/ehcache/sample/web/rest/errors/ExceptionTranslatorTestController.java | package org.ehcache.sample.web.rest.errors;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ExceptionTranslatorTestController {
@GetMapping("/test/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/test/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {
}
@GetMapping("/test/parameterized-error")
public void parameterizedError() {
throw new CustomParameterizedException("test parameterized error", "param0_value", "param1_value");
}
@GetMapping("/test/parameterized-error2")
public void parameterizedError2() {
Map<String, Object> params = new HashMap<>();
params.put("foo", "foo_value");
params.put("bar", "bar_value");
throw new CustomParameterizedException("test parameterized error", params);
}
@GetMapping("/test/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart String part) {
}
@GetMapping("/test/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam String param) {
}
@GetMapping("/test/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/test/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/test/response-status")
public void exceptionWithReponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/test/internal-server-error")
public void internalServerError() {
throw new RuntimeException();
}
public static class TestDTO {
@NotNull
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
@SuppressWarnings("serial")
public static class TestResponseStatusException extends RuntimeException {
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/test/java/org/ehcache/sample/web/rest/errors/ExceptionTranslatorIntTest.java | fullstack/src/test/java/org/ehcache/sample/web/rest/errors/ExceptionTranslatorIntTest.java | package org.ehcache.sample.web.rest.errors;
import org.ehcache.sample.DemoApp;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Test class for the ExceptionTranslator controller advice.
*
* @see ExceptionTranslator
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApp.class)
public class ExceptionTranslatorIntTest {
@Autowired
private ExceptionTranslatorTestController controller;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.setControllerAdvice(exceptionTranslator)
.setMessageConverters(jacksonMessageConverter)
.build();
}
@Test
public void testConcurrencyFailure() throws Exception {
mockMvc.perform(get("/test/concurrency-failure"))
.andExpect(status().isConflict())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_CONCURRENCY_FAILURE));
}
@Test
public void testMethodArgumentNotValid() throws Exception {
mockMvc.perform(post("/test/method-argument").content("{}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value(ErrorConstants.ERR_VALIDATION))
.andExpect(jsonPath("$.fieldErrors.[0].objectName").value("testDTO"))
.andExpect(jsonPath("$.fieldErrors.[0].field").value("test"))
.andExpect(jsonPath("$.fieldErrors.[0].message").value("NotNull"));
}
@Test
public void testParameterizedError() throws Exception {
mockMvc.perform(get("/test/parameterized-error"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("test parameterized error"))
.andExpect(jsonPath("$.params.param0").value("param0_value"))
.andExpect(jsonPath("$.params.param1").value("param1_value"));
}
@Test
public void testParameterizedError2() throws Exception {
mockMvc.perform(get("/test/parameterized-error2"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("test parameterized error"))
.andExpect(jsonPath("$.params.foo").value("foo_value"))
.andExpect(jsonPath("$.params.bar").value("bar_value"));
}
@Test
public void testMissingServletRequestPartException() throws Exception {
mockMvc.perform(get("/test/missing-servlet-request-part"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
public void testMissingServletRequestParameterException() throws Exception {
mockMvc.perform(get("/test/missing-servlet-request-parameter"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"));
}
@Test
public void testAccessDenied() throws Exception {
mockMvc.perform(get("/test/access-denied"))
.andExpect(status().isForbidden())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.403"))
.andExpect(jsonPath("$.detail").value("test access denied!"));
}
@Test
public void testUnauthorized() throws Exception {
mockMvc.perform(get("/test/unauthorized"))
.andExpect(status().isUnauthorized())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.401"))
.andExpect(jsonPath("$.path").value("/test/unauthorized"))
.andExpect(jsonPath("$.detail").value("test authentication failed!"));
}
@Test
public void testMethodNotSupported() throws Exception {
mockMvc.perform(post("/test/access-denied"))
.andExpect(status().isMethodNotAllowed())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.405"))
.andExpect(jsonPath("$.detail").value("Request method 'POST' not supported"));
}
@Test
public void testExceptionWithResponseStatus() throws Exception {
mockMvc.perform(get("/test/response-status"))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.400"))
.andExpect(jsonPath("$.title").value("test response status"));
}
@Test
public void testInternalServerError() throws Exception {
mockMvc.perform(get("/test/internal-server-error"))
.andExpect(status().isInternalServerError())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.message").value("error.http.500"))
.andExpect(jsonPath("$.title").value("Internal Server Error"));
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/ApplicationWebXml.java | fullstack/src/main/java/org/ehcache/sample/ApplicationWebXml.java | package org.ehcache.sample;
import org.ehcache.sample.config.DefaultProfileUtil;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* This is a helper Java class that provides an alternative to creating a web.xml.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
/**
* set a default to use when no profile is configured.
*/
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(DemoApp.class);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/DemoApp.java | fullstack/src/main/java/org/ehcache/sample/DemoApp.java | package org.ehcache.sample;
import org.ehcache.sample.config.ApplicationProperties;
import org.ehcache.sample.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.ehcache.sample.domain.Actor;
import org.ehcache.sample.repository.ActorRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import com.google.common.base.Strings;
import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.zip.GZIPInputStream;
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
public class DemoApp {
private static final Logger log = LoggerFactory.getLogger(DemoApp.class);
private final Environment env;
public DemoApp(Environment env) {
this.env = env;
}
/**
* Initializes demo.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(DemoApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
}
@Bean
public CommandLineRunner demo(ActorRepository actorRepository) {
return (args) -> {
boolean stubWebServices = env.getProperty("application.stubWebServices", Boolean.class, false);
if(stubWebServices) {
log.warn("Fake web service calls will be made");
}
else {
String googleApiKey = env.getProperty("application.googleApiKey");
String darkSkyApiKey = env.getProperty("application.darkSkyApiKey");
if (Strings.isNullOrEmpty(googleApiKey)) {
log.warn("The googleApiKey is not defined, CoordinatesService will NOT work !");
}
if (Strings.isNullOrEmpty(darkSkyApiKey)) {
log.warn("The darkSkyApiKey is not defined, WeatherService will NOT work !");
}
}
// Assume that if we already have entries in the DB, that we already read the full file
if (actorRepository.count() != 0) {
return;
}
String biographiesLocation = env.getProperty("application.biographiesLocation");
String biographiesRemoteLocation = env.getProperty("application.biographiesRemoteLocation");
log.info("The Actor table is empty, let's fill it up!");
Path localBiographiesPath = Paths.get(biographiesLocation);
// If the file isn't present locally, download it
if(!Files.exists(localBiographiesPath)) {
log.info("We could NOT find a local copy of biographies.gz at {}, so let's download it from {}", biographiesLocation, biographiesRemoteLocation);
try(InputStream inputStream = new URL(biographiesRemoteLocation).openStream()) {
Files.copy(inputStream, localBiographiesPath);
}
log.info("Download complete");
} else {
log.info("Using local copy of biographies.gz at {}", localBiographiesPath.toAbsolutePath().toString());
}
try (BufferedReader br = new BufferedReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(localBiographiesPath)), StandardCharsets.ISO_8859_1))) {
Stream<String> lines = br.lines()
.filter(s -> s.startsWith("NM:") && s.matches("^.*,.*$") || (s.startsWith("DB:") && s.matches("^.*\\s[0-9]{1,2}\\s.*\\s[0-9]{4}.*$")));
Pattern birthDatePattern = Pattern.compile("^.*\\s([0-9]{1,2})\\s(.*)\\s([0-9]{4})(.*)$");
AtomicReference<Actor> currentActor = new AtomicReference<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.US);
lines.forEachOrdered(s -> {
try {
if (s.startsWith("NM:")) {
Actor actor = new Actor();
actor.setLastName(s.substring(4, s.indexOf(",")));
actor.setFirstName(s.split(",")[1].substring(1));
currentActor.set(actor);
} else {
Matcher birthDateMatcher = birthDatePattern.matcher(s);
if (birthDateMatcher.find()) {
String day = birthDateMatcher.group(1);
String month = birthDateMatcher.group(2);
String year = birthDateMatcher.group(3);
Actor actor = currentActor.get();
try {
LocalDate birthDate = LocalDate.parse(day + " " + month + " " + year, formatter);
actor.setBirthDate(birthDate);
if (birthDateMatcher.group(4) != null && birthDateMatcher.group(4).length() > 2) {
actor.setBirthLocation(birthDateMatcher.group(4).substring(2));
}
actorRepository.save(actor);
} catch (NumberFormatException e) {
log.warn("Could not parse birthDate for " + currentActor.get().getFirstName() + " " + currentActor.get().getLastName(), e);
}
}
}
} catch (Exception e) {
log.warn("Error loading : " + s);
}
});
}
log.info("Number of actors in the database: {}", actorRepository.count());
};
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/UserService.java | fullstack/src/main/java/org/ehcache/sample/service/UserService.java | package org.ehcache.sample.service;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.domain.Authority;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.repository.AuthorityRepository;
import org.ehcache.sample.repository.UserRepository;
import org.ehcache.sample.security.AuthoritiesConstants;
import org.ehcache.sample.security.SecurityUtils;
import org.ehcache.sample.service.dto.UserDTO;
import org.ehcache.sample.service.util.RandomUtil;
import org.ehcache.sample.web.rest.errors.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
private final CacheManager cacheManager;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
this.cacheManager = cacheManager;
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
this.clearUserCaches(user);
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
this.clearUserCaches(user);
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmailIgnoreCase(mail)
.filter(User::getActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
this.clearUserCaches(user);
return user;
});
}
public User registerUser(UserDTO userDTO, String password) {
userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new LoginAlreadyUsedException();
}
});
userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new EmailAlreadyUsedException();
}
});
User newUser = new User();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(userDTO.getLogin().toLowerCase());
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userDTO.getFirstName());
newUser.setLastName(userDTO.getLastName());
newUser.setEmail(userDTO.getEmail().toLowerCase());
newUser.setImageUrl(userDTO.getImageUrl());
newUser.setLangKey(userDTO.getLangKey());
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
Set<Authority> authorities = new HashSet<>();
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
this.clearUserCaches(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
private boolean removeNonActivatedUser(User existingUser){
if (existingUser.getActivated()) {
return false;
}
userRepository.delete(existingUser);
userRepository.flush();
this.clearUserCaches(existingUser);
return true;
}
public User createUser(UserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail().toLowerCase());
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
user.setActivated(true);
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
user.setAuthorities(authorities);
}
userRepository.save(user);
this.clearUserCaches(user);
log.debug("Created Information for User: {}", user);
return user;
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user
* @param lastName last name of user
* @param email email id of user
* @param langKey language key
* @param imageUrl image URL of user
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email.toLowerCase());
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
});
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update
* @return updated user
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(user -> {
this.clearUserCaches(user);
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail().toLowerCase());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}
public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
this.clearUserCaches(user);
log.debug("Deleted User: {}", user);
});
}
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
this.clearUserCaches(user);
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
this.clearUserCaches(user);
});
}
/**
* @return a list of all the authorities
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
private void clearUserCaches(User user) {
Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)).evict(user.getLogin());
Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(user.getEmail());
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/AuditEventService.java | fullstack/src/main/java/org/ehcache/sample/service/AuditEventService.java | package org.ehcache.sample.service;
import org.ehcache.sample.config.audit.AuditEventConverter;
import org.ehcache.sample.repository.PersistenceAuditEventRepository;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.Optional;
/**
* Service for managing audit events.
* <p>
* This is the default implementation to support SpringBoot Actuator AuditEventRepository
*/
@Service
@Transactional
public class AuditEventService {
private final PersistenceAuditEventRepository persistenceAuditEventRepository;
private final AuditEventConverter auditEventConverter;
public AuditEventService(
PersistenceAuditEventRepository persistenceAuditEventRepository,
AuditEventConverter auditEventConverter) {
this.persistenceAuditEventRepository = persistenceAuditEventRepository;
this.auditEventConverter = auditEventConverter;
}
public Page<AuditEvent> findAll(Pageable pageable) {
return persistenceAuditEventRepository.findAll(pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) {
return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Optional<AuditEvent> find(Long id) {
return Optional.ofNullable(persistenceAuditEventRepository.findById(id))
.filter(Optional::isPresent)
.map(Optional::get)
.map(auditEventConverter::convertToAuditEvent);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/CoordinatesService.java | fullstack/src/main/java/org/ehcache/sample/service/CoordinatesService.java | package org.ehcache.sample.service;
import org.ehcache.sample.config.ApplicationProperties;
import org.ehcache.sample.domain.Coordinates;
import org.ehcache.sample.service.dto.ResourceType;
import org.ehcache.sample.service.util.HttpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
/**
* Created by Anthony Dahanne on 2016-09-23.
*/
@Service
public class CoordinatesService {
private final String googleAPiKey;
private final HttpService httpService;
private final ObjectMapper objectMapper;
private final ResourceCallService resourceCallService;
public CoordinatesService(HttpService httpService, ObjectMapper objectMapper, ResourceCallService resourceCallService, ApplicationProperties applicationProperties) {
this.httpService = httpService;
this.objectMapper = objectMapper;
this.resourceCallService = resourceCallService;
this.googleAPiKey = applicationProperties.getGoogleApiKey();
}
public Coordinates retrieveCoordinates(String location) {
Stopwatch stopwatch = Stopwatch.createStarted();
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" +
HttpUtil.utf8Encode(location) +
"&key=" + googleAPiKey;
String responseAsString = "Not received";
try {
responseAsString = httpService.sendGet(url);
JsonNode locationNode = objectMapper.readTree(responseAsString).findValue("location");
if(locationNode != null) {
String latitude = locationNode.get("lat").asText();
String longitude = locationNode.get("lng").asText();
return new Coordinates(latitude, longitude);
}
else {
return new Coordinates("0", "0");
}
}
catch(Exception e) {
throw new RuntimeException("Can't find coordinates for " + location + "\n call to " + url + " with google response : " + responseAsString, e);
}
finally {
resourceCallService.addCall("Google Geocode Rest API", ResourceType.WEB_SERVICE, location, stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/package-info.java | fullstack/src/main/java/org/ehcache/sample/service/package-info.java | /**
* Service layer beans.
*/
package org.ehcache.sample.service;
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/ResourceCallService.java | fullstack/src/main/java/org/ehcache/sample/service/ResourceCallService.java | package org.ehcache.sample.service;
import org.ehcache.sample.service.dto.ResourceCallReport;
import org.ehcache.sample.service.dto.ResourceType;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.RequestScope;
import java.util.ArrayList;
import java.util.List;
/**
* @author Henri Tremblay
*/
@Service
@RequestScope
public class ResourceCallService {
private List<ResourceCallReport> reports = new ArrayList<>();
public void addCall(String resourceName, ResourceType type, String param, long elapsed) {
reports.add(new ResourceCallReport(resourceName, type, param, elapsed));
}
public long currentElapsed() {
return reports.stream().mapToLong(ResourceCallReport::getElapsed).sum();
}
public List<ResourceCallReport> getReports() {
return reports;
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/MailService.java | fullstack/src/main/java/org/ehcache/sample/service/MailService.java | package org.ehcache.sample.service;
import org.ehcache.sample.domain.User;
import io.github.jhipster.config.JHipsterProperties;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
/**
* Service for sending emails.
* <p>
* We use the @Async annotation to send emails asynchronously.
*/
@Service
public class MailService {
private final Logger log = LoggerFactory.getLogger(MailService.class);
private static final String USER = "user";
private static final String BASE_URL = "baseUrl";
private final JHipsterProperties jHipsterProperties;
private final JavaMailSender javaMailSender;
private final MessageSource messageSource;
private final SpringTemplateEngine templateEngine;
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
MessageSource messageSource, SpringTemplateEngine templateEngine) {
this.jHipsterProperties = jHipsterProperties;
this.javaMailSender = javaMailSender;
this.messageSource = messageSource;
this.templateEngine = templateEngine;
}
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.warn("Email could not be sent to user '{}'", to, e);
} else {
log.warn("Email could not be sent to user '{}': {}", to, e.getMessage());
}
}
}
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
sendEmail(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title");
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/ActorService.java | fullstack/src/main/java/org/ehcache/sample/service/ActorService.java | package org.ehcache.sample.service;
import org.ehcache.sample.domain.Actor;
import org.ehcache.sample.repository.ActorRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing Actor.
*/
@Service
@Transactional
public class ActorService {
private final Logger log = LoggerFactory.getLogger(ActorService.class);
private final ActorRepository actorRepository;
public ActorService(ActorRepository actorRepository) {
this.actorRepository = actorRepository;
}
/**
* Save a actor.
*
* @param actor the entity to save
* @return the persisted entity
*/
public Actor save(Actor actor) {
log.debug("Request to save Actor : {}", actor);
return actorRepository.save(actor);
}
/**
* Get all the actors.
*
* @param pageable the pagination information
* @return the list of entities
*/
@Transactional(readOnly = true)
public Page<Actor> findAll(Pageable pageable) {
log.debug("Request to get all Actors");
return actorRepository.findAll(pageable);
}
/**
* Get one actor by id.
*
* @param id the id of the entity
* @return the entity
*/
@Transactional(readOnly = true)
public Optional<Actor> findOne(Long id) {
log.debug("Request to get Actor : {}", id);
return actorRepository.findById(id);
}
/**
* Delete the actor by id.
*
* @param id the id of the entity
*/
public void delete(Long id) {
log.debug("Request to delete Actor : {}", id);
actorRepository.deleteById(id);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/WeatherService.java | fullstack/src/main/java/org/ehcache/sample/service/WeatherService.java | package org.ehcache.sample.service;
import org.ehcache.sample.config.ApplicationProperties;
import org.ehcache.sample.domain.Coordinates;
import org.ehcache.sample.service.dto.ResourceType;
import org.ehcache.sample.service.dto.WeatherReport;
import org.ehcache.sample.service.util.HttpUtil;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.google.common.base.Stopwatch;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.Locale;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import javax.cache.annotation.CacheResult;
/**
* Created by Anthony Dahanne on 2016-09-23.
*/
@Service
public class WeatherService {
private final boolean stubWebServices;
private final String darkSkyApiKey;
private final HttpService httpService;
private final CoordinatesService coordinatesService;
private final ObjectMapper objectMapper;
private final ResourceCallService resourceCallService;
public WeatherService(HttpService httpService, CoordinatesService coordinatesService, ObjectMapper objectMapper, ResourceCallService resourceCallService, ApplicationProperties applicationProperties) {
this.httpService = httpService;
this.coordinatesService = coordinatesService;
this.objectMapper = objectMapper;
this.resourceCallService = resourceCallService;
this.darkSkyApiKey = applicationProperties.getDarkSkyApiKey();
this.stubWebServices = applicationProperties.isStubWebServices();
}
@CacheResult(cacheName = "weatherReports")
public WeatherReport retrieveWeatherReport(String location, LocalDate date) {
if (stubWebServices) {
return getFakeWeatherReport(location, date);
}
// resource call report gathered in the retrieveCoordinates service
Coordinates coordinates = coordinatesService.retrieveCoordinates(location);
Stopwatch stopwatch = Stopwatch.createStarted();
String url = "https://api.darksky.net/forecast/" +
darkSkyApiKey + "/" +
coordinates.getLatitude() +
HttpUtil.utf8Encode(",") +
coordinates.getLongitude() +
HttpUtil.utf8Encode(",") +
date.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli() / 1000 + "?units=si";
String responseAsString = "Never received";
try {
responseAsString = httpService.sendGet(url);
JsonNode daily = objectMapper.readTree(responseAsString).findValue("daily");
if(daily != null) {
ArrayNode dataNode = (ArrayNode) daily.findValue("data");
return new WeatherReport(
date, location,
dataNode.get(0).get("icon").asText(),
dataNode.get(0).get("summary").asText(),
dataNode.get(0).get("temperatureMin").asDouble(),
dataNode.get(0).get("temperatureMax").asDouble());
}
else {
return new WeatherReport(date, location, "unknown", "Unknown.", Double.NaN, Double.NaN);
}
}
catch(Exception e) {
throw new RuntimeException("Can't find weather report for " + location + " for this date : " + date + "\n call to " +
url + " with darkskyapi response was : " + responseAsString, e);
}
finally {
resourceCallService.addCall("Darksky Rest API", ResourceType.WEB_SERVICE, location + " on " + date, stopwatch.elapsed(TimeUnit.MILLISECONDS));
}
}
private static final String[] WEATHERS = {
"Cloudy",
"Sunny",
"Rainy",
"Snowy"
};
private WeatherReport getFakeWeatherReport(String location, LocalDate date) {
Random rand = ThreadLocalRandom.current();
Stopwatch stopwatch = Stopwatch.createStarted();
try {
Thread.sleep(500 + rand.nextInt(500));
resourceCallService.addCall("Fake Webservice call", ResourceType.WEB_SERVICE, location, stopwatch.elapsed(TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
// ignore
}
int min = -30 + rand.nextInt(60);
int max = min + rand.nextInt(15);
String summary = WEATHERS[rand.nextInt(WEATHERS.length)];
String icon = summary.toLowerCase(Locale.US);
return new WeatherReport(date, location, summary, icon, min, max);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/HttpService.java | fullstack/src/main/java/org/ehcache/sample/service/HttpService.java | package org.ehcache.sample.service;
import org.springframework.stereotype.Service;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
/**
* Created by Anthony Dahanne on 2016-09-25.
*/
@Service
public class HttpService {
public String sendGet(String url) throws Exception {
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/ResourceCallReport.java | fullstack/src/main/java/org/ehcache/sample/service/dto/ResourceCallReport.java | package org.ehcache.sample.service.dto;
/**
* Created by Anthony Dahanne on 2016-09-25.
*/
public class ResourceCallReport {
private final String resourceName;
private final ResourceType resourceType;
private final String param;
private final long elapsed;
public ResourceCallReport(String resourceName, ResourceType resourceType, String param, long elapsed) {
this.resourceName = resourceName;
this.resourceType = resourceType;
this.param = param;
this.elapsed = elapsed;
}
public String getResourceName() {
return resourceName;
}
public ResourceType getResourceType() {
return resourceType;
}
public String getParam() {
return param;
}
public long getElapsed() {
return elapsed;
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/package-info.java | fullstack/src/main/java/org/ehcache/sample/service/dto/package-info.java | /**
* Data Transfer Objects.
*/
package org.ehcache.sample.service.dto;
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/PasswordChangeDTO.java | fullstack/src/main/java/org/ehcache/sample/service/dto/PasswordChangeDTO.java | package org.ehcache.sample.service.dto;
/**
* A DTO representing a password change required data - current and new password.
*/
public class PasswordChangeDTO {
private String currentPassword;
private String newPassword;
public PasswordChangeDTO() {
// Empty constructor needed for Jackson.
}
public PasswordChangeDTO(String currentPassword, String newPassword) {
this.currentPassword = currentPassword;
this.newPassword = newPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/UserDTO.java | fullstack/src/main/java/org/ehcache/sample/service/dto/UserDTO.java | package org.ehcache.sample.service.dto;
import org.ehcache.sample.config.Constants;
import org.ehcache.sample.domain.Authority;
import org.ehcache.sample.domain.User;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.*;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class UserDTO {
private Long id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 6)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.activated = user.getActivated();
this.imageUrl = user.getImageUrl();
this.langKey = user.getLangKey();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.authorities = user.getAuthorities().stream()
.map(Authority::getName)
.collect(Collectors.toSet());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
@Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/StarDTO.java | fullstack/src/main/java/org/ehcache/sample/service/dto/StarDTO.java | package org.ehcache.sample.service.dto;
import org.ehcache.sample.domain.Actor;
import com.google.common.base.MoreObjects;
import java.time.LocalDate;
import java.util.List;
/**
* Created by Anthony Dahanne on 2016-09-27.
*/
public class StarDTO {
private Long id;
private String firstName;
private String lastName;
private LocalDate birthDate;
private String birthLocation;
private List<WeatherReport> weatherReports;
private List<ResourceCallReport> resourceCallReports;
private long totalTimeSpent;
private String hostname;
public StarDTO(Actor actor, List<WeatherReport> weatherReports, List<ResourceCallReport> resourceCallReports, long totalTimeSpent, String hostname) {
this.id = actor.getId();
this.firstName = actor.getFirstName();
this.lastName = actor.getLastName();
this.birthDate = actor.getBirthDate();
this.birthLocation = actor.getBirthLocation();
this.weatherReports = weatherReports;
this.resourceCallReports = resourceCallReports;
this.totalTimeSpent = totalTimeSpent;
this.hostname = hostname;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getBirthLocation() {
return birthLocation;
}
public void setBirthLocation(String birthLocation) {
this.birthLocation = birthLocation;
}
public List<WeatherReport> getWeatherReports() {
return weatherReports;
}
public void setWeatherReports(List<WeatherReport> weatherReports) {
this.weatherReports = weatherReports;
}
public List<ResourceCallReport> getResourceCallReports() {
return resourceCallReports;
}
public void setResourceCallReports(List<ResourceCallReport> resourceCallReports) {
this.resourceCallReports = resourceCallReports;
}
public long getTotalTimeSpent() {
return totalTimeSpent;
}
public void setTotalTimeSpent(long totalTimeSpent) {
this.totalTimeSpent = totalTimeSpent;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("id", id)
.add("firstName", firstName)
.add("lastName", lastName)
.add("birthDate", birthDate)
.add("birthLocation", birthLocation)
.add("weatherReports", weatherReports)
.add("resourceCallReports", resourceCallReports)
.add("totalTimeSpent", totalTimeSpent)
.add("hostname", hostname)
.toString();
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/WeatherReport.java | fullstack/src/main/java/org/ehcache/sample/service/dto/WeatherReport.java | package org.ehcache.sample.service.dto;
import java.io.Serializable;
import java.time.LocalDate;
/**
* Created by Anthony Dahanne on 2016-09-23.
*/
public class WeatherReport implements Serializable {
private LocalDate date;
private String location;
private String icon;
private String summary;
private double temperatureMin;
private double temperatureMax;
public WeatherReport(LocalDate date, String location, String icon, String summary, double temperatureMin, double temperatureMax) {
this.date = date;
this.location = location;
this.icon = icon;
this.summary = summary;
this.temperatureMin = temperatureMin;
this.temperatureMax = temperatureMax;
}
public WeatherReport() {
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public double getTemperatureMin() {
return temperatureMin;
}
public void setTemperatureMin(double temperatureMin) {
this.temperatureMin = temperatureMin;
}
public double getTemperatureMax() {
return temperatureMax;
}
public void setTemperatureMax(double temperatureMax) {
this.temperatureMax = temperatureMax;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WeatherReport that = (WeatherReport) o;
if (Double.compare(that.temperatureMin, temperatureMin) != 0) return false;
if (Double.compare(that.temperatureMax, temperatureMax) != 0) return false;
if (date != null ? !date.equals(that.date) : that.date != null) return false;
if (location != null ? !location.equals(that.location) : that.location != null) return false;
if (icon != null ? !icon.equals(that.icon) : that.icon != null) return false;
return summary != null ? summary.equals(that.summary) : that.summary == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = date != null ? date.hashCode() : 0;
result = 31 * result + (location != null ? location.hashCode() : 0);
result = 31 * result + (icon != null ? icon.hashCode() : 0);
result = 31 * result + (summary != null ? summary.hashCode() : 0);
temp = Double.doubleToLongBits(temperatureMin);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(temperatureMax);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public String toString() {
return "WeatherReport{" +
"date=" + date +
", location='" + location + '\'' +
", icon='" + icon + '\'' +
", summary='" + summary + '\'' +
", temperatureMin=" + temperatureMin +
", temperatureMax=" + temperatureMax +
'}';
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/dto/ResourceType.java | fullstack/src/main/java/org/ehcache/sample/service/dto/ResourceType.java | package org.ehcache.sample.service.dto;
/**
* @author Henri Tremblay
*/
public enum ResourceType {
WEB_SERVICE, DATABASE
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/util/HttpUtil.java | fullstack/src/main/java/org/ehcache/sample/service/util/HttpUtil.java | package org.ehcache.sample.service.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* @author Henri Tremblay
*/
public final class HttpUtil {
private HttpUtil() {}
public static String utf8Encode(String url) {
return urlEncode(url, StandardCharsets.UTF_8);
}
public static String urlEncode(String url, Charset cs) {
try {
return URLEncoder.encode(url, cs.name());
}
catch(UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/util/RandomUtil.java | fullstack/src/main/java/org/ehcache/sample/service/util/RandomUtil.java | package org.ehcache.sample.service.util;
import org.apache.commons.lang3.RandomStringUtils;
/**
* Utility class for generating random Strings.
*/
public final class RandomUtil {
private static final int DEF_COUNT = 20;
private RandomUtil() {
}
/**
* Generate a password.
*
* @return the generated password
*/
public static String generatePassword() {
return RandomStringUtils.randomAlphanumeric(DEF_COUNT);
}
/**
* Generate an activation key.
*
* @return the generated activation key
*/
public static String generateActivationKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
/**
* Generate a reset key.
*
* @return the generated reset key
*/
public static String generateResetKey() {
return RandomStringUtils.randomNumeric(DEF_COUNT);
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/mapper/package-info.java | fullstack/src/main/java/org/ehcache/sample/service/mapper/package-info.java | /**
* MapStruct mappers for mapping domain objects and Data Transfer Objects.
*/
package org.ehcache.sample.service.mapper;
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/service/mapper/UserMapper.java | fullstack/src/main/java/org/ehcache/sample/service/mapper/UserMapper.java | package org.ehcache.sample.service.mapper;
import org.ehcache.sample.domain.Authority;
import org.ehcache.sample.domain.User;
import org.ehcache.sample.service.dto.UserDTO;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* Mapper for the entity User and its DTO called UserDTO.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class UserMapper {
public UserDTO userToUserDTO(User user) {
return new UserDTO(user);
}
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream()
.filter(Objects::nonNull)
.map(this::userToUserDTO)
.collect(Collectors.toList());
}
public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
if (authorities != null) {
user.setAuthorities(authorities);
}
return user;
}
}
public List<User> userDTOsToUsers(List<UserDTO> userDTOs) {
return userDTOs.stream()
.filter(Objects::nonNull)
.map(this::userDTOToUser)
.collect(Collectors.toList());
}
public User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
public Set<Authority> authoritiesFromStrings(Set<String> strings) {
return strings.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
}).collect(Collectors.toSet());
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/aop/logging/LoggingAspect.java | fullstack/src/main/java/org/ehcache/sample/aop/logging/LoggingAspect.java | package org.ehcache.sample.aop.logging;
import io.github.jhipster.config.JHipsterConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import java.util.Arrays;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut("within(org.ehcache.sample.repository..*)"+
" || within(org.ehcache.sample.service..*)"+
" || within(org.ehcache.sample.web.rest..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) {
log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
} else {
log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL");
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice
* @return result
* @throws Throwable throws IllegalArgumentException
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
if (log.isDebugEnabled()) {
log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
throw e;
}
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/Actor.java | fullstack/src/main/java/org/ehcache/sample/domain/Actor.java | package org.ehcache.sample.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Objects;
/**
* A Actor.
*/
@Entity
@Table(name = "actor")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Actor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "birth_date")
private LocalDate birthDate;
@Column(name = "birth_location")
private String birthLocation;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public Actor firstName(String firstName) {
this.firstName = firstName;
return this;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public Actor lastName(String lastName) {
this.lastName = lastName;
return this;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getBirthDate() {
return birthDate;
}
public Actor birthDate(LocalDate birthDate) {
this.birthDate = birthDate;
return this;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public String getBirthLocation() {
return birthLocation;
}
public Actor birthLocation(String birthLocation) {
this.birthLocation = birthLocation;
return this;
}
public void setBirthLocation(String birthLocation) {
this.birthLocation = birthLocation;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Actor actor = (Actor) o;
if (actor.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), actor.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "Actor{" +
"id=" + getId() +
", firstName='" + getFirstName() + "'" +
", lastName='" + getLastName() + "'" +
", birthDate='" + getBirthDate() + "'" +
", birthLocation='" + getBirthLocation() + "'" +
"}";
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/Coordinates.java | fullstack/src/main/java/org/ehcache/sample/domain/Coordinates.java | package org.ehcache.sample.domain;
/**
* Created by Anthony Dahanne on 2016-09-23.
*/
public class Coordinates {
private String latitude;
private String longitude;
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
public Coordinates(String latitude, String longitude) {
this.latitude = latitude;
this.longitude = longitude;
}
@Override
public String toString() {
return "Coordinates{" +
"latitude='" + latitude + '\'' +
", longitude='" + longitude + '\'' +
'}';
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/package-info.java | fullstack/src/main/java/org/ehcache/sample/domain/package-info.java | /**
* JPA domain objects.
*/
package org.ehcache.sample.domain;
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/Authority.java | fullstack/src/main/java/org/ehcache/sample/domain/Authority.java | package org.ehcache.sample.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* An authority (a security role) used by Spring Security.
*/
@Entity
@Table(name = "jhi_authority")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Authority authority = (Authority) o;
return !(name != null ? !name.equals(authority.name) : authority.name != null);
}
@Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/PersistentAuditEvent.java | fullstack/src/main/java/org/ehcache/sample/domain/PersistentAuditEvent.java | package org.ehcache.sample.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashMap;
import java.util.Objects;
import java.util.Map;
/**
* Persist AuditEvent managed by the Spring Boot actuator.
*
* @see org.springframework.boot.actuate.audit.AuditEvent
*/
@Entity
@Table(name = "jhi_persistent_audit_event")
public class PersistentAuditEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "event_id")
private Long id;
@NotNull
@Column(nullable = false)
private String principal;
@Column(name = "event_date")
private Instant auditEventDate;
@Column(name = "event_type")
private String auditEventType;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
private Map<String, String> data = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o;
return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "PersistentAuditEvent{" +
"principal='" + principal + '\'' +
", auditEventDate=" + auditEventDate +
", auditEventType='" + auditEventType + '\'' +
'}';
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/User.java | fullstack/src/main/java/org/ehcache/sample/domain/User.java | package org.ehcache.sample.domain;
import org.ehcache.sample.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.validation.constraints.Email;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import java.time.Instant;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 6)
@Column(name = "lang_key", length = 6)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return !(user.getId() == null || getId() == null) && Objects.equals(getId(), user.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/domain/AbstractAuditingEntity.java | fullstack/src/main/java/org/ehcache/sample/domain/AbstractAuditingEntity.java | package org.ehcache.sample.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.envers.Audited;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serializable;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Base abstract class for entities which will hold definitions for created, last modified by and created,
* last modified by date.
*/
@MappedSuperclass
@Audited
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/repository/UserRepository.java | fullstack/src/main/java/org/ehcache/sample/repository/UserRepository.java | package org.ehcache.sample.repository;
import org.ehcache.sample.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.time.Instant;
/**
* Spring Data JPA repository for the User entity.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
String USERS_BY_LOGIN_CACHE = "usersByLogin";
String USERS_BY_EMAIL_CACHE = "usersByEmail";
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndCreatedDateBefore(Instant dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmailIgnoreCase(String email);
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesById(Long id);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_LOGIN_CACHE)
Optional<User> findOneWithAuthoritiesByLogin(String login);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_EMAIL_CACHE)
Optional<User> findOneWithAuthoritiesByEmail(String email);
Page<User> findAllByLoginNot(Pageable pageable, String login);
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
ehcache/ehcache3-samples | https://github.com/ehcache/ehcache3-samples/blob/51678052dbe66701eda3b7aff483252a94345ce5/fullstack/src/main/java/org/ehcache/sample/repository/ActorRepository.java | fullstack/src/main/java/org/ehcache/sample/repository/ActorRepository.java | package org.ehcache.sample.repository;
import org.ehcache.sample.domain.Actor;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring Data repository for the Actor entity.
*/
@SuppressWarnings("unused")
@Repository
public interface ActorRepository extends JpaRepository<Actor, Long> {
List<Actor> findByLastNameIgnoreCase(String lastName);
}
| java | Apache-2.0 | 51678052dbe66701eda3b7aff483252a94345ce5 | 2026-01-05T02:40:54.100300Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.