repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
mesosphere/mesos-rxjava | mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
| import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
/**
* Builder used to create a {@link MesosClient}.
* <p>
* PLEASE NOTE: All methods in this class function as "set" rather than "copy with new value"
* @param <Send> The type of objects that will be sent to Mesos
* @param <Receive> The type of objects that are expected from Mesos
*/
public final class MesosClientBuilder<Send, Receive> {
private URI mesosUri;
private Function<Class<?>, UserAgentEntry> applicationUserAgentEntry; | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
// Path: mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
/**
* Builder used to create a {@link MesosClient}.
* <p>
* PLEASE NOTE: All methods in this class function as "set" rather than "copy with new value"
* @param <Send> The type of objects that will be sent to Mesos
* @param <Receive> The type of objects that are expected from Mesos
*/
public final class MesosClientBuilder<Send, Receive> {
private URI mesosUri;
private Function<Class<?>, UserAgentEntry> applicationUserAgentEntry; | private MessageCodec<Send> sendCodec; |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
| import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull; | * {@code onOverflow} to signal the overflow to the producer.</li>
* </ul>
*
* As an example, this may be necessary for Mesos schedulers that launch large numbers
* of tasks at a time and then request reconciliation.
*
* @param capacity number of slots available in the buffer.
* @param onOverflow action to execute if an item needs to be buffered, but there are no available slots. Null is allowed.
* @param strategy how should the {@code Observable} react to buffer overflows.
* @return this builder (allowing for further chained calls)
* @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a>
*/
@NotNull
public MesosClientBuilder<Send, Receive> onBackpressureBuffer(
final long capacity,
@Nullable final Action0 onOverflow,
@NotNull final BackpressureOverflow.Strategy strategy
) {
this.backpressureTransformer = observable -> observable.onBackpressureBuffer(capacity, onOverflow, strategy);
return this;
}
/**
* Builds the instance of {@link MesosClient} that has been configured by this builder.
* All items are expected to have non-null values, if any item is null an exception will be thrown.
* @return The configured {@link MesosClient}
*/
@NotNull
public final MesosClient<Send, Receive> build() {
return new MesosClient<>( | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntry.java
// public final class UserAgentEntry {
// @NotNull
// private final String name;
// @NotNull
// private final String version;
// @Nullable
// private final String details;
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version) {
// this(name, version, null);
// }
//
// public UserAgentEntry(@NotNull final String name, @NotNull final String version, @Nullable final String details) {
// this.name = name;
// this.version = version;
// this.details = details;
// }
//
// @NotNull
// public String getName() {
// return name;
// }
//
// @NotNull
// public String getVersion() {
// return version;
// }
//
// @Nullable
// public String getDetails() {
// return details;
// }
//
// @Override
// public boolean equals(final Object o) {
// if (this == o) {
// return true;
// }
// if (o == null || getClass() != o.getClass()) {
// return false;
// }
// final UserAgentEntry that = (UserAgentEntry) o;
// return Objects.equals(name, that.name) &&
// Objects.equals(version, that.version) &&
// Objects.equals(details, that.details);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(name, version, details);
// }
//
// @Override
// public String toString() {
// if (details != null) {
// return String.format("%s/%s (%s)", name, version, details);
// } else {
// return String.format("%s/%s", name, version);
// }
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
// Path: mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/MesosClientBuilder.java
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgentEntry;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import rx.BackpressureOverflow;
import rx.Observable;
import rx.functions.Action0;
import java.net.URI;
import java.util.Optional;
import java.util.function.Function;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull;
* {@code onOverflow} to signal the overflow to the producer.</li>
* </ul>
*
* As an example, this may be necessary for Mesos schedulers that launch large numbers
* of tasks at a time and then request reconciliation.
*
* @param capacity number of slots available in the buffer.
* @param onOverflow action to execute if an item needs to be buffered, but there are no available slots. Null is allowed.
* @param strategy how should the {@code Observable} react to buffer overflows.
* @return this builder (allowing for further chained calls)
* @see <a href="http://reactivex.io/documentation/operators/backpressure.html">ReactiveX operators documentation: backpressure operators</a>
*/
@NotNull
public MesosClientBuilder<Send, Receive> onBackpressureBuffer(
final long capacity,
@Nullable final Action0 onOverflow,
@NotNull final BackpressureOverflow.Strategy strategy
) {
this.backpressureTransformer = observable -> observable.onBackpressureBuffer(capacity, onOverflow, strategy);
return this;
}
/**
* Builds the instance of {@link MesosClient} that has been configured by this builder.
* All items are expected to have non-null values, if any item is null an exception will be thrown.
* @return The configured {@link MesosClient}
*/
@NotNull
public final MesosClient<Send, Receive> build() {
return new MesosClient<>( | checkNotNull(mesosUri), |
mesosphere/mesos-rxjava | mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/simulation/MesosServerSimulation.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
| import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.server.HttpServer;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import rx.Observable;
import rx.Subscription;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
import rx.subscriptions.MultipleAssignmentSubscription;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate; | }
LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call));
if (isSubscribePredicate.test(call)) {
if (subscribedLatch.getCount() == 0) {
final String message = "Only one event stream can be open per server";
response.setStatus(HttpResponseStatus.CONFLICT);
response.getHeaders().set("Content-Type", "test/plain;charset=utf-8");
response.writeString(message);
return response.close();
}
LOGGER.debug("Responding with event stream from source: {}", events);
response.getHeaders().setTransferEncodingChunked();
response.getHeaders().set("Content-Type", sendCodec.mediaType());
response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.getHeaders().add("Pragma", "no-cache");
final Subject<Void, Void> subject = PublishSubject.create();
final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
final Subscription actionSubscription = events
.doOnSubscribe(() -> LOGGER.debug("Event stream subscription active"))
.doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e)))
.doOnError((t) -> LOGGER.error("Error while creating response", t))
.doOnCompleted(() -> {
eventsCompletedLatch.countDown();
LOGGER.debug("Sending events complete");
if (!response.isCloseIssued()) {
response.close(true);
}
})
.map(sendCodec::encode) | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/MessageCodec.java
// public interface MessageCodec<T> {
//
// /**
// * Serialize the given {@code message} into an array of bytes.
// *
// * @param message the message to serialize
// * @return the serialized message
// */
// @NotNull
// byte[] encode(@NotNull final T message);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param bytes the bytes to deserialize
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final byte[] bytes);
//
// /**
// * Deserialize the given byte array into a message.
// *
// * @param in The {@link InputStream} to deserialize the message from
// * @return the deserialized message
// * @throws RuntimeException If an error occurs when decoding {@code bytes}. If a checked exception is possible
// * it should be wrapped in a RuntimeException.
// */
// @NotNull
// T decode(@NotNull final InputStream in);
//
// /**
// * Returns the <a target="_blank" href="https://en.wikipedia.org/wiki/Media_type">IANA media type</a> of the serialized message
// * format handled by this object.
// * <p>
// * The value returned by this method will be used in the {@code Content-Type} and {@code Accept} headers for
// * messages sent to and received from Mesos, respectively.
// *
// * @return the media type identifier
// */
// @NotNull
// String mediaType();
//
// /**
// * Renders the given {@code message} to informative, human-readable text.
// * <p>
// * The intent of this method is to allow messages to be easily read in program logs and while debugging.
// *
// * @param message the message to render
// * @return the rendered message
// */
// @NotNull
// String show(@NotNull final T message);
//
// }
// Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/simulation/MesosServerSimulation.java
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.MessageCodec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.reactivex.netty.RxNetty;
import io.reactivex.netty.protocol.http.server.HttpServer;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import rx.Observable;
import rx.Subscription;
import rx.subjects.PublishSubject;
import rx.subjects.Subject;
import rx.subscriptions.MultipleAssignmentSubscription;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
}
LOGGER.debug(RECEIVE_MARKER, "Call: {}", receiveCodec.show(call));
if (isSubscribePredicate.test(call)) {
if (subscribedLatch.getCount() == 0) {
final String message = "Only one event stream can be open per server";
response.setStatus(HttpResponseStatus.CONFLICT);
response.getHeaders().set("Content-Type", "test/plain;charset=utf-8");
response.writeString(message);
return response.close();
}
LOGGER.debug("Responding with event stream from source: {}", events);
response.getHeaders().setTransferEncodingChunked();
response.getHeaders().set("Content-Type", sendCodec.mediaType());
response.getHeaders().add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
response.getHeaders().add("Pragma", "no-cache");
final Subject<Void, Void> subject = PublishSubject.create();
final MultipleAssignmentSubscription subscription = new MultipleAssignmentSubscription();
final Subscription actionSubscription = events
.doOnSubscribe(() -> LOGGER.debug("Event stream subscription active"))
.doOnNext(e -> LOGGER.debug(SEND_MARKER, "Event: {}", sendCodec.show(e)))
.doOnError((t) -> LOGGER.error("Error while creating response", t))
.doOnCompleted(() -> {
eventsCompletedLatch.countDown();
LOGGER.debug("Sending events complete");
if (!response.isCloseIssued()) {
response.close(true);
}
})
.map(sendCodec::encode) | .map(RecordIOUtils::createChunk) |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
| import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder() | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
// Path: mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java
import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder() | .sendCodec(StringMessageCodec.UTF8_STRING) |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
| import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder()
.sendCodec(StringMessageCodec.UTF8_STRING)
.receiveCodec(StringMessageCodec.UTF8_STRING)
.mesosUri(URI.create("http://localhost:12345")) | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
// Path: mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java
import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder()
.sendCodec(StringMessageCodec.UTF8_STRING)
.receiveCodec(StringMessageCodec.UTF8_STRING)
.mesosUri(URI.create("http://localhost:12345")) | .applicationUserAgentEntry(literal(clientName, "latest")) |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
| import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder()
.sendCodec(StringMessageCodec.UTF8_STRING)
.receiveCodec(StringMessageCodec.UTF8_STRING)
.mesosUri(URI.create("http://localhost:12345"))
.applicationUserAgentEntry(literal(clientName, "latest"))
.subscribe("subscribe")
.processStream(events -> events.map(e -> Optional.<SinkOperation<String>>empty()))
.build();
final HttpClientRequest<ByteBuf> request = client.createPost
.call("ACK")
.toBlocking()
.first();
final Map<String, String> headers = headersToMap(request.getHeaders());
assertThat(headers).containsKeys("User-Agent");
final String ua = headers.get("User-Agent");
assertThat(ua).startsWith(String.format("%s/%s", clientName, "latest"));
assertThat(ua).contains("mesos-rxjava-client/");
}
@Test
public void testRequestUriFromPassedUri() throws Exception {
final Func1<String, Observable<HttpClientRequest<ByteBuf>>> createPost = MesosClient.curryCreatePost(
URI.create("http://localhost:12345/glavin/api/v1/scheduler"),
StringMessageCodec.UTF8_STRING,
StringMessageCodec.UTF8_STRING, | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/StringMessageCodec.java
// public final class StringMessageCodec implements MessageCodec<String> {
//
// @NotNull
// public static final MessageCodec<String> UTF8_STRING = new StringMessageCodec();
//
// private StringMessageCodec() {}
//
// @NotNull
// @Override
// public byte[] encode(@NotNull final String message) {
// return message.getBytes(StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final byte[] bytes) {
// return new String(bytes, StandardCharsets.UTF_8);
// }
//
// @NotNull
// @Override
// public String decode(@NotNull final InputStream in) {
// try {
// final StringBuilder sb = new StringBuilder();
// final Reader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
// final CharBuffer buffer = CharBuffer.allocate(0x800);// 2k chars (4k bytes)
// while (reader.read(buffer) != -1) {
// buffer.flip();
// sb.append(buffer);
// buffer.clear();
// }
// return sb.toString();
// } catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
//
// @NotNull
// @Override
// public String mediaType() {
// return "text/plain;charset=utf-8";
// }
//
// @NotNull
// @Override
// public String show(@NotNull final String message) {
// return message;
// }
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgent.java
// public final class UserAgent {
//
// @NotNull
// private final List<UserAgentEntry> entries;
// @NotNull
// private final String toStringValue;
//
// @SafeVarargs
// public UserAgent(@NotNull final Function<Class<?>, UserAgentEntry>... entries) {
// this.entries =
// Collections.unmodifiableList(
// Arrays.asList(entries)
// .stream()
// .map(f -> f.apply(this.getClass()))
// .collect(Collectors.toList())
// );
// this.toStringValue = this.entries
// .stream()
// .map(UserAgentEntry::toString)
// .collect(Collectors.joining(" "));
// }
//
// @NotNull
// public List<UserAgentEntry> getEntries() {
// return entries;
// }
//
// @Override
// public String toString() {
// return toStringValue;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/UserAgentEntries.java
// @NotNull
// public static Function<Class<?>, UserAgentEntry> literal(@NotNull final String name, @NotNull final String version) {
// return (Class<?> c) -> new UserAgentEntry(name, version);
// }
// Path: mesos-rxjava-client/src/test/java/com/mesosphere/mesos/rx/java/MesosClientTest.java
import com.google.common.collect.Maps;
import com.mesosphere.mesos.rx.java.test.StringMessageCodec;
import com.mesosphere.mesos.rx.java.util.UserAgent;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.http.DefaultHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;
import io.reactivex.netty.protocol.http.UnicastContentSubject;
import io.reactivex.netty.protocol.http.client.HttpClientRequest;
import io.reactivex.netty.protocol.http.client.HttpClientResponse;
import io.reactivex.netty.protocol.http.client.HttpRequestHeaders;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Observable;
import rx.functions.Func1;
import java.net.URI;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static com.mesosphere.mesos.rx.java.util.UserAgentEntries.literal;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
public final class MesosClientTest {
@Test
public void testUserAgentContains_MesosRxJavaCore_RxNetty() throws Exception {
final String clientName = "unit-tests";
final MesosClient<String, String> client = MesosClientBuilder.<String, String>newBuilder()
.sendCodec(StringMessageCodec.UTF8_STRING)
.receiveCodec(StringMessageCodec.UTF8_STRING)
.mesosUri(URI.create("http://localhost:12345"))
.applicationUserAgentEntry(literal(clientName, "latest"))
.subscribe("subscribe")
.processStream(events -> events.map(e -> Optional.<SinkOperation<String>>empty()))
.build();
final HttpClientRequest<ByteBuf> request = client.createPost
.call("ACK")
.toBlocking()
.first();
final Map<String, String> headers = headersToMap(request.getHeaders());
assertThat(headers).containsKeys("User-Agent");
final String ua = headers.get("User-Agent");
assertThat(ua).startsWith(String.format("%s/%s", clientName, "latest"));
assertThat(ua).contains("mesos-rxjava-client/");
}
@Test
public void testRequestUriFromPassedUri() throws Exception {
final Func1<String, Observable<HttpClientRequest<ByteBuf>>> createPost = MesosClient.curryCreatePost(
URI.create("http://localhost:12345/glavin/api/v1/scheduler"),
StringMessageCodec.UTF8_STRING,
StringMessageCodec.UTF8_STRING, | new UserAgent( |
mesosphere/mesos-rxjava | mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorChunkSizesTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
| import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
@RunWith(Parameterized.class)
public final class RecordIOOperatorChunkSizesTest {
@Parameters(name = "chunkSize={0}")
public static List<Integer> chunkSizes() {
return newArrayList(1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60);
}
private final int chunkSize;
public RecordIOOperatorChunkSizesTest(final int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk size must be positive");
}
this.chunkSize = chunkSize;
}
@Test
public void test() { | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
// Path: mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorChunkSizesTest.java
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
@RunWith(Parameterized.class)
public final class RecordIOOperatorChunkSizesTest {
@Parameters(name = "chunkSize={0}")
public static List<Integer> chunkSizes() {
return newArrayList(1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60);
}
private final int chunkSize;
public RecordIOOperatorChunkSizesTest(final int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk size must be positive");
}
this.chunkSize = chunkSize;
}
@Test
public void test() { | final byte[] chunk = RecordIOUtils.createChunk(TestingProtos.SUBSCRIBED.toByteArray()); |
mesosphere/mesos-rxjava | mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorChunkSizesTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
| import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
@RunWith(Parameterized.class)
public final class RecordIOOperatorChunkSizesTest {
@Parameters(name = "chunkSize={0}")
public static List<Integer> chunkSizes() {
return newArrayList(1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60);
}
private final int chunkSize;
public RecordIOOperatorChunkSizesTest(final int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk size must be positive");
}
this.chunkSize = chunkSize;
}
@Test
public void test() {
final byte[] chunk = RecordIOUtils.createChunk(TestingProtos.SUBSCRIBED.toByteArray());
final List<byte[]> bytes = RecordIOOperatorTest.partitionIntoArraysOfSize(chunk, chunkSize); | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
// Path: mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorChunkSizesTest.java
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.util.List;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
@RunWith(Parameterized.class)
public final class RecordIOOperatorChunkSizesTest {
@Parameters(name = "chunkSize={0}")
public static List<Integer> chunkSizes() {
return newArrayList(1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 60);
}
private final int chunkSize;
public RecordIOOperatorChunkSizesTest(final int chunkSize) {
if (chunkSize <= 0) {
throw new IllegalArgumentException("Chunk size must be positive");
}
this.chunkSize = chunkSize;
}
@Test
public void test() {
final byte[] chunk = RecordIOUtils.createChunk(TestingProtos.SUBSCRIBED.toByteArray());
final List<byte[]> bytes = RecordIOOperatorTest.partitionIntoArraysOfSize(chunk, chunkSize); | final List<ByteBuf> chunks = CollectionUtils.listMap(bytes, Unpooled::copiedBuffer); |
mesosphere/mesos-rxjava | mesos-rxjava-example/mesos-rxjava-example-framework/src/main/java/com/mesosphere/mesos/rx/java/example/framework/sleepy/State.java | // Path: mesos-rxjava-protobuf-client/src/main/java/com/mesosphere/mesos/rx/java/protobuf/ProtoUtils.java
// @NotNull
// public static String protoToString(@NotNull final Object message) {
// return "{ " + PROTO_TO_STRING.matcher(message.toString()).replaceAll(" ").trim() + " }";
// }
| import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import static com.mesosphere.mesos.rx.java.protobuf.ProtoUtils.protoToString; |
@NotNull
public FwId getFwId() {
return fwId;
}
public double getCpusPerTask() {
return cpusPerTask;
}
public double getMemMbPerTask() {
return memMbPerTask;
}
@NotNull
public String getResourceRole() {
return resourceRole;
}
@NotNull
public AtomicInteger getOfferCounter() {
return offerCounter;
}
@NotNull
public AtomicInteger getTotalTaskCounter() {
return totalTaskCounter;
}
public void put(final TaskId key, final TaskState value) { | // Path: mesos-rxjava-protobuf-client/src/main/java/com/mesosphere/mesos/rx/java/protobuf/ProtoUtils.java
// @NotNull
// public static String protoToString(@NotNull final Object message) {
// return "{ " + PROTO_TO_STRING.matcher(message.toString()).replaceAll(" ").trim() + " }";
// }
// Path: mesos-rxjava-example/mesos-rxjava-example-framework/src/main/java/com/mesosphere/mesos/rx/java/example/framework/sleepy/State.java
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import static com.mesosphere.mesos.rx.java.protobuf.ProtoUtils.protoToString;
@NotNull
public FwId getFwId() {
return fwId;
}
public double getCpusPerTask() {
return cpusPerTask;
}
public double getMemMbPerTask() {
return memMbPerTask;
}
@NotNull
public String getResourceRole() {
return resourceRole;
}
@NotNull
public AtomicInteger getOfferCounter() {
return offerCounter;
}
@NotNull
public AtomicInteger getTotalTaskCounter() {
return totalTaskCounter;
}
public void put(final TaskId key, final TaskState value) { | LOGGER.debug("put(key : {}, value : {})", protoToString(key), value); |
mesosphere/mesos-rxjava | mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
| import org.jetbrains.annotations.NotNull;
import java.nio.charset.StandardCharsets;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.test;
/**
* A set of utilities for dealing with the RecordIO format.
* @see <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#recordio-response-format" target="_blank">RecordIO</a>
*/
public final class RecordIOUtils {
private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
private static final int NEW_LINE_BYTE_SIZE = 1;
private RecordIOUtils() {}
@NotNull
public static byte[] createChunk(@NotNull final byte[] bytes) { | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
// Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
import org.jetbrains.annotations.NotNull;
import java.nio.charset.StandardCharsets;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.test;
/**
* A set of utilities for dealing with the RecordIO format.
* @see <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#recordio-response-format" target="_blank">RecordIO</a>
*/
public final class RecordIOUtils {
private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
private static final int NEW_LINE_BYTE_SIZE = 1;
private RecordIOUtils() {}
@NotNull
public static byte[] createChunk(@NotNull final byte[] bytes) { | checkNotNull(bytes, "bytes must not be null"); |
mesosphere/mesos-rxjava | mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/SinkOperation.java | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
| import org.jetbrains.annotations.NotNull;
import rx.functions.Action0;
import rx.functions.Action1;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
/**
* A simple object that represents a {@link T} that is to be sent to Mesos.
* <p>
* For example, when communicating with the Mesos HTTP Scheduler API, any
* <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#calls" target="_blank">Call</a>
* that isn't a
* <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#subscribe" target="_blank">SUBSCRIBE</a>
* will result in a semi-blocking request.
* <p>
* This means things like request validation (including body deserialization and field validation) are
* performed synchronously during the request. Due to this behavior, this class exists to inform the
* user of the success or failure of requests sent to the master.
* <p>
* It should be noted that this object doesn't represent the means of detecting and handling connection errors
* with Mesos. The intent is that it will be communicated to the whole event stream rather than an
* individual {@code SinkOperation}.
* <p>
* <i>NOTE</i>
* The semantics of which thread a callback ({@code onComplete} or {@code onError}) will be invoked on are undefined
* and should not be relied upon. This means that all standard thread safety/guards should be in place for the actions
* performed inside the callback.
*
* @see SinkOperations#create
*/
public final class SinkOperation<T> {
@NotNull
private final T thingToSink;
@NotNull
private final Action1<Throwable> onError;
@NotNull
private final Action0 onCompleted;
/**
* This constructor is considered an internal API and should not be used directly, instead use one of the
* factory methods defined in {@link SinkOperations}.
* @param thingToSink The {@link T} to send to Mesos
* @param onCompleted The callback invoked when HTTP 202 is returned by Mesos
* @param onError The callback invoked for an HTTP 400 or 500 status code returned by Mesos
*/
SinkOperation(
@NotNull final T thingToSink,
@NotNull final Action0 onCompleted,
@NotNull final Action1<Throwable> onError
) { | // Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/Validations.java
// public static <T> T checkNotNull(@Nullable T ref) {
// return checkNotNull(ref, null);
// }
// Path: mesos-rxjava-client/src/main/java/com/mesosphere/mesos/rx/java/SinkOperation.java
import org.jetbrains.annotations.NotNull;
import rx.functions.Action0;
import rx.functions.Action1;
import static com.mesosphere.mesos.rx.java.util.Validations.checkNotNull;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java;
/**
* A simple object that represents a {@link T} that is to be sent to Mesos.
* <p>
* For example, when communicating with the Mesos HTTP Scheduler API, any
* <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#calls" target="_blank">Call</a>
* that isn't a
* <a href="https://github.com/apache/mesos/blob/master/docs/scheduler-http-api.md#subscribe" target="_blank">SUBSCRIBE</a>
* will result in a semi-blocking request.
* <p>
* This means things like request validation (including body deserialization and field validation) are
* performed synchronously during the request. Due to this behavior, this class exists to inform the
* user of the success or failure of requests sent to the master.
* <p>
* It should be noted that this object doesn't represent the means of detecting and handling connection errors
* with Mesos. The intent is that it will be communicated to the whole event stream rather than an
* individual {@code SinkOperation}.
* <p>
* <i>NOTE</i>
* The semantics of which thread a callback ({@code onComplete} or {@code onError}) will be invoked on are undefined
* and should not be relied upon. This means that all standard thread safety/guards should be in place for the actions
* performed inside the callback.
*
* @see SinkOperations#create
*/
public final class SinkOperation<T> {
@NotNull
private final T thingToSink;
@NotNull
private final Action1<Throwable> onError;
@NotNull
private final Action0 onCompleted;
/**
* This constructor is considered an internal API and should not be used directly, instead use one of the
* factory methods defined in {@link SinkOperations}.
* @param thingToSink The {@link T} to send to Mesos
* @param onCompleted The callback invoked when HTTP 202 is returned by Mesos
* @param onError The callback invoked for an HTTP 400 or 500 status code returned by Mesos
*/
SinkOperation(
@NotNull final T thingToSink,
@NotNull final Action0 onCompleted,
@NotNull final Action1<Throwable> onError
) { | this.thingToSink = checkNotNull(thingToSink, "argument thingToSink can not be null"); |
mesosphere/mesos-rxjava | mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
| import com.google.common.primitives.Bytes;
import com.google.protobuf.AbstractMessageLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
public class RecordIOOperatorTest {
private static final List<Event> EVENT_PROTOS = newArrayList(
TestingProtos.SUBSCRIBED,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT
);
private static final List<byte[]> EVENT_CHUNKS = EVENT_PROTOS.stream()
.map(AbstractMessageLite::toByteArray) | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
// Path: mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorTest.java
import com.google.common.primitives.Bytes;
import com.google.protobuf.AbstractMessageLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
public class RecordIOOperatorTest {
private static final List<Event> EVENT_PROTOS = newArrayList(
TestingProtos.SUBSCRIBED,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT
);
private static final List<byte[]> EVENT_CHUNKS = EVENT_PROTOS.stream()
.map(AbstractMessageLite::toByteArray) | .map(RecordIOUtils::createChunk) |
mesosphere/mesos-rxjava | mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorTest.java | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
| import com.google.common.primitives.Bytes;
import com.google.protobuf.AbstractMessageLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat; | /*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
public class RecordIOOperatorTest {
private static final List<Event> EVENT_PROTOS = newArrayList(
TestingProtos.SUBSCRIBED,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT
);
private static final List<byte[]> EVENT_CHUNKS = EVENT_PROTOS.stream()
.map(AbstractMessageLite::toByteArray)
.map(RecordIOUtils::createChunk)
.collect(Collectors.toList());
@Test
public void correctlyAbleToReadEventsFromEventsBinFile() throws Exception {
final InputStream inputStream = this.getClass().getResourceAsStream("/events.bin");
final List<ByteBuf> chunks = new ArrayList<>();
final byte[] bytes = new byte[100];
int read;
while ((read = inputStream.read(bytes)) != -1) {
chunks.add(Unpooled.copiedBuffer(bytes, 0, read));
}
final List<Event> events = runTestOnChunks(chunks); | // Path: mesos-rxjava-test/src/main/java/com/mesosphere/mesos/rx/java/test/RecordIOUtils.java
// public final class RecordIOUtils {
// private static final byte NEW_LINE_BYTE = "\n".getBytes(StandardCharsets.UTF_8)[0];
// private static final int NEW_LINE_BYTE_SIZE = 1;
//
// private RecordIOUtils() {}
//
// @NotNull
// public static byte[] createChunk(@NotNull final byte[] bytes) {
// checkNotNull(bytes, "bytes must not be null");
// final byte[] messageSize = Integer.toString(bytes.length).getBytes(StandardCharsets.UTF_8);
//
// final int messageSizeLength = messageSize.length;
// final int chunkSize = messageSizeLength + NEW_LINE_BYTE_SIZE + bytes.length;
// final byte[] chunk = new byte[chunkSize];
// System.arraycopy(messageSize, 0, chunk, 0, messageSizeLength);
// chunk[messageSizeLength] = NEW_LINE_BYTE;
// System.arraycopy(bytes, 0, chunk, messageSizeLength + 1, bytes.length);
// return chunk;
// }
//
// }
//
// Path: mesos-rxjava-util/src/main/java/com/mesosphere/mesos/rx/java/util/CollectionUtils.java
// public final class CollectionUtils {
// private CollectionUtils() {}
//
// @NotNull
// public static <T, R> List<R> listMap(@NotNull final List<T> input, @NotNull final Function<T, R> mapper) {
// return input
// .stream()
// .map(mapper)
// .collect(Collectors.toList());
// }
//
// /**
// * The contract of {@link List#equals(Object)} is that a "deep equals" is performed, however the actual
// * "deep equals" depends on the elements being compared. In the case of arrays the default
// * {@link Object#equals(Object)} is used.
// * <p>
// * This method is a convenience utility to check if two lists of byte[] are "equal"
// * @param a The first List of byte[]s
// * @param b The second List of byte[]s
// * @return {@code true} if {@code a} and {@code b} are the exact same array (determined by {@code ==}) OR only if
// * {@code a} and {@code b} are the same size AND {@link Arrays#equals(byte[], byte[])} returns {@code true}
// * for every index matching element from {@code a} and {@code b}.
// */
// public static boolean deepEquals(@NotNull final List<byte[]> a, @NotNull final List<byte[]> b) {
// if (a == b) {
// return true;
// }
// if (a.size() != b.size()) {
// return false;
// }
// for (int i = 0; i < a.size(); i++) {
// if (!Arrays.equals(a.get(i), b.get(i))) {
// return false;
// }
// }
// return true;
// }
// }
// Path: mesos-rxjava-recordio/src/test/java/com/mesosphere/mesos/rx/java/recordio/RecordIOOperatorTest.java
import com.google.common.primitives.Bytes;
import com.google.protobuf.AbstractMessageLite;
import com.google.protobuf.InvalidProtocolBufferException;
import com.mesosphere.mesos.rx.java.test.RecordIOUtils;
import com.mesosphere.mesos.rx.java.util.CollectionUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.apache.mesos.v1.scheduler.Protos.Event;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
/*
* Copyright (C) 2015 Mesosphere, Inc
*
* Licensed 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.
*/
package com.mesosphere.mesos.rx.java.recordio;
public class RecordIOOperatorTest {
private static final List<Event> EVENT_PROTOS = newArrayList(
TestingProtos.SUBSCRIBED,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT,
TestingProtos.HEARTBEAT
);
private static final List<byte[]> EVENT_CHUNKS = EVENT_PROTOS.stream()
.map(AbstractMessageLite::toByteArray)
.map(RecordIOUtils::createChunk)
.collect(Collectors.toList());
@Test
public void correctlyAbleToReadEventsFromEventsBinFile() throws Exception {
final InputStream inputStream = this.getClass().getResourceAsStream("/events.bin");
final List<ByteBuf> chunks = new ArrayList<>();
final byte[] bytes = new byte[100];
int read;
while ((read = inputStream.read(bytes)) != -1) {
chunks.add(Unpooled.copiedBuffer(bytes, 0, read));
}
final List<Event> events = runTestOnChunks(chunks); | final List<Event.Type> eventTypes = CollectionUtils.listMap(events, Event::getType); |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/AuthenticationServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
// @Service
// public class SessionAuthenticationServiceImpl implements AuthenticationService {
//
// private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
//
// @Autowired
// public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
// this.sessionProvider = sessionProvider;
// this.adminTwitterId = adminTwitterId;
// }
//
// private final SessionProvider sessionProvider;
// private final Long adminTwitterId;
//
// @Override
// public Long authenticate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// session().setAttribute(CURRENT_USER_ID, user.getUserId());
// return user.getUserId();
// }
//
// @Override
// public Long getCurrentUserId() {
// return (Long) session().getAttribute(CURRENT_USER_ID);
// }
//
// @Override
// public Boolean isAuthenticated() {
// return getCurrentUserId() != null;
// }
//
// @Override
// public Boolean isAdmin() {
// return Objects.equals(getCurrentUserId(), adminTwitterId);
// }
//
// @Override
// public void logOut() {
// session().removeAttribute(CURRENT_USER_ID);
// }
//
// private HttpSession session() {
// return sessionProvider.getSession();
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.SessionAuthenticationServiceImpl;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.http.HttpSession; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AuthenticationServiceTest {
@Mock
private HttpSession session;
@Mock | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
// @Service
// public class SessionAuthenticationServiceImpl implements AuthenticationService {
//
// private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
//
// @Autowired
// public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
// this.sessionProvider = sessionProvider;
// this.adminTwitterId = adminTwitterId;
// }
//
// private final SessionProvider sessionProvider;
// private final Long adminTwitterId;
//
// @Override
// public Long authenticate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// session().setAttribute(CURRENT_USER_ID, user.getUserId());
// return user.getUserId();
// }
//
// @Override
// public Long getCurrentUserId() {
// return (Long) session().getAttribute(CURRENT_USER_ID);
// }
//
// @Override
// public Boolean isAuthenticated() {
// return getCurrentUserId() != null;
// }
//
// @Override
// public Boolean isAdmin() {
// return Objects.equals(getCurrentUserId(), adminTwitterId);
// }
//
// @Override
// public void logOut() {
// session().removeAttribute(CURRENT_USER_ID);
// }
//
// private HttpSession session() {
// return sessionProvider.getSession();
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/AuthenticationServiceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.SessionAuthenticationServiceImpl;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.http.HttpSession;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AuthenticationServiceTest {
@Mock
private HttpSession session;
@Mock | private SessionProvider sessionProvider; |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/AuthenticationServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
// @Service
// public class SessionAuthenticationServiceImpl implements AuthenticationService {
//
// private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
//
// @Autowired
// public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
// this.sessionProvider = sessionProvider;
// this.adminTwitterId = adminTwitterId;
// }
//
// private final SessionProvider sessionProvider;
// private final Long adminTwitterId;
//
// @Override
// public Long authenticate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// session().setAttribute(CURRENT_USER_ID, user.getUserId());
// return user.getUserId();
// }
//
// @Override
// public Long getCurrentUserId() {
// return (Long) session().getAttribute(CURRENT_USER_ID);
// }
//
// @Override
// public Boolean isAuthenticated() {
// return getCurrentUserId() != null;
// }
//
// @Override
// public Boolean isAdmin() {
// return Objects.equals(getCurrentUserId(), adminTwitterId);
// }
//
// @Override
// public void logOut() {
// session().removeAttribute(CURRENT_USER_ID);
// }
//
// private HttpSession session() {
// return sessionProvider.getSession();
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
| import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.SessionAuthenticationServiceImpl;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.http.HttpSession; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AuthenticationServiceTest {
@Mock
private HttpSession session;
@Mock
private SessionProvider sessionProvider;
private AuthenticationService sut;
@Before
public void ainit() {
initMocks(this);
when(sessionProvider.getSession()).thenReturn(session); | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
// @Service
// public class SessionAuthenticationServiceImpl implements AuthenticationService {
//
// private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
//
// @Autowired
// public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
// this.sessionProvider = sessionProvider;
// this.adminTwitterId = adminTwitterId;
// }
//
// private final SessionProvider sessionProvider;
// private final Long adminTwitterId;
//
// @Override
// public Long authenticate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// session().setAttribute(CURRENT_USER_ID, user.getUserId());
// return user.getUserId();
// }
//
// @Override
// public Long getCurrentUserId() {
// return (Long) session().getAttribute(CURRENT_USER_ID);
// }
//
// @Override
// public Boolean isAuthenticated() {
// return getCurrentUserId() != null;
// }
//
// @Override
// public Boolean isAdmin() {
// return Objects.equals(getCurrentUserId(), adminTwitterId);
// }
//
// @Override
// public void logOut() {
// session().removeAttribute(CURRENT_USER_ID);
// }
//
// private HttpSession session() {
// return sessionProvider.getSession();
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/AuthenticationServiceTest.java
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.SessionAuthenticationServiceImpl;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.http.HttpSession;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AuthenticationServiceTest {
@Mock
private HttpSession session;
@Mock
private SessionProvider sessionProvider;
private AuthenticationService sut;
@Before
public void ainit() {
initMocks(this);
when(sessionProvider.getSession()).thenReturn(session); | sut = new SessionAuthenticationServiceImpl(sessionProvider, 42L); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/config/FeatureConfiguration.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
// public interface FeatureStrategy {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @throws WTFDYUMException
// */
// void completeCron(Long userId) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId);
//
// /**
// * Gets the feature.
// *
// * @return the feature
// */
// Feature getFeature();
//
// /**
// * Checks for cron.
// *
// * @return whether or not this feature has a cron that should be executed
// * periodically
// */
// boolean hasCron();
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId);
// }
| import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.feature.FeatureStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Spring configuration for feature strategies beans
*/
@Configuration
public class FeatureConfiguration {
@Bean(name = "featureStrategies") | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
// public interface FeatureStrategy {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @throws WTFDYUMException
// */
// void completeCron(Long userId) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId);
//
// /**
// * Gets the feature.
// *
// * @return the feature
// */
// Feature getFeature();
//
// /**
// * Checks for cron.
// *
// * @return whether or not this feature has a cron that should be executed
// * periodically
// */
// boolean hasCron();
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/config/FeatureConfiguration.java
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.feature.FeatureStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Spring configuration for feature strategies beans
*/
@Configuration
public class FeatureConfiguration {
@Bean(name = "featureStrategies") | public Map<Feature, FeatureStrategy> featureStrategies(final List<FeatureStrategy> featureStrategies) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/config/FeatureConfiguration.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
// public interface FeatureStrategy {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @throws WTFDYUMException
// */
// void completeCron(Long userId) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId);
//
// /**
// * Gets the feature.
// *
// * @return the feature
// */
// Feature getFeature();
//
// /**
// * Checks for cron.
// *
// * @return whether or not this feature has a cron that should be executed
// * periodically
// */
// boolean hasCron();
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId);
// }
| import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.feature.FeatureStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Spring configuration for feature strategies beans
*/
@Configuration
public class FeatureConfiguration {
@Bean(name = "featureStrategies") | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
// public interface FeatureStrategy {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @throws WTFDYUMException
// */
// void completeCron(Long userId) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId);
//
// /**
// * Gets the feature.
// *
// * @return the feature
// */
// Feature getFeature();
//
// /**
// * Checks for cron.
// *
// * @return whether or not this feature has a cron that should be executed
// * periodically
// */
// boolean hasCron();
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/config/FeatureConfiguration.java
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.feature.FeatureStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Spring configuration for feature strategies beans
*/
@Configuration
public class FeatureConfiguration {
@Bean(name = "featureStrategies") | public Map<Feature, FeatureStrategy> featureStrategies(final List<FeatureStrategy> featureStrategies) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/TwitterService.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/User.java
// public class User {
//
// private long id;
//
// private String name;
//
// private String screenName;
//
// private String profileImageUrl;
//
// private String URL;
//
// public long getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getProfileImageURL() {
// return profileImageUrl;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public String getURL() {
// return URL;
// }
//
// public void setId(final long id) {
// this.id = id;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public void setProfileImageURL(final String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public void setScreenName(final String screenName) {
// this.screenName = screenName;
// }
//
// public void setURL(final String url) {
// this.URL = url;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
| import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.dto.User;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import java.util.List;
import java.util.Optional;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
/**
* The Interface TwitterService. This is used to interact with twitter.
*/
public interface TwitterService {
/**
* Complete signin.
*
* @param requestToken
* the request token returned by {@link #signin(String) signin}
* method
* @param verifier
* the oauth verifier
* @return the access token to the user account
* @throws WTFDYUMException
* if something is wrong with Twitter communication
*/
AccessToken completeSignin(RequestToken requestToken, String verifier) throws WTFDYUMException;
/**
* Gets the followers of the specified userId.
*
* If the principal is present, the request is made on the behalf of
* principal. Else, the request is made on the behalf of the application
*
* @param userId
* the user id
* @param principal
* the principal
* @return the followers
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/User.java
// public class User {
//
// private long id;
//
// private String name;
//
// private String screenName;
//
// private String profileImageUrl;
//
// private String URL;
//
// public long getId() {
// return id;
// }
//
// public String getName() {
// return name;
// }
//
// public String getProfileImageURL() {
// return profileImageUrl;
// }
//
// public String getScreenName() {
// return screenName;
// }
//
// public String getURL() {
// return URL;
// }
//
// public void setId(final long id) {
// this.id = id;
// }
//
// public void setName(final String name) {
// this.name = name;
// }
//
// public void setProfileImageURL(final String profileImageUrl) {
// this.profileImageUrl = profileImageUrl;
// }
//
// public void setScreenName(final String screenName) {
// this.screenName = screenName;
// }
//
// public void setURL(final String url) {
// this.URL = url;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/TwitterService.java
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.dto.User;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import java.util.List;
import java.util.Optional;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
/**
* The Interface TwitterService. This is used to interact with twitter.
*/
public interface TwitterService {
/**
* Complete signin.
*
* @param requestToken
* the request token returned by {@link #signin(String) signin}
* method
* @param verifier
* the oauth verifier
* @return the access token to the user account
* @throws WTFDYUMException
* if something is wrong with Twitter communication
*/
AccessToken completeSignin(RequestToken requestToken, String verifier) throws WTFDYUMException;
/**
* Gets the followers of the specified userId.
*
* If the principal is present, the request is made on the behalf of
* principal. Else, the request is made on the behalf of the application
*
* @param userId
* the user id
* @param principal
* the principal
* @return the followers
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | Set<Long> getFollowers(Long userId, Optional<Principal> principal) throws WTFDYUMException; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AdminService.java
// public interface AdminService {
// Map<Feature, Integer> countEnabledFeature(Set<Long> members);
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java
// public interface FeatureService {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// void completeCron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId, Feature feature);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId, Feature feature);
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId, Feature feature);
// }
| import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.AdminService;
import com.jeanchampemont.wtfdyum.service.FeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; | /*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AdminService.java
// public interface AdminService {
// Map<Feature, Integer> countEnabledFeature(Set<Long> members);
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java
// public interface FeatureService {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// void completeCron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId, Feature feature);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId, Feature feature);
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId, Feature feature);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.AdminService;
import com.jeanchampemont.wtfdyum.service.FeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired | public AdminServiceImpl(FeatureService featureService) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AdminService.java
// public interface AdminService {
// Map<Feature, Integer> countEnabledFeature(Set<Long> members);
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java
// public interface FeatureService {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// void completeCron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId, Feature feature);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId, Feature feature);
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId, Feature feature);
// }
| import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.AdminService;
import com.jeanchampemont.wtfdyum.service.FeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set; | /*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
public AdminServiceImpl(FeatureService featureService) {
this.featureService = featureService;
}
private final FeatureService featureService;
@Override | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AdminService.java
// public interface AdminService {
// Map<Feature, Integer> countEnabledFeature(Set<Long> members);
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java
// public interface FeatureService {
//
// /**
// * Complete cron.
// *
// * This method is called after all cron for this user have been executed
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// void completeCron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Method that should be executed periodically for this feature.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return the resulting events set
// * @throws WTFDYUMException
// * the WTFDYUM exception
// */
// Set<Event> cron(Long userId, Feature feature) throws WTFDYUMException;
//
// /**
// * Disable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was enabled and has been disabled, false
// * otherwise
// */
// boolean disableFeature(Long userId, Feature feature);
//
// /**
// * Enable the feature for this userId.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return true if the feature was disabled and has been enabled, false
// * otherwise
// */
// boolean enableFeature(Long userId, Feature feature);
//
// /**
// * Checks if is enabled.
// *
// * @param userId
// * the user id
// * @param feature
// * the feature
// * @return whether or not this feature is enabled
// */
// boolean isEnabled(Long userId, Feature feature);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.AdminService;
import com.jeanchampemont.wtfdyum.service.FeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class AdminServiceImpl implements AdminService {
@Autowired
public AdminServiceImpl(FeatureService featureService) {
this.featureService = featureService;
}
private final FeatureService featureService;
@Override | public Map<Feature, Integer> countEnabledFeature(Set<Long> members) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
| import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired | private AuthenticationService authenticationService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
| import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private AuthenticationService authenticationService;
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private AuthenticationService authenticationService;
@Autowired | private PrincipalService principalService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
| import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private AuthenticationService authenticationService;
@Autowired
private PrincipalService principalService;
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.getModel().put("authenticated", authenticationService.isAuthenticated());
modelAndView.getModel().put("admin", authenticationService.isAdmin());
}
SessionManager.setPrincipal(null);
super.postHandle(request, response, handler, modelAndView);
}
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
throws Exception {
final Long currentUserId = authenticationService.getCurrentUserId();
if (currentUserId != null) { | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.utils;
/**
* The Class AuthenticationInterceptor. This class:
*
* - adds authentication information in each model, for the templates to use. -
* add the principal to the SessionManager
*/
@Component
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
@Autowired
private AuthenticationService authenticationService;
@Autowired
private PrincipalService principalService;
@Override
public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
final ModelAndView modelAndView) throws Exception {
if (modelAndView != null) {
modelAndView.getModel().put("authenticated", authenticationService.isAuthenticated());
modelAndView.getModel().put("admin", authenticationService.isAdmin());
}
SessionManager.setPrincipal(null);
super.postHandle(request, response, handler, modelAndView);
}
@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
throws Exception {
final Long currentUserId = authenticationService.getCurrentUserId();
if (currentUserId != null) { | final Principal principal = principalService.get(currentUserId); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
| import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Objects; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class SessionAuthenticationServiceImpl implements AuthenticationService {
private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Objects;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class SessionAuthenticationServiceImpl implements AuthenticationService {
private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
@Autowired | public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
| import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Objects; | /*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class SessionAuthenticationServiceImpl implements AuthenticationService {
private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
@Autowired
public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
this.sessionProvider = sessionProvider;
this.adminTwitterId = adminTwitterId;
}
private final SessionProvider sessionProvider;
private final Long adminTwitterId;
@Override | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/SessionProvider.java
// @Component
// public class SessionProvider {
//
// public HttpSession getSession() {
// return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest().getSession();
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/SessionAuthenticationServiceImpl.java
import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.utils.SessionProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.Objects;
/*
* Copyright (C) 2015, 2016, 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class SessionAuthenticationServiceImpl implements AuthenticationService {
private static final String CURRENT_USER_ID = "CURRENT_USER_ID";
@Autowired
public SessionAuthenticationServiceImpl(SessionProvider sessionProvider, @Value("${wtfdyum.admin.twitterId}") Long adminTwitterId) {
this.sessionProvider = sessionProvider;
this.adminTwitterId = adminTwitterId;
}
private final SessionProvider sessionProvider;
private final Long adminTwitterId;
@Override | public Long authenticate(final Principal user) { |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/security/SecurityAspectTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
| import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.lang.annotation.Annotation;
import static org.mockito.Mockito.*; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.security;
@RunWith(MockitoJUnitRunner.class)
public class SecurityAspectTest {
@Mock | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/security/SecurityAspectTest.java
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.lang.annotation.Annotation;
import static org.mockito.Mockito.*;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.security;
@RunWith(MockitoJUnitRunner.class)
public class SecurityAspectTest {
@Mock | private AuthenticationService authenticationService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
| import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.feature;
/**
* This interface should be implemented by all feature's strategies.
*/
public interface FeatureStrategy {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @throws WTFDYUMException
*/
void completeCron(Long userId) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.feature;
/**
* This interface should be implemented by all feature's strategies.
*/
public interface FeatureStrategy {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @throws WTFDYUMException
*/
void completeCron(Long userId) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | Set<Event> cron(Long userId) throws WTFDYUMException; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
| import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.feature;
/**
* This interface should be implemented by all feature's strategies.
*/
public interface FeatureStrategy {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @throws WTFDYUMException
*/
void completeCron(Long userId) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/
Set<Event> cron(Long userId) throws WTFDYUMException;
/**
* Disable the feature for this userId.
*
* @param userId
* the user id
* @return true if the feature was enabled and has been disabled, false
* otherwise
*/
boolean disableFeature(Long userId);
/**
* Enable the feature for this userId.
*
* @param userId
* the user id
* @return true if the feature was disabled and has been enabled, false
* otherwise
*/
boolean enableFeature(Long userId);
/**
* Gets the feature.
*
* @return the feature
*/ | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/feature/FeatureStrategy.java
import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.feature;
/**
* This interface should be implemented by all feature's strategies.
*/
public interface FeatureStrategy {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @throws WTFDYUMException
*/
void completeCron(Long userId) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/
Set<Event> cron(Long userId) throws WTFDYUMException;
/**
* Disable the feature for this userId.
*
* @param userId
* the user id
* @return true if the feature was enabled and has been disabled, false
* otherwise
*/
boolean disableFeature(Long userId);
/**
* Enable the feature for this userId.
*
* @param userId
* the user id
* @return true if the feature was disabled and has been enabled, false
* otherwise
*/
boolean enableFeature(Long userId);
/**
* Gets the feature.
*
* @return the feature
*/ | Feature getFeature(); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/security/SecurityAspect.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
| import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.security;
@Aspect
@Component
public class SecurityAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/security/SecurityAspect.java
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.security;
@Aspect
@Component
public class SecurityAspect {
private final Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired | private AuthenticationService authenticationService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
| import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set; | /*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface FeatureService {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @param feature
* the feature
* @throws WTFDYUMException
* the WTFDYUM exception
*/
void completeCron(Long userId, Feature feature) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @param feature
* the feature
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/utils/WTFDYUMException.java
// @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "WTFDYUMException")
// public class WTFDYUMException extends Exception {
//
// private static final long serialVersionUID = 4147162490508812242L;
//
// public WTFDYUMException(final Exception e, final WTFDYUMExceptionType type) {
// super(e);
// this.type = type;
// }
//
// public WTFDYUMException(final WTFDYUMExceptionType type) {
// this.type = type;
// }
//
// private final WTFDYUMExceptionType type;
//
// public WTFDYUMExceptionType getType() {
// return type;
// }
//
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/FeatureService.java
import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.utils.WTFDYUMException;
import java.util.Set;
/*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface FeatureService {
/**
* Complete cron.
*
* This method is called after all cron for this user have been executed
*
* @param userId
* the user id
* @param feature
* the feature
* @throws WTFDYUMException
* the WTFDYUM exception
*/
void completeCron(Long userId, Feature feature) throws WTFDYUMException;
/**
* Method that should be executed periodically for this feature.
*
* @param userId
* the user id
* @param feature
* the feature
* @return the resulting events set
* @throws WTFDYUMException
* the WTFDYUM exception
*/ | Set<Event> cron(Long userId, Feature feature) throws WTFDYUMException; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/EventType.java
// public enum EventType {
// REGISTRATION("You registered to WTFDYUM!", EventSeverityType.INFO),
// FEATURE_ENABLED("You enabled %s.", EventSeverityType.INFO),
// FEATURE_DISABLED("You disabled %s.", EventSeverityType.WARNING),
// UNFOLLOW("@%s stopped following you.", EventSeverityType.WARNING),
// TWITTER_ERROR("Error while contacting twitter.", EventSeverityType.ERROR),
// RATE_LIMIT_EXCEEDED("Twitter's rate limit is exceeded, you might have too many followers.", EventSeverityType.ERROR),
// INVALID_TWITTER_CREDENTIALS(
// "Could not access your twitter account. If this error persists, please verify you allowed this application.",
// EventSeverityType.ERROR),
// CREDENTIALS_INVALID_LIMIT_REACHED(
// "All settings where disabled due to several errors while accessing your twitter account",
// EventSeverityType.ERROR),
// UNKNOWN_ERROR("An unknown error occured", EventSeverityType.ERROR);
//
// private EventType(final String message, final EventSeverityType severity) {
// this.message = message;
// this.severity = severity;
// }
//
// private String message;
//
// private EventSeverityType severity;
//
// public String getMessage() {
// return message;
// }
//
// public EventSeverityType getSeverity() {
// return severity;
// }
// }
| import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jeanchampemont.wtfdyum.dto.type.EventType;
import java.time.LocalDateTime;
import java.util.Objects; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.dto;
public class Event {
public Event() {
// left deliberately empty
}
| // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/EventType.java
// public enum EventType {
// REGISTRATION("You registered to WTFDYUM!", EventSeverityType.INFO),
// FEATURE_ENABLED("You enabled %s.", EventSeverityType.INFO),
// FEATURE_DISABLED("You disabled %s.", EventSeverityType.WARNING),
// UNFOLLOW("@%s stopped following you.", EventSeverityType.WARNING),
// TWITTER_ERROR("Error while contacting twitter.", EventSeverityType.ERROR),
// RATE_LIMIT_EXCEEDED("Twitter's rate limit is exceeded, you might have too many followers.", EventSeverityType.ERROR),
// INVALID_TWITTER_CREDENTIALS(
// "Could not access your twitter account. If this error persists, please verify you allowed this application.",
// EventSeverityType.ERROR),
// CREDENTIALS_INVALID_LIMIT_REACHED(
// "All settings where disabled due to several errors while accessing your twitter account",
// EventSeverityType.ERROR),
// UNKNOWN_ERROR("An unknown error occured", EventSeverityType.ERROR);
//
// private EventType(final String message, final EventSeverityType severity) {
// this.message = message;
// this.severity = severity;
// }
//
// private String message;
//
// private EventSeverityType severity;
//
// public String getMessage() {
// return message;
// }
//
// public EventSeverityType getSeverity() {
// return severity;
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.jeanchampemont.wtfdyum.dto.type.EventType;
import java.time.LocalDateTime;
import java.util.Objects;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.dto;
public class Event {
public Event() {
// left deliberately empty
}
| public Event(final EventType type, final String additionalData) { |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/web/AjaxController.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
// public interface UserService {
//
// void addEvent(Long userId, Event event);
//
// boolean applyLimit(Long userId, UserLimitType type);
//
// Set<Feature> getEnabledFeatures(Long userId);
//
// List<Event> getRecentEvents(Long userId, int count);
//
// List<Event> getRecentEvents(Long userId, int count, int start);
//
// void resetLimit(Long userId, UserLimitType type);
// }
| import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; | /*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.web;
@Controller
@RequestMapping(path = "/ajax")
public class AjaxController {
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
// public interface UserService {
//
// void addEvent(Long userId, Event event);
//
// boolean applyLimit(Long userId, UserLimitType type);
//
// Set<Feature> getEnabledFeatures(Long userId);
//
// List<Event> getRecentEvents(Long userId, int count);
//
// List<Event> getRecentEvents(Long userId, int count, int start);
//
// void resetLimit(Long userId, UserLimitType type);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/web/AjaxController.java
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.web;
@Controller
@RequestMapping(path = "/ajax")
public class AjaxController {
@Autowired | private UserService userService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/web/AjaxController.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
// public interface UserService {
//
// void addEvent(Long userId, Event event);
//
// boolean applyLimit(Long userId, UserLimitType type);
//
// Set<Feature> getEnabledFeatures(Long userId);
//
// List<Event> getRecentEvents(Long userId, int count);
//
// List<Event> getRecentEvents(Long userId, int count, int start);
//
// void resetLimit(Long userId, UserLimitType type);
// }
| import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView; | /*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.web;
@Controller
@RequestMapping(path = "/ajax")
public class AjaxController {
@Autowired
private UserService userService;
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/service/AuthenticationService.java
// public interface AuthenticationService {
//
// /**
// * Authenticate.
// *
// * @param user
// * the user
// * @return the connected userId
// */
// Long authenticate(Principal user);
//
// /**
// * Gets the current user id.
// *
// * @return the current user id
// */
// Long getCurrentUserId();
//
// /**
// * Checks if the current user is authenticated.
// *
// * @return the boolean
// */
// Boolean isAuthenticated();
//
// /**
// * @return whether or not the current user is an admin.
// */
// Boolean isAdmin();
//
// /**
// * Log out.
// */
// void logOut();
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
// public interface UserService {
//
// void addEvent(Long userId, Event event);
//
// boolean applyLimit(Long userId, UserLimitType type);
//
// Set<Feature> getEnabledFeatures(Long userId);
//
// List<Event> getRecentEvents(Long userId, int count);
//
// List<Event> getRecentEvents(Long userId, int count, int start);
//
// void resetLimit(Long userId, UserLimitType type);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/web/AjaxController.java
import com.jeanchampemont.wtfdyum.service.AuthenticationService;
import com.jeanchampemont.wtfdyum.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/*
* Copyright (C) 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.web;
@Controller
@RequestMapping(path = "/ajax")
public class AjaxController {
@Autowired
private UserService userService;
@Autowired | private AuthenticationService authenticationService; |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/UserLimitType.java
// public enum UserLimitType {
// CREDENTIALS_INVALID(5);
//
// private UserLimitType(final int limitValue) {
// this.limitValue = limitValue;
// }
//
// private int limitValue;
//
// public int getLimitValue() {
// return limitValue;
// }
// }
| import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.dto.type.UserLimitType;
import java.util.List;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface UserService {
void addEvent(Long userId, Event event);
| // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/UserLimitType.java
// public enum UserLimitType {
// CREDENTIALS_INVALID(5);
//
// private UserLimitType(final int limitValue) {
// this.limitValue = limitValue;
// }
//
// private int limitValue;
//
// public int getLimitValue() {
// return limitValue;
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.dto.type.UserLimitType;
import java.util.List;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface UserService {
void addEvent(Long userId, Event event);
| boolean applyLimit(Long userId, UserLimitType type); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/UserLimitType.java
// public enum UserLimitType {
// CREDENTIALS_INVALID(5);
//
// private UserLimitType(final int limitValue) {
// this.limitValue = limitValue;
// }
//
// private int limitValue;
//
// public int getLimitValue() {
// return limitValue;
// }
// }
| import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.dto.type.UserLimitType;
import java.util.List;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface UserService {
void addEvent(Long userId, Event event);
boolean applyLimit(Long userId, UserLimitType type);
| // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Event.java
// public class Event {
//
// public Event() {
// // left deliberately empty
// }
//
// public Event(final EventType type, final String additionalData) {
// this.type = type;
// this.additionalData = additionalData;
// }
//
// private EventType type;
//
// private String additionalData;
//
// private LocalDateTime creationDateTime;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Event other = (Event) obj;
// if (additionalData == null) {
// if (other.additionalData != null) {
// return false;
// }
// } else if (!additionalData.equals(other.additionalData)) {
// return false;
// }
// if (creationDateTime == null) {
// if (other.creationDateTime != null) {
// return false;
// }
// } else if (!creationDateTime.equals(other.creationDateTime)) {
// return false;
// }
// if (type != other.type) {
// return false;
// }
// return true;
// }
//
// public String getAdditionalData() {
// return additionalData;
// }
//
// public LocalDateTime getCreationDateTime() {
// return creationDateTime;
// }
//
// @JsonIgnore
// public String getMessage() {
// return String.format(type.getMessage(), additionalData);
// }
//
// public EventType getType() {
// return type;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(this.type, this.creationDateTime, this.additionalData);
// }
//
// public void setAdditionalData(final String additionalData) {
// this.additionalData = additionalData;
// }
//
// public void setCreationDateTime(final LocalDateTime creationDateTime) {
// this.creationDateTime = creationDateTime;
// }
//
// public void setType(final EventType type) {
// this.type = type;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/type/UserLimitType.java
// public enum UserLimitType {
// CREDENTIALS_INVALID(5);
//
// private UserLimitType(final int limitValue) {
// this.limitValue = limitValue;
// }
//
// private int limitValue;
//
// public int getLimitValue() {
// return limitValue;
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/UserService.java
import com.jeanchampemont.wtfdyum.dto.Event;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.dto.type.UserLimitType;
import java.util.List;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface UserService {
void addEvent(Long userId, Event event);
boolean applyLimit(Long userId, UserLimitType type);
| Set<Feature> getEnabledFeatures(Long userId); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/config/WebMvcConfiguration.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java
// @Component
// public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
//
// @Autowired
// private AuthenticationService authenticationService;
//
// @Autowired
// private PrincipalService principalService;
//
// @Override
// public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
// final ModelAndView modelAndView) throws Exception {
// if (modelAndView != null) {
// modelAndView.getModel().put("authenticated", authenticationService.isAuthenticated());
// modelAndView.getModel().put("admin", authenticationService.isAdmin());
// }
// SessionManager.setPrincipal(null);
// super.postHandle(request, response, handler, modelAndView);
// }
//
// @Override
// public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
// throws Exception {
// final Long currentUserId = authenticationService.getCurrentUserId();
// if (currentUserId != null) {
// final Principal principal = principalService.get(currentUserId);
// SessionManager.setPrincipal(principal);
// }
// return super.preHandle(request, response, handler);
// }
// }
| import com.jeanchampemont.wtfdyum.utils.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Configuration for Spring MVC
*/
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/utils/AuthenticationInterceptor.java
// @Component
// public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
//
// @Autowired
// private AuthenticationService authenticationService;
//
// @Autowired
// private PrincipalService principalService;
//
// @Override
// public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
// final ModelAndView modelAndView) throws Exception {
// if (modelAndView != null) {
// modelAndView.getModel().put("authenticated", authenticationService.isAuthenticated());
// modelAndView.getModel().put("admin", authenticationService.isAdmin());
// }
// SessionManager.setPrincipal(null);
// super.postHandle(request, response, handler, modelAndView);
// }
//
// @Override
// public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
// throws Exception {
// final Long currentUserId = authenticationService.getCurrentUserId();
// if (currentUserId != null) {
// final Principal principal = principalService.get(currentUserId);
// SessionManager.setPrincipal(principal);
// }
// return super.preHandle(request, response, handler);
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/config/WebMvcConfiguration.java
import com.jeanchampemont.wtfdyum.utils.AuthenticationInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.config;
/**
* Configuration for Spring MVC
*/
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
@Autowired | private AuthenticationInterceptor authenticationInterceptor; |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/FollowersServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/FollowersServiceImpl.java
// @Service
// public class FollowersServiceImpl implements FollowersService {
//
// private static final String FOLLOWERS_KEY_PREFIX = "FOLLOWERS_";
//
// private static final String TEMP_FOLLOWERS_KEY_PREFIX = "TEMP_FOLLOWERS_";
//
// @Autowired
// public FollowersServiceImpl(final RedisTemplate<String, Long> longRedisTemplate) {
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public Set<Long> getUnfollowers(final Long userId, final Set<Long> currentFollowersId) {
// longRedisTemplate.opsForSet().add(tempFollowersKey(userId),
// currentFollowersId.toArray(new Long[currentFollowersId.size()]));
//
// final Set<Long> unfollowers = longRedisTemplate.opsForSet().difference(followersKey(userId),
// tempFollowersKey(userId));
// longRedisTemplate.delete(tempFollowersKey(userId));
// return unfollowers;
// }
//
// @Override
// public void saveFollowers(final Long userId, final Set<Long> followersId) {
// longRedisTemplate.delete(followersKey(userId));
// longRedisTemplate.opsForSet().add(followersKey(userId), followersId.toArray(new Long[followersId.size()]));
// }
//
// private String followersKey(final Long userId) {
// return new StringBuilder(FOLLOWERS_KEY_PREFIX).append(userId.toString()).toString();
// }
//
// private String tempFollowersKey(final Long userId) {
// return new StringBuilder(TEMP_FOLLOWERS_KEY_PREFIX).append(userId.toString()).toString();
// }
// }
| import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.service.impl.FollowersServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class FollowersServiceTest {
| // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/FollowersServiceImpl.java
// @Service
// public class FollowersServiceImpl implements FollowersService {
//
// private static final String FOLLOWERS_KEY_PREFIX = "FOLLOWERS_";
//
// private static final String TEMP_FOLLOWERS_KEY_PREFIX = "TEMP_FOLLOWERS_";
//
// @Autowired
// public FollowersServiceImpl(final RedisTemplate<String, Long> longRedisTemplate) {
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public Set<Long> getUnfollowers(final Long userId, final Set<Long> currentFollowersId) {
// longRedisTemplate.opsForSet().add(tempFollowersKey(userId),
// currentFollowersId.toArray(new Long[currentFollowersId.size()]));
//
// final Set<Long> unfollowers = longRedisTemplate.opsForSet().difference(followersKey(userId),
// tempFollowersKey(userId));
// longRedisTemplate.delete(tempFollowersKey(userId));
// return unfollowers;
// }
//
// @Override
// public void saveFollowers(final Long userId, final Set<Long> followersId) {
// longRedisTemplate.delete(followersKey(userId));
// longRedisTemplate.opsForSet().add(followersKey(userId), followersId.toArray(new Long[followersId.size()]));
// }
//
// private String followersKey(final Long userId) {
// return new StringBuilder(FOLLOWERS_KEY_PREFIX).append(userId.toString()).toString();
// }
//
// private String tempFollowersKey(final Long userId) {
// return new StringBuilder(TEMP_FOLLOWERS_KEY_PREFIX).append(userId.toString()).toString();
// }
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/FollowersServiceTest.java
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.service.impl.FollowersServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class FollowersServiceTest {
| private FollowersServiceImpl sut; |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/AdminServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
// @Service
// public class AdminServiceImpl implements AdminService {
//
// @Autowired
// public AdminServiceImpl(FeatureService featureService) {
// this.featureService = featureService;
// }
//
// private final FeatureService featureService;
//
// @Override
// public Map<Feature, Integer> countEnabledFeature(Set<Long> members) {
// Map<Feature, Integer> result = new HashMap<>();
// for (Feature f : Feature.values()) {
// int count = 0;
// for (Long member : members) {
// if (featureService.isEnabled(member, f)) {
// count++;
// }
// }
// result.put(f, count);
// }
// return result;
// }
// }
| import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.impl.AdminServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map; | /*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AdminServiceTest {
@Mock
private FeatureService featureService;
private AdminService sut;
@Before
public void init() {
initMocks(this); | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
// @Service
// public class AdminServiceImpl implements AdminService {
//
// @Autowired
// public AdminServiceImpl(FeatureService featureService) {
// this.featureService = featureService;
// }
//
// private final FeatureService featureService;
//
// @Override
// public Map<Feature, Integer> countEnabledFeature(Set<Long> members) {
// Map<Feature, Integer> result = new HashMap<>();
// for (Feature f : Feature.values()) {
// int count = 0;
// for (Long member : members) {
// if (featureService.isEnabled(member, f)) {
// count++;
// }
// }
// result.put(f, count);
// }
// return result;
// }
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/AdminServiceTest.java
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.impl.AdminServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
/*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AdminServiceTest {
@Mock
private FeatureService featureService;
private AdminService sut;
@Before
public void init() {
initMocks(this); | sut = new AdminServiceImpl(featureService); |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/AdminServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
// @Service
// public class AdminServiceImpl implements AdminService {
//
// @Autowired
// public AdminServiceImpl(FeatureService featureService) {
// this.featureService = featureService;
// }
//
// private final FeatureService featureService;
//
// @Override
// public Map<Feature, Integer> countEnabledFeature(Set<Long> members) {
// Map<Feature, Integer> result = new HashMap<>();
// for (Feature f : Feature.values()) {
// int count = 0;
// for (Long member : members) {
// if (featureService.isEnabled(member, f)) {
// count++;
// }
// }
// result.put(f, count);
// }
// return result;
// }
// }
| import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.impl.AdminServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map; | /*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AdminServiceTest {
@Mock
private FeatureService featureService;
private AdminService sut;
@Before
public void init() {
initMocks(this);
sut = new AdminServiceImpl(featureService);
}
@Test
public void countEnabledFeatureNominalTest() {
Set<Long> ids = new HashSet<>(Arrays.asList(42L, 45L)); | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Feature.java
// public enum Feature {
//
// NOTIFY_UNFOLLOW("Send me a direct message when someone stops following me", "unfollow notifications"),
//
// TWEET_UNFOLLOW("Send a public tweet with @mention when someone stops following me", "unfollow tweet");
//
// private Feature(final String message, final String shortName) {
// this.message = message;
// this.shortName = shortName;
// }
//
// private String message;
//
// private String shortName;
//
// public String getMessage() {
// return message;
// }
//
// public String getShortName() {
// return shortName;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/AdminServiceImpl.java
// @Service
// public class AdminServiceImpl implements AdminService {
//
// @Autowired
// public AdminServiceImpl(FeatureService featureService) {
// this.featureService = featureService;
// }
//
// private final FeatureService featureService;
//
// @Override
// public Map<Feature, Integer> countEnabledFeature(Set<Long> members) {
// Map<Feature, Integer> result = new HashMap<>();
// for (Feature f : Feature.values()) {
// int count = 0;
// for (Long member : members) {
// if (featureService.isEnabled(member, f)) {
// count++;
// }
// }
// result.put(f, count);
// }
// return result;
// }
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/AdminServiceTest.java
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Feature;
import com.jeanchampemont.wtfdyum.service.impl.AdminServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
/*
* Copyright (C) 2018 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class AdminServiceTest {
@Mock
private FeatureService featureService;
private AdminService sut;
@Before
public void init() {
initMocks(this);
sut = new AdminServiceImpl(featureService);
}
@Test
public void countEnabledFeatureNominalTest() {
Set<Long> ids = new HashSet<>(Arrays.asList(42L, 45L)); | when(featureService.isEnabled(42L, Feature.NOTIFY_UNFOLLOW)).thenReturn(true); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
| import com.jeanchampemont.wtfdyum.dto.Principal;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface PrincipalService {
int countMembers();
| // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
import com.jeanchampemont.wtfdyum.dto.Principal;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
public interface PrincipalService {
int countMembers();
| Principal get(Long id); |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/PrincipalServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java
// @Service
// public class PrincipalServiceImpl implements PrincipalService {
//
// private static final String MEMBERS_KEY = "MEMBERS";
//
// @Autowired
// public PrincipalServiceImpl(final RedisTemplate<String, Principal> principalRedisTemplate,
// final RedisTemplate<String, Long> longRedisTemplate) {
// this.principalRedisTemplate = principalRedisTemplate;
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Principal> principalRedisTemplate;
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public int countMembers() {
// return longRedisTemplate.opsForSet().size(MEMBERS_KEY).intValue();
// }
//
// @Override
// public Principal get(final Long id) {
// Preconditions.checkNotNull(id);
// return principalRedisTemplate.opsForValue().get(id.toString());
// }
//
// @Override
// public Set<Long> getMembers() {
// return longRedisTemplate.opsForSet().members(MEMBERS_KEY);
// }
//
// @Override
// public void saveUpdate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// principalRedisTemplate.opsForValue().set(user.getUserId().toString(), user);
// longRedisTemplate.opsForSet().add(MEMBERS_KEY, user.getUserId());
// }
//
// }
| import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.PrincipalServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class PrincipalServiceTest {
private PrincipalService sut;
@Mock
private RedisTemplate<String, Long> longRedisTemplate;
@Mock | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java
// @Service
// public class PrincipalServiceImpl implements PrincipalService {
//
// private static final String MEMBERS_KEY = "MEMBERS";
//
// @Autowired
// public PrincipalServiceImpl(final RedisTemplate<String, Principal> principalRedisTemplate,
// final RedisTemplate<String, Long> longRedisTemplate) {
// this.principalRedisTemplate = principalRedisTemplate;
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Principal> principalRedisTemplate;
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public int countMembers() {
// return longRedisTemplate.opsForSet().size(MEMBERS_KEY).intValue();
// }
//
// @Override
// public Principal get(final Long id) {
// Preconditions.checkNotNull(id);
// return principalRedisTemplate.opsForValue().get(id.toString());
// }
//
// @Override
// public Set<Long> getMembers() {
// return longRedisTemplate.opsForSet().members(MEMBERS_KEY);
// }
//
// @Override
// public void saveUpdate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// principalRedisTemplate.opsForValue().set(user.getUserId().toString(), user);
// longRedisTemplate.opsForSet().add(MEMBERS_KEY, user.getUserId());
// }
//
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/PrincipalServiceTest.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.PrincipalServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class PrincipalServiceTest {
private PrincipalService sut;
@Mock
private RedisTemplate<String, Long> longRedisTemplate;
@Mock | private RedisTemplate<String, Principal> principalRedisTemplate; |
jchampemont/WTFDYUM | src/test/java/com/jeanchampemont/wtfdyum/service/PrincipalServiceTest.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java
// @Service
// public class PrincipalServiceImpl implements PrincipalService {
//
// private static final String MEMBERS_KEY = "MEMBERS";
//
// @Autowired
// public PrincipalServiceImpl(final RedisTemplate<String, Principal> principalRedisTemplate,
// final RedisTemplate<String, Long> longRedisTemplate) {
// this.principalRedisTemplate = principalRedisTemplate;
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Principal> principalRedisTemplate;
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public int countMembers() {
// return longRedisTemplate.opsForSet().size(MEMBERS_KEY).intValue();
// }
//
// @Override
// public Principal get(final Long id) {
// Preconditions.checkNotNull(id);
// return principalRedisTemplate.opsForValue().get(id.toString());
// }
//
// @Override
// public Set<Long> getMembers() {
// return longRedisTemplate.opsForSet().members(MEMBERS_KEY);
// }
//
// @Override
// public void saveUpdate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// principalRedisTemplate.opsForValue().set(user.getUserId().toString(), user);
// longRedisTemplate.opsForSet().add(MEMBERS_KEY, user.getUserId());
// }
//
// }
| import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.PrincipalServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class PrincipalServiceTest {
private PrincipalService sut;
@Mock
private RedisTemplate<String, Long> longRedisTemplate;
@Mock
private RedisTemplate<String, Principal> principalRedisTemplate;
@Mock
private ValueOperations<String, Principal> valueOperations;
@Mock
private SetOperations<String, Long> setOperations;
@Before
public void ainit() {
initMocks(this); | // Path: src/main/java/com/jeanchampemont/wtfdyum/WTFDYUMApplication.java
// @SpringBootApplication
// @EnableScheduling
// public class WTFDYUMApplication {
//
// @Bean
// public Clock clock() {
// return Clock.systemDefaultZone();
// }
//
// public static void main(final String[] args) {
// SpringApplication.run(WTFDYUMApplication.class, args);
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java
// @Service
// public class PrincipalServiceImpl implements PrincipalService {
//
// private static final String MEMBERS_KEY = "MEMBERS";
//
// @Autowired
// public PrincipalServiceImpl(final RedisTemplate<String, Principal> principalRedisTemplate,
// final RedisTemplate<String, Long> longRedisTemplate) {
// this.principalRedisTemplate = principalRedisTemplate;
// this.longRedisTemplate = longRedisTemplate;
// }
//
// private final RedisTemplate<String, Principal> principalRedisTemplate;
//
// private final RedisTemplate<String, Long> longRedisTemplate;
//
// @Override
// public int countMembers() {
// return longRedisTemplate.opsForSet().size(MEMBERS_KEY).intValue();
// }
//
// @Override
// public Principal get(final Long id) {
// Preconditions.checkNotNull(id);
// return principalRedisTemplate.opsForValue().get(id.toString());
// }
//
// @Override
// public Set<Long> getMembers() {
// return longRedisTemplate.opsForSet().members(MEMBERS_KEY);
// }
//
// @Override
// public void saveUpdate(final Principal user) {
// Preconditions.checkNotNull(user);
// Preconditions.checkNotNull(user.getUserId());
//
// principalRedisTemplate.opsForValue().set(user.getUserId().toString(), user);
// longRedisTemplate.opsForSet().add(MEMBERS_KEY, user.getUserId());
// }
//
// }
// Path: src/test/java/com/jeanchampemont/wtfdyum/service/PrincipalServiceTest.java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import static org.mockito.MockitoAnnotations.initMocks;
import com.jeanchampemont.wtfdyum.WTFDYUMApplication;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.impl.PrincipalServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = WTFDYUMApplication.class)
public class PrincipalServiceTest {
private PrincipalService sut;
@Mock
private RedisTemplate<String, Long> longRedisTemplate;
@Mock
private RedisTemplate<String, Principal> principalRedisTemplate;
@Mock
private ValueOperations<String, Principal> valueOperations;
@Mock
private SetOperations<String, Long> setOperations;
@Before
public void ainit() {
initMocks(this); | sut = new PrincipalServiceImpl(principalRedisTemplate, longRedisTemplate); |
jchampemont/WTFDYUM | src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
| import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set; | /*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class PrincipalServiceImpl implements PrincipalService {
private static final String MEMBERS_KEY = "MEMBERS";
@Autowired | // Path: src/main/java/com/jeanchampemont/wtfdyum/dto/Principal.java
// public class Principal {
//
// public Principal() {
// // left deliberately empty
// }
//
// public Principal(final Long userId, final String token, final String tokenSecret) {
// this.userId = userId;
// this.token = token;
// this.tokenSecret = tokenSecret;
// }
//
// private Long userId;
//
// private String token;
//
// private String tokenSecret;
//
// @Override
// public boolean equals(final Object obj) {
// if (this == obj) {
// return true;
// }
// if (obj == null) {
// return false;
// }
// if (getClass() != obj.getClass()) {
// return false;
// }
// final Principal other = (Principal) obj;
// if (token == null) {
// if (other.token != null) {
// return false;
// }
// } else if (!token.equals(other.token)) {
// return false;
// }
// if (tokenSecret == null) {
// if (other.tokenSecret != null) {
// return false;
// }
// } else if (!tokenSecret.equals(other.tokenSecret)) {
// return false;
// }
// if (userId == null) {
// if (other.userId != null) {
// return false;
// }
// } else if (!userId.equals(other.userId)) {
// return false;
// }
// return true;
// }
//
// public String getToken() {
// return token;
// }
//
// public String getTokenSecret() {
// return tokenSecret;
// }
//
// public Long getUserId() {
// return userId;
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(token, tokenSecret, userId);
// }
//
// public void setToken(final String token) {
// this.token = token;
// }
//
// public void setTokenSecret(final String tokenSecret) {
// this.tokenSecret = tokenSecret;
// }
//
// public void setUserId(final Long userId) {
// this.userId = userId;
// }
// }
//
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/PrincipalService.java
// public interface PrincipalService {
//
// int countMembers();
//
// Principal get(Long id);
//
// Set<Long> getMembers();
//
// void saveUpdate(Principal user);
// }
// Path: src/main/java/com/jeanchampemont/wtfdyum/service/impl/PrincipalServiceImpl.java
import com.google.common.base.Preconditions;
import com.jeanchampemont.wtfdyum.dto.Principal;
import com.jeanchampemont.wtfdyum.service.PrincipalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Set;
/*
* Copyright (C) 2015, 2016 WTFDYUM
*
* This file is part of the WTFDYUM project.
*
* Licensed 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.
*/
package com.jeanchampemont.wtfdyum.service.impl;
@Service
public class PrincipalServiceImpl implements PrincipalService {
private static final String MEMBERS_KEY = "MEMBERS";
@Autowired | public PrincipalServiceImpl(final RedisTemplate<String, Principal> principalRedisTemplate, |
persado/stevia | src/main/java/com/persado/oss/quality/stevia/selenium/core/WebController.java | // Path: src/main/java/com/persado/oss/quality/stevia/network/http/HttpCookie.java
// public class HttpCookie implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private String key;
// private String value;
//
// public HttpCookie(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
// public void setKey(String key) {
// this.key = key;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
//
// }
| import com.persado.oss.quality.stevia.network.http.HttpCookie;
import com.persado.oss.quality.stevia.selenium.core.controllers.commonapi.KeyInfo;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.io.IOException;
import java.util.List;
import java.util.Map; | */
String getTableElementSpecificHeaderLocator(String locator, String elementName, String headerName);
/**
* Constructs the locator of an element for specific row and column of a table.
*
* @param locator the table locator
* @param row the row the element is
* @param column the column the element is
* @return the locator, with the specific row and column embedded
*/
String getTableElementSpecificRowAndColumnLocator(String locator, String row, String column);
/**
* Gets the value of an element attribute.
*
* @param locator the element locator
* @param attribute the attribute value you want to retrieve
* @return the attribute value
*/
String getAttributeValue(String locator,String attribute);
/**
* Gets the cookie by name.
*
* @param name the name
* @return an HttpCookie
*/ | // Path: src/main/java/com/persado/oss/quality/stevia/network/http/HttpCookie.java
// public class HttpCookie implements Serializable{
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
//
// private String key;
// private String value;
//
// public HttpCookie(String key, String value) {
// this.key = key;
// this.value = value;
// }
//
// public String getKey() {
// return key;
// }
// public void setKey(String key) {
// this.key = key;
// }
// public String getValue() {
// return value;
// }
// public void setValue(String value) {
// this.value = value;
// }
//
//
// }
// Path: src/main/java/com/persado/oss/quality/stevia/selenium/core/WebController.java
import com.persado.oss.quality.stevia.network.http.HttpCookie;
import com.persado.oss.quality.stevia.selenium.core.controllers.commonapi.KeyInfo;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import java.io.IOException;
import java.util.List;
import java.util.Map;
*/
String getTableElementSpecificHeaderLocator(String locator, String elementName, String headerName);
/**
* Constructs the locator of an element for specific row and column of a table.
*
* @param locator the table locator
* @param row the row the element is
* @param column the column the element is
* @return the locator, with the specific row and column embedded
*/
String getTableElementSpecificRowAndColumnLocator(String locator, String row, String column);
/**
* Gets the value of an element attribute.
*
* @param locator the element locator
* @param attribute the attribute value you want to retrieve
* @return the attribute value
*/
String getAttributeValue(String locator,String attribute);
/**
* Gets the cookie by name.
*
* @param name the name
* @return an HttpCookie
*/ | HttpCookie getCookieByName(String name); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/TranslatePoint.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
| public double getYTranslation() {
return yTranslation;
}
public void setYTranslation(double yTranslation) {
this.yTranslation = yTranslation;
}
public double getZTranslation() {
return zTranslation;
}
public void setZTranslation(double zTranslation) {
this.zTranslation = zTranslation;
}
public void setTranslations(double x, double y, double z) {
setXTranslation(x);
setYTranslation(y);
setZTranslation(z);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/TranslatePoint.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
public double getYTranslation() {
return yTranslation;
}
public void setYTranslation(double yTranslation) {
this.yTranslation = yTranslation;
}
public double getZTranslation() {
return zTranslation;
}
public void setZTranslation(double zTranslation) {
this.zTranslation = zTranslation;
}
public void setTranslations(double x, double y, double z) {
setXTranslation(x);
setYTranslation(y);
setZTranslation(z);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| throw new NoModuleException();
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Clamp.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Clamp extends Module {
double lowerBound = 0.0;
double upperBound = 1.0;
public Clamp() {
super(1);
}
public double getLowerBound() {
return lowerBound;
}
public void setLowerBound(double lowerBound) {
this.lowerBound = lowerBound;
}
public double getUpperBound() {
return upperBound;
}
public void setUpperBound(double upperBound) {
this.upperBound = upperBound;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Clamp.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Clamp extends Module {
double lowerBound = 0.0;
double upperBound = 1.0;
public Clamp() {
super(1);
}
public double getLowerBound() {
return lowerBound;
}
public void setLowerBound(double lowerBound) {
this.lowerBound = lowerBound;
}
public double getUpperBound() {
return upperBound;
}
public void setUpperBound(double upperBound) {
this.upperBound = upperBound;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Min.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Min extends Module {
public Min() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Min.java
import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Min extends Module {
public Min() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Invert.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Invert extends Module {
public Invert() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Invert.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Invert extends Module {
public Invert() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/ScaleBias.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class ScaleBias extends Module {
/// Default bias for the noise::module::ScaleBias noise module.
public static final double DEFAULT_BIAS = 0.0;
/// Default scale for the noise::module::ScaleBias noise module.
public static final double DEFAULT_SCALE = 1.0;
/// Bias to apply to the scaled output value from the source module.
double bias = DEFAULT_BIAS;
/// Scaling factor to apply to the output value from the source
/// module.
double scale = DEFAULT_SCALE;
public ScaleBias() {
super(1);
}
public double getBias() {
return bias;
}
public void setBias(double bias) {
this.bias = bias;
}
public double getScale() {
return scale;
}
public void setScale(double scale) {
this.scale = scale;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/ScaleBias.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class ScaleBias extends Module {
/// Default bias for the noise::module::ScaleBias noise module.
public static final double DEFAULT_BIAS = 0.0;
/// Default scale for the noise::module::ScaleBias noise module.
public static final double DEFAULT_SCALE = 1.0;
/// Bias to apply to the scaled output value from the source module.
double bias = DEFAULT_BIAS;
/// Scaling factor to apply to the output value from the source
/// module.
double scale = DEFAULT_SCALE;
public ScaleBias() {
super(1);
}
public double getBias() {
return bias;
}
public void setBias(double bias) {
this.bias = bias;
}
public double getScale() {
return scale;
}
public void setScale(double scale) {
this.scale = scale;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/Cache.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
| import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module;
public class Cache extends Module {
/// The cached output value at the cached input value.
double cachedValue;
/// Determines if a cached output value is stored in this noise
/// module.
boolean isCached = false;
// @a x coordinate of the cached input value.
double xCache;
/// @a y coordinate of the cached input value.
double yCache;
/// @a z coordinate of the cached input value.
double zCache;
public Cache() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public void SetSourceModule(int index, Module sourceModule) {
super.SetSourceModule(index, sourceModule);
isCached = false;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/Cache.java
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module;
public class Cache extends Module {
/// The cached output value at the cached input value.
double cachedValue;
/// Determines if a cached output value is stored in this noise
/// module.
boolean isCached = false;
// @a x coordinate of the cached input value.
double xCache;
/// @a y coordinate of the cached input value.
double yCache;
/// @a z coordinate of the cached input value.
double zCache;
public Cache() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public void SetSourceModule(int index, Module sourceModule) {
super.SetSourceModule(index, sourceModule);
isCached = false;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/Module.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
| import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module;
public abstract class Module {
protected Module[] SourceModule;
public Module(int sourceModuleCount) {
SourceModule = null;
// Create an array of pointers to all source modules required by this
// noise module. Set these pointers to NULL.
if (sourceModuleCount > 0) {
SourceModule = new Module[sourceModuleCount];
for (int i = 0; i < sourceModuleCount; i++) {
SourceModule[i] = null;
}
} else {
SourceModule = null;
}
}
public Module getSourceModule(int index) {
if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) { | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module;
public abstract class Module {
protected Module[] SourceModule;
public Module(int sourceModuleCount) {
SourceModule = null;
// Create an array of pointers to all source modules required by this
// noise module. Set these pointers to NULL.
if (sourceModuleCount > 0) {
SourceModule = new Module[sourceModuleCount];
for (int i = 0; i < sourceModuleCount; i++) {
SourceModule[i] = null;
}
} else {
SourceModule = null;
}
}
public Module getSourceModule(int index) {
if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) { | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/model/Line.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
| /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the displacement of a line segment.
*
* This model returns an output value from a noise module given the
* one-dimensional coordinate of an input value located on a line segment, which
* can be used as displacements.
*
* This class is useful for creating: - roads and rivers - disaffected college
* students
*
* To generate an output value, pass an input value between 0.0 and 1.0 to the
* GetValue() method. 0.0 represents the start position of the line segment and
* 1.0 represents the end position of the line segment.
*/
public class Line {
// A flag that specifies whether the value is to be attenuated
// (moved toward 0.0) as the ends of the line segment are approached.
boolean attenuate = false;
// A pointer to the noise module used to generate the output values.
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/model/Line.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the displacement of a line segment.
*
* This model returns an output value from a noise module given the
* one-dimensional coordinate of an input value located on a line segment, which
* can be used as displacements.
*
* This class is useful for creating: - roads and rivers - disaffected college
* students
*
* To generate an output value, pass an input value between 0.0 and 1.0 to the
* GetValue() method. 0.0 represents the start position of the line segment and
* 1.0 represents the end position of the line segment.
*/
public class Line {
// A flag that specifies whether the value is to be attenuated
// (moved toward 0.0) as the ends of the line segment are approached.
boolean attenuate = false;
// A pointer to the noise module used to generate the output values.
| Module module;
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/model/Line.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
| *
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the one-dimensional
* coordinate of the specified input value located on the line segment.
*
* @param p The distance along the line segment (ranges from 0.0 to 1.0)
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
* @pre The start and end points of the line segment were specified.
*
* The output value is generated by the noise module passed to the
* SetModule() method. This value may be attenuated (moved toward 0.0)
* as @a p approaches either end of the line segment; this is the
* default behavior.
*
* If the value is not to be attenuated, @a p can safely range outside
* the 0.0 to 1.0 range; the output value will be extrapolated along
* the line that this segment is part of.
*/
public double getValue(double p) {
if (module == null)
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/model/Line.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
*
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the one-dimensional
* coordinate of the specified input value located on the line segment.
*
* @param p The distance along the line segment (ranges from 0.0 to 1.0)
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
* @pre The start and end points of the line segment were specified.
*
* The output value is generated by the noise module passed to the
* SetModule() method. This value may be attenuated (moved toward 0.0)
* as @a p approaches either end of the line segment; this is the
* default behavior.
*
* If the value is not to be attenuated, @a p can safely range outside
* the 0.0 to 1.0 range; the output value will be extrapolated along
* the line that this segment is part of.
*/
public double getValue(double p) {
if (module == null)
| throw new NoModuleException();
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/model/Sphere.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the surface of a sphere.
*
* @image html modelsphere.png
*
* This model returns an output value from a noise module given the
* coordinates of an input value located on the surface of a sphere.
*
* To generate an output value, pass the (latitude, longitude)
* coordinates of an input value to the GetValue() method.
*
* This model is useful for creating: - seamless textures that can be
* mapped onto a sphere - terrain height maps for entire planets
*
* This sphere has a radius of 1.0 unit and its center is located at the
* origin.
*/
public class Sphere {
Module module;
/**
* Constructor
*
* @param module The noise module that is used to generate the output
* values.
*/
public Sphere(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the noise module that is used to generate the output values.
*
* @returns A reference to the noise module.
* @pre A noise module was passed to the SetModule() method.
*/
public Module getModule() {
return module;
}
/**
* Sets the noise module that is used to generate the output values.
*
* @param module The noise module that is used to generate the output
* values.
*
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the (latitude,
* longitude) coordinates of the specified input value located on the
* surface of the sphere.
*
* @param lat The latitude of the input value, in degrees.
* @param lon The longitude of the input value, in degrees.
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
*
* This output value is generated by the noise module passed to the
* SetModule() method.
*
* Use a negative latitude if the input value is located on the
* southern hemisphere.
*
* Use a negative longitude if the input value is located on the
* western hemisphere.
*/
public double getValue(double lat, double log) {
if (module == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/model/Sphere.java
import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the surface of a sphere.
*
* @image html modelsphere.png
*
* This model returns an output value from a noise module given the
* coordinates of an input value located on the surface of a sphere.
*
* To generate an output value, pass the (latitude, longitude)
* coordinates of an input value to the GetValue() method.
*
* This model is useful for creating: - seamless textures that can be
* mapped onto a sphere - terrain height maps for entire planets
*
* This sphere has a radius of 1.0 unit and its center is located at the
* origin.
*/
public class Sphere {
Module module;
/**
* Constructor
*
* @param module The noise module that is used to generate the output
* values.
*/
public Sphere(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the noise module that is used to generate the output values.
*
* @returns A reference to the noise module.
* @pre A noise module was passed to the SetModule() method.
*/
public Module getModule() {
return module;
}
/**
* Sets the noise module that is used to generate the output values.
*
* @param module The noise module that is used to generate the output
* values.
*
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the (latitude,
* longitude) coordinates of the specified input value located on the
* surface of the sphere.
*
* @param lat The latitude of the input value, in degrees.
* @param lon The longitude of the input value, in degrees.
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
*
* This output value is generated by the noise module passed to the
* SetModule() method.
*
* Use a negative latitude if the input value is located on the
* southern hemisphere.
*
* Use a negative longitude if the input value is located on the
* western hemisphere.
*/
public double getValue(double lat, double log) {
if (module == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Terrace.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
| // Make room for the new control point at the specified position within
// the control point array. The position is determined by the value of
// the control point; the control points must be sorted by value within
// that array.
double[] newControlPoints = new double[controlPointCount + 1];
for (int i = 0; i < controlPointCount; i++) {
if (i < insertionPos) {
newControlPoints[i] = ControlPoints[i];
} else {
newControlPoints[i + 1] = ControlPoints[i];
}
}
ControlPoints = newControlPoints;
++controlPointCount;
// Now that we've made room for the new control point within the array,
// add the new control point.
ControlPoints[insertionPos] = value;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Terrace.java
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
// Make room for the new control point at the specified position within
// the control point array. The position is determined by the value of
// the control point; the control points must be sorted by value within
// that array.
double[] newControlPoints = new double[controlPointCount + 1];
for (int i = 0; i < controlPointCount; i++) {
if (i < insertionPos) {
newControlPoints[i] = ControlPoints[i];
} else {
newControlPoints[i + 1] = ControlPoints[i];
}
}
ControlPoints = newControlPoints;
++controlPointCount;
// Now that we've made room for the new control point within the array,
// add the new control point.
ControlPoints[insertionPos] = value;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| throw new NoModuleException();
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/model/Plane.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the surface of a plane.
*
* This model returns an output value from a noise module given the coordinates
* of an input value located on the surface of an ( @a x,
*
* @a z ) plane.
*
* To generate an output value, pass the ( @a x, @a z ) coordinates of an
* input value to the GetValue() method.
*
* This model is useful for creating: - two-dimensional textures - terrain
* height maps for local areas
*
* This plane extends infinitely in both directions.
*/
public class Plane {
Module module;
/**
* Constructor
*
* @param module The noise module that is used to generate the output
* values.
*/
public Plane(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the noise module that is used to generate the output values.
*
* @returns A reference to the noise module.
* @pre A noise module was passed to the SetModule() method.
*/
public Module getModule() {
return module;
}
/**
* Sets the noise module that is used to generate the output values.
*
* @param module The noise module that is used to generate the output
* values.
*
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the ( @a x, @a z )
* coordinates of the specified input value located on the surface of the
* plane.
*
* @param x The @a x coordinate of the input value.
* @param z The @a z coordinate of the input value.
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
*
* This output value is generated by the noise module passed to the
* SetModule() method.
*/
double getValue(double x, double z) {
if (module == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/model/Plane.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.model;
/**
* Model that defines the surface of a plane.
*
* This model returns an output value from a noise module given the coordinates
* of an input value located on the surface of an ( @a x,
*
* @a z ) plane.
*
* To generate an output value, pass the ( @a x, @a z ) coordinates of an
* input value to the GetValue() method.
*
* This model is useful for creating: - two-dimensional textures - terrain
* height maps for local areas
*
* This plane extends infinitely in both directions.
*/
public class Plane {
Module module;
/**
* Constructor
*
* @param module The noise module that is used to generate the output
* values.
*/
public Plane(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the noise module that is used to generate the output values.
*
* @returns A reference to the noise module.
* @pre A noise module was passed to the SetModule() method.
*/
public Module getModule() {
return module;
}
/**
* Sets the noise module that is used to generate the output values.
*
* @param module The noise module that is used to generate the output
* values.
*
* This noise module must exist for the lifetime of this object,
* until you pass a new noise module to this method.
*/
public void setModule(Module module) {
if (module == null)
throw new IllegalArgumentException("module cannot be null");
this.module = module;
}
/**
* Returns the output value from the noise module given the ( @a x, @a z )
* coordinates of the specified input value located on the surface of the
* plane.
*
* @param x The @a x coordinate of the input value.
* @param z The @a z coordinate of the input value.
* @return The output value from the noise module.
* @pre A noise module was passed to the SetModule() method.
*
* This output value is generated by the noise module passed to the
* SetModule() method.
*/
double getValue(double x, double z) {
if (module == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Curve.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
import java.util.ArrayList;
| for (insertionPos = 0; insertionPos < controlPoints.size(); insertionPos++) {
if (inputValue < controlPoints.get(insertionPos).inputValue) {
// We found the array index in which to insert the new control point.
// Exit now.
break;
} else if (inputValue == controlPoints.get(insertionPos).inputValue) {
// Each control point is required to contain a unique input value, so
// throw an exception.
throw new IllegalArgumentException("inputValue must be unique");
}
}
return insertionPos;
}
protected void InsertAtPos(int insertionPos, double inputValue, double outputValue) {
ControlPoint newPoint = new ControlPoint();
newPoint.inputValue = inputValue;
newPoint.outputValue = outputValue;
controlPoints.add(insertionPos, newPoint);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Curve.java
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
import java.util.ArrayList;
for (insertionPos = 0; insertionPos < controlPoints.size(); insertionPos++) {
if (inputValue < controlPoints.get(insertionPos).inputValue) {
// We found the array index in which to insert the new control point.
// Exit now.
break;
} else if (inputValue == controlPoints.get(insertionPos).inputValue) {
// Each control point is required to contain a unique input value, so
// throw an exception.
throw new IllegalArgumentException("inputValue must be unique");
}
}
return insertionPos;
}
protected void InsertAtPos(int insertionPos, double inputValue, double outputValue) {
ControlPoint newPoint = new ControlPoint();
newPoint.inputValue = inputValue;
newPoint.outputValue = outputValue;
controlPoints.add(insertionPos, newPoint);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null)
| throw new NoModuleException();
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Displace.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Displace extends Module {
public Displace() {
super(4);
}
@Override
public int GetSourceModuleCount() {
return 4;
}
public Module GetXDisplaceModule() {
if (SourceModule == null || SourceModule[1] == null) { | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Displace.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Displace extends Module {
public Displace() {
super(4);
}
@Override
public int GetSourceModuleCount() {
return 4;
}
public Module GetXDisplaceModule() {
if (SourceModule == null || SourceModule[1] == null) { | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Select.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
| /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Select extends Module {
/// Default edge-falloff value for the noise::module::Select noise module.
public static final double DEFAULT_SELECT_EDGE_FALLOFF = 0.0;
/// Default lower bound of the selection range for the
/// noise::module::Select noise module.
public static final double DEFAULT_SELECT_LOWER_BOUND = -1.0;
/// Default upper bound of the selection range for the
/// noise::module::Select noise module.
public static final double DEFAULT_SELECT_UPPER_BOUND = 1.0;
/// Edge-falloff value.
double edgeFalloff = DEFAULT_SELECT_EDGE_FALLOFF;
/// Lower bound of the selection range.
double lowerBound = DEFAULT_SELECT_LOWER_BOUND;
/// Upper bound of the selection range.
double upperBound = DEFAULT_SELECT_UPPER_BOUND;
public Select() {
super(3);
}
public Module getControlModule() {
if (SourceModule == null || SourceModule[2] == null) {
| // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Select.java
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Select extends Module {
/// Default edge-falloff value for the noise::module::Select noise module.
public static final double DEFAULT_SELECT_EDGE_FALLOFF = 0.0;
/// Default lower bound of the selection range for the
/// noise::module::Select noise module.
public static final double DEFAULT_SELECT_LOWER_BOUND = -1.0;
/// Default upper bound of the selection range for the
/// noise::module::Select noise module.
public static final double DEFAULT_SELECT_UPPER_BOUND = 1.0;
/// Edge-falloff value.
double edgeFalloff = DEFAULT_SELECT_EDGE_FALLOFF;
/// Lower bound of the selection range.
double lowerBound = DEFAULT_SELECT_LOWER_BOUND;
/// Upper bound of the selection range.
double upperBound = DEFAULT_SELECT_UPPER_BOUND;
public Select() {
super(3);
}
public Module getControlModule() {
if (SourceModule == null || SourceModule[2] == null) {
| throw new NoModuleException();
|
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Power.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Power extends Module {
public Power() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Power.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Power extends Module {
public Power() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Add.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Add extends Module {
public Add() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Add.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Add extends Module {
public Add() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Blend.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Blend extends Module {
public Blend() {
super(3);
}
public Module getControlModule() {
if (SourceModule[2] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Blend.java
import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Blend extends Module {
public Blend() {
super(3);
}
public Module getControlModule() {
if (SourceModule[2] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Multiply.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Multiply extends Module {
public Multiply() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Multiply.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Multiply extends Module {
public Multiply() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/ScalePoint.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | }
public void setxScale(double xScale) {
this.xScale = xScale;
}
public double getyScale() {
return yScale;
}
public void setyScale(double yScale) {
this.yScale = yScale;
}
public double getzScale() {
return zScale;
}
public void setzScale(double zScale) {
this.zScale = zScale;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/ScalePoint.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
}
public void setxScale(double xScale) {
this.xScale = xScale;
}
public double getyScale() {
return yScale;
}
public void setyScale(double yScale) {
this.yScale = yScale;
}
public double getzScale() {
return zScale;
}
public void setzScale(double zScale) {
this.zScale = zScale;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Exponent.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Exponent extends Module {
public static final double DEFAULT_EXPONENT = 1.0;
protected double exponent = DEFAULT_EXPONENT;
public Exponent() {
super(1);
}
public double getExponent() {
return exponent;
}
public void setExponent(double exponent) {
this.exponent = exponent;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Exponent.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Exponent extends Module {
public static final double DEFAULT_EXPONENT = 1.0;
protected double exponent = DEFAULT_EXPONENT;
public Exponent() {
super(1);
}
public double getExponent() {
return exponent;
}
public void setExponent(double exponent) {
this.exponent = exponent;
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/combiner/Max.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Max extends Module {
public Max() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/combiner/Max.java
import net.royawesome.jlibnoise.module.Module;
import net.royawesome.jlibnoise.Utils;
import net.royawesome.jlibnoise.exception.NoModuleException;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.combiner;
public class Max extends Module {
public Max() {
super(2);
}
@Override
public int GetSourceModuleCount() {
return 2;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule[0] == null) | throw new NoModuleException(); |
RoyAwesome/jlibnoise | src/main/java/net/royawesome/jlibnoise/module/modifier/Abs.java | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
| import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module; | /* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Abs extends Module {
public Abs() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule == null) | // Path: src/main/java/net/royawesome/jlibnoise/exception/NoModuleException.java
// public class NoModuleException extends NoiseException {
//
// }
//
// Path: src/main/java/net/royawesome/jlibnoise/module/Module.java
// public abstract class Module {
// protected Module[] SourceModule;
//
// public Module(int sourceModuleCount) {
// SourceModule = null;
//
// // Create an array of pointers to all source modules required by this
// // noise module. Set these pointers to NULL.
// if (sourceModuleCount > 0) {
// SourceModule = new Module[sourceModuleCount];
// for (int i = 0; i < sourceModuleCount; i++) {
// SourceModule[i] = null;
// }
// } else {
// SourceModule = null;
// }
//
// }
//
// public Module getSourceModule(int index) {
// if (index >= GetSourceModuleCount() || index < 0 || SourceModule[index] == null) {
// throw new NoModuleException();
// }
// return (SourceModule[index]);
//
// }
//
// public void SetSourceModule(int index, Module sourceModule) {
// if (SourceModule == null)
// return;
// if (index >= GetSourceModuleCount() || index < 0) {
// throw new IllegalArgumentException("Index must be between 0 and GetSourceMoudleCount()");
// }
// SourceModule[index] = sourceModule;
// }
//
// public abstract int GetSourceModuleCount();
//
// public abstract double GetValue(double x, double y, double z);
// }
// Path: src/main/java/net/royawesome/jlibnoise/module/modifier/Abs.java
import net.royawesome.jlibnoise.exception.NoModuleException;
import net.royawesome.jlibnoise.module.Module;
/* Copyright (C) 2011 Garrett Fleenor
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3.0 of the License, or (at
your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
License (COPYING.txt) for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
This is a port of libnoise ( http://libnoise.sourceforge.net/index.html ). Original implementation by Jason Bevins
*/
package net.royawesome.jlibnoise.module.modifier;
public class Abs extends Module {
public Abs() {
super(1);
}
@Override
public int GetSourceModuleCount() {
return 1;
}
@Override
public double GetValue(double x, double y, double z) {
if (SourceModule == null) | throw new NoModuleException(); |
dexter/elianto | src/main/java/it/cnr/isti/hpc/dexter/annotate/util/ConllDocument.java | // Path: src/main/java/it/cnr/isti/hpc/dexter/annotate/bean/DocumentContent.java
// public class DocumentContent implements Serializable {
// List<DocumentField> content;
//
// public DocumentContent() {
// content = new ArrayList<DocumentField>();
// }
//
// public List<DocumentField> getContent() {
// return content;
// }
//
// public void setContent(List<DocumentField> content) {
// this.content = content;
// }
//
// public void addField(String name, String value) {
// content.add(new DocumentField(name, value));
// }
//
// public static class DocumentField implements Serializable {
// String name;
// String value;
//
// public DocumentField(String name, String value) {
// super();
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// }
//
// }
| import it.cnr.isti.hpc.dexter.annotate.bean.DocumentContent;
import java.util.List;
import com.google.gson.Gson; | /**
* Copyright 2014 Diego Ceccarelli
*
* Licensed 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.
*/
/**
* Copyright 2014 Diego Ceccarelli
*
* Licensed 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.
*/
package it.cnr.isti.hpc.dexter.annotate.util;
/**
* @author Diego Ceccarelli <diego.ceccarelli@isti.cnr.it>
*
* Created on Feb 11, 2014
*/
public class ConllDocument {
private static Gson gson = new Gson();
Document document;
String external_id;
String internal_id;
String collection;
public ConllDocument() {
}
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
}
public String getExternal_id() {
return external_id;
}
public void setExternal_id(String external_id) {
this.external_id = external_id;
}
public String getInternal_id() {
return internal_id;
}
public void setInternal_id(String internal_id) {
this.internal_id = internal_id;
}
public String getCollection() {
return collection;
}
| // Path: src/main/java/it/cnr/isti/hpc/dexter/annotate/bean/DocumentContent.java
// public class DocumentContent implements Serializable {
// List<DocumentField> content;
//
// public DocumentContent() {
// content = new ArrayList<DocumentField>();
// }
//
// public List<DocumentField> getContent() {
// return content;
// }
//
// public void setContent(List<DocumentField> content) {
// this.content = content;
// }
//
// public void addField(String name, String value) {
// content.add(new DocumentField(name, value));
// }
//
// public static class DocumentField implements Serializable {
// String name;
// String value;
//
// public DocumentField(String name, String value) {
// super();
// this.name = name;
// this.value = value;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getValue() {
// return value;
// }
//
// public void setValue(String value) {
// this.value = value;
// }
//
// }
//
// }
// Path: src/main/java/it/cnr/isti/hpc/dexter/annotate/util/ConllDocument.java
import it.cnr.isti.hpc.dexter.annotate.bean.DocumentContent;
import java.util.List;
import com.google.gson.Gson;
/**
* Copyright 2014 Diego Ceccarelli
*
* Licensed 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.
*/
/**
* Copyright 2014 Diego Ceccarelli
*
* Licensed 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.
*/
package it.cnr.isti.hpc.dexter.annotate.util;
/**
* @author Diego Ceccarelli <diego.ceccarelli@isti.cnr.it>
*
* Created on Feb 11, 2014
*/
public class ConllDocument {
private static Gson gson = new Gson();
Document document;
String external_id;
String internal_id;
String collection;
public ConllDocument() {
}
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
}
public String getExternal_id() {
return external_id;
}
public void setExternal_id(String external_id) {
this.external_id = external_id;
}
public String getInternal_id() {
return internal_id;
}
public void setInternal_id(String internal_id) {
this.internal_id = internal_id;
}
public String getCollection() {
return collection;
}
| public DocumentContent getContent() { |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/workspace/ArgonOptionListener.java | // Path: src/main/java/de/axxepta/oxygen/api/BaseXConnectionWrapper.java
// public class BaseXConnectionWrapper {
//
// private static final Logger logger = LogManager.getLogger(BaseXConnectionWrapper.class);
// static Connection connection;
// private static String host = null;
//
// public static void refreshFromOptions(boolean defaults) {
// final String host = ArgonOptionPage.getOption(KEY_BASEX_HOST, defaults);
// BaseXConnectionWrapper.host = host;
// final String user = ArgonOptionPage.getOption(KEY_BASEX_USERNAME, defaults);
// final String pass = ArgonOptionPage.getOption(KEY_BASEX_PASSWORD, defaults);
// final int port = Integer.parseInt(ArgonOptionPage.getOption(KEY_BASEX_HTTP_PORT, defaults));
//
// logger.info("refreshFromOptions " + host + " " + port + " " + user + " " + pass);
// try {
// connection = ClassFactory.getInstance().getRestConnection(host, port, user, pass);
// } catch (URISyntaxException er) {
// connection = null;
// }
//
// ConnectionWrapper.init();
//
// }
//
// public static void refreshDefaults() {
// try {
// connection = ClassFactory.getInstance().getRestConnection("localhost:8984/rest", 8984, "admin", "admin");
// } catch (URISyntaxException er) {
// connection = null;
// }
// }
//
// public static void refreshDefaults(String host, int port, String user, String password) {
// try {
// connection = ClassFactory.getInstance().getRestConnection(host, port, user, password);
// } catch (URISyntaxException er) {
// connection = null;
// }
// }
//
// public static Connection getConnection() {
// if (host == null) {
// refreshFromOptions(false);
// }
// return connection;
// }
// }
| import de.axxepta.oxygen.api.BaseXConnectionWrapper;
import ro.sync.exml.workspace.api.options.WSOptionChangedEvent;
import ro.sync.exml.workspace.api.options.WSOptionListener; | package de.axxepta.oxygen.workspace;
/**
* @author Markus on 20.10.2015.
*/
public class ArgonOptionListener extends WSOptionListener {
public ArgonOptionListener(String s) {
super(s);
}
@Override
public void optionValueChanged(WSOptionChangedEvent wsOptionChangedEvent) { | // Path: src/main/java/de/axxepta/oxygen/api/BaseXConnectionWrapper.java
// public class BaseXConnectionWrapper {
//
// private static final Logger logger = LogManager.getLogger(BaseXConnectionWrapper.class);
// static Connection connection;
// private static String host = null;
//
// public static void refreshFromOptions(boolean defaults) {
// final String host = ArgonOptionPage.getOption(KEY_BASEX_HOST, defaults);
// BaseXConnectionWrapper.host = host;
// final String user = ArgonOptionPage.getOption(KEY_BASEX_USERNAME, defaults);
// final String pass = ArgonOptionPage.getOption(KEY_BASEX_PASSWORD, defaults);
// final int port = Integer.parseInt(ArgonOptionPage.getOption(KEY_BASEX_HTTP_PORT, defaults));
//
// logger.info("refreshFromOptions " + host + " " + port + " " + user + " " + pass);
// try {
// connection = ClassFactory.getInstance().getRestConnection(host, port, user, pass);
// } catch (URISyntaxException er) {
// connection = null;
// }
//
// ConnectionWrapper.init();
//
// }
//
// public static void refreshDefaults() {
// try {
// connection = ClassFactory.getInstance().getRestConnection("localhost:8984/rest", 8984, "admin", "admin");
// } catch (URISyntaxException er) {
// connection = null;
// }
// }
//
// public static void refreshDefaults(String host, int port, String user, String password) {
// try {
// connection = ClassFactory.getInstance().getRestConnection(host, port, user, password);
// } catch (URISyntaxException er) {
// connection = null;
// }
// }
//
// public static Connection getConnection() {
// if (host == null) {
// refreshFromOptions(false);
// }
// return connection;
// }
// }
// Path: src/main/java/de/axxepta/oxygen/workspace/ArgonOptionListener.java
import de.axxepta.oxygen.api.BaseXConnectionWrapper;
import ro.sync.exml.workspace.api.options.WSOptionChangedEvent;
import ro.sync.exml.workspace.api.options.WSOptionListener;
package de.axxepta.oxygen.workspace;
/**
* @author Markus on 20.10.2015.
*/
public class ArgonOptionListener extends WSOptionListener {
public ArgonOptionListener(String s) {
super(s);
}
@Override
public void optionValueChanged(WSOptionChangedEvent wsOptionChangedEvent) { | BaseXConnectionWrapper.refreshFromOptions(false); |
axxepta/project-argon | src/test/java/de/axxepta/oxygen/customprotocol/ArgonChooserDialogTest.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
//
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java
// public static class Element {
//
// private final ArgonEntity type;
// private final String name;
//
// Element(ArgonEntity type, String name) {
// this.type = type;
// this.name = name;
// }
//
// public ArgonEntity getType() {
// return type;
// }
//
// public String getName() {
// return name;
// }
// }
| import de.axxepta.oxygen.api.ArgonEntity;
import de.axxepta.oxygen.customprotocol.ArgonChooserListModel.Element;
import org.junit.Test;
import java.util.Arrays;
import static de.axxepta.oxygen.api.ArgonEntity.DB;
import static org.junit.Assert.assertEquals; | package de.axxepta.oxygen.customprotocol;
public class ArgonChooserDialogTest {
@Test
public void getResourceString() throws Exception {
assertEquals("", ArgonChooserDialog.getResourceString(Arrays.asList( | // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
//
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java
// public static class Element {
//
// private final ArgonEntity type;
// private final String name;
//
// Element(ArgonEntity type, String name) {
// this.type = type;
// this.name = name;
// }
//
// public ArgonEntity getType() {
// return type;
// }
//
// public String getName() {
// return name;
// }
// }
// Path: src/test/java/de/axxepta/oxygen/customprotocol/ArgonChooserDialogTest.java
import de.axxepta.oxygen.api.ArgonEntity;
import de.axxepta.oxygen.customprotocol.ArgonChooserListModel.Element;
import org.junit.Test;
import java.util.Arrays;
import static de.axxepta.oxygen.api.ArgonEntity.DB;
import static org.junit.Assert.assertEquals;
package de.axxepta.oxygen.customprotocol;
public class ArgonChooserDialogTest {
@Test
public void getResourceString() throws Exception {
assertEquals("", ArgonChooserDialog.getResourceString(Arrays.asList( | new Element(DB, "foo")))); |
axxepta/project-argon | src/test/java/de/axxepta/oxygen/customprotocol/ArgonChooserDialogTest.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
//
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java
// public static class Element {
//
// private final ArgonEntity type;
// private final String name;
//
// Element(ArgonEntity type, String name) {
// this.type = type;
// this.name = name;
// }
//
// public ArgonEntity getType() {
// return type;
// }
//
// public String getName() {
// return name;
// }
// }
| import de.axxepta.oxygen.api.ArgonEntity;
import de.axxepta.oxygen.customprotocol.ArgonChooserListModel.Element;
import org.junit.Test;
import java.util.Arrays;
import static de.axxepta.oxygen.api.ArgonEntity.DB;
import static org.junit.Assert.assertEquals; | package de.axxepta.oxygen.customprotocol;
public class ArgonChooserDialogTest {
@Test
public void getResourceString() throws Exception {
assertEquals("", ArgonChooserDialog.getResourceString(Arrays.asList(
new Element(DB, "foo"))));
assertEquals("bar", ArgonChooserDialog.getResourceString(Arrays.asList( | // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
//
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java
// public static class Element {
//
// private final ArgonEntity type;
// private final String name;
//
// Element(ArgonEntity type, String name) {
// this.type = type;
// this.name = name;
// }
//
// public ArgonEntity getType() {
// return type;
// }
//
// public String getName() {
// return name;
// }
// }
// Path: src/test/java/de/axxepta/oxygen/customprotocol/ArgonChooserDialogTest.java
import de.axxepta.oxygen.api.ArgonEntity;
import de.axxepta.oxygen.customprotocol.ArgonChooserListModel.Element;
import org.junit.Test;
import java.util.Arrays;
import static de.axxepta.oxygen.api.ArgonEntity.DB;
import static org.junit.Assert.assertEquals;
package de.axxepta.oxygen.customprotocol;
public class ArgonChooserDialogTest {
@Test
public void getResourceString() throws Exception {
assertEquals("", ArgonChooserDialog.getResourceString(Arrays.asList(
new Element(DB, "foo"))));
assertEquals("bar", ArgonChooserDialog.getResourceString(Arrays.asList( | new Element(DB, "foo"), new Element(ArgonEntity.DIR, "bar")))); |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/utils/WorkspaceUtils.java | // Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
| import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.exml.editor.EditorPageConstants;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.PluginWorkspaceProvider;
import ro.sync.exml.workspace.api.editor.WSEditor;
import ro.sync.exml.workspace.api.editor.page.text.WSTextEditorPage;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets; | msg,
new String[]{trueButton, falseButton},
new int[]{trueValue, falseValue},
initial);
}
private static boolean checkOverwrite() {
int save = booleanDialog(workspaceAccess,
Lang.get(Lang.Keys.dlg_overwrite),
Lang.get(Lang.Keys.lbl_overwrite),
Lang.get(Lang.Keys.cm_yes), OVERWRITE_YES,
Lang.get(Lang.Keys.cm_no), OVERWRITE_NO,
0);
return (save == OVERWRITE_YES);
}
private static int checkOverwriteAll() {
return workspaceAccess.showConfirmDialog(Lang.get(Lang.Keys.dlg_overwrite), Lang.get(Lang.Keys.lbl_overwrite),
new String[]{Lang.get(Lang.Keys.cm_yes), Lang.get(Lang.Keys.cm_always), Lang.get(Lang.Keys.cm_no), Lang.get(Lang.Keys.cm_never)},
new int[]{OVERWRITE_YES, OVERWRITE_ALL, OVERWRITE_NO, OVERWRITE_NONE}, 2);
}
/**
* Check for existence of a BaseX resource and show overwrite dialog if necessary
*
* @param source source of storage target
* @param path resource path of storage target
* @return true if resource does not yet exist or user agreed to overwrite
* @see OverwriteChecker
*/ | // Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
// Path: src/main/java/de/axxepta/oxygen/utils/WorkspaceUtils.java
import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.exml.editor.EditorPageConstants;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.PluginWorkspaceProvider;
import ro.sync.exml.workspace.api.editor.WSEditor;
import ro.sync.exml.workspace.api.editor.page.text.WSTextEditorPage;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
msg,
new String[]{trueButton, falseButton},
new int[]{trueValue, falseValue},
initial);
}
private static boolean checkOverwrite() {
int save = booleanDialog(workspaceAccess,
Lang.get(Lang.Keys.dlg_overwrite),
Lang.get(Lang.Keys.lbl_overwrite),
Lang.get(Lang.Keys.cm_yes), OVERWRITE_YES,
Lang.get(Lang.Keys.cm_no), OVERWRITE_NO,
0);
return (save == OVERWRITE_YES);
}
private static int checkOverwriteAll() {
return workspaceAccess.showConfirmDialog(Lang.get(Lang.Keys.dlg_overwrite), Lang.get(Lang.Keys.lbl_overwrite),
new String[]{Lang.get(Lang.Keys.cm_yes), Lang.get(Lang.Keys.cm_always), Lang.get(Lang.Keys.cm_no), Lang.get(Lang.Keys.cm_never)},
new int[]{OVERWRITE_YES, OVERWRITE_ALL, OVERWRITE_NO, OVERWRITE_NONE}, 2);
}
/**
* Check for existence of a BaseX resource and show overwrite dialog if necessary
*
* @param source source of storage target
* @param path resource path of storage target
* @return true if resource does not yet exist or user agreed to overwrite
* @see OverwriteChecker
*/ | public static boolean newResourceOrOverwrite(BaseXSource source, String path) { |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/actions/CompareVersionsAction.java | // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryTableModel.java
// public class VersionHistoryTableModel extends AbstractTableModel {
//
// private static final Logger logger = LogManager.getLogger(VersionHistoryTableModel.class);
//
// private static final String[] COLUMN_NAMES =
// {Lang.get(Lang.Keys.lbl_version), Lang.get(Lang.Keys.lbl_revision), Lang.get(Lang.Keys.lbl_date)};
//
// private List<VersionHistoryEntry> data;
//
// public VersionHistoryTableModel(List<VersionHistoryEntry> data) {
// this.data = data != null ? new ArrayList<>(data) : Collections.emptyList();
// }
//
// @Override
// public int getRowCount() {
// return data.size();
// }
//
// @Override
// public int getColumnCount() {
// return 3;
// }
//
// @Override
// public Object getValueAt(int rowIndex, int columnIndex) {
// if (rowIndex >= getRowCount()) {
// throw new IllegalArgumentException("Row argument out of bounds.");
// }
// if (columnIndex >= getColumnCount()) {
// throw new IllegalArgumentException("Column argument out of bounds.");
// }
// return data.get(rowIndex).getDisplayVector()[columnIndex];
// }
//
// @Override
// public String getColumnName(final int columnIndex) {
// if (columnIndex >= getColumnCount())
// throw new IllegalArgumentException("Column argument out of bounds.");
// return COLUMN_NAMES[columnIndex];
// }
//
// public void setNewContent(List<VersionHistoryEntry> newData) {
// logger.info("setNewContent " + newData);
// data = new ArrayList<>(newData);
// fireTableDataChanged();
// }
//
// public URL getURL(int rowIndex) {
// if (rowIndex >= getRowCount()) {
// throw new IllegalArgumentException("Row argument out of bounds.");
// }
// return data.get(rowIndex).getURL();
// }
// }
| import de.axxepta.oxygen.versioncontrol.VersionHistoryTableModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.PluginWorkspaceProvider;
import ro.sync.exml.workspace.api.editor.WSEditor;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
| package de.axxepta.oxygen.actions;
/**
* @author Markus on 02.02.2016.
*/
public class CompareVersionsAction extends AbstractAction {
private final JTable table;
private static final Logger logger = LogManager.getLogger(CompareVersionsAction.class);
public CompareVersionsAction(String name, JTable table) {
super(name);
this.table = table;
}
@Override
public void actionPerformed(ActionEvent e) {
URL[] urls = selectURLs();
openDiffer(urls);
}
private URL[] selectURLs() {
final URL[] urls = new URL[2];
int[] selection = table.getSelectedRows();
// if only one revision row is selected, it is compared to the last (current) one
if (selection.length == 1) {
int rows = table.getModel().getRowCount();
| // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryTableModel.java
// public class VersionHistoryTableModel extends AbstractTableModel {
//
// private static final Logger logger = LogManager.getLogger(VersionHistoryTableModel.class);
//
// private static final String[] COLUMN_NAMES =
// {Lang.get(Lang.Keys.lbl_version), Lang.get(Lang.Keys.lbl_revision), Lang.get(Lang.Keys.lbl_date)};
//
// private List<VersionHistoryEntry> data;
//
// public VersionHistoryTableModel(List<VersionHistoryEntry> data) {
// this.data = data != null ? new ArrayList<>(data) : Collections.emptyList();
// }
//
// @Override
// public int getRowCount() {
// return data.size();
// }
//
// @Override
// public int getColumnCount() {
// return 3;
// }
//
// @Override
// public Object getValueAt(int rowIndex, int columnIndex) {
// if (rowIndex >= getRowCount()) {
// throw new IllegalArgumentException("Row argument out of bounds.");
// }
// if (columnIndex >= getColumnCount()) {
// throw new IllegalArgumentException("Column argument out of bounds.");
// }
// return data.get(rowIndex).getDisplayVector()[columnIndex];
// }
//
// @Override
// public String getColumnName(final int columnIndex) {
// if (columnIndex >= getColumnCount())
// throw new IllegalArgumentException("Column argument out of bounds.");
// return COLUMN_NAMES[columnIndex];
// }
//
// public void setNewContent(List<VersionHistoryEntry> newData) {
// logger.info("setNewContent " + newData);
// data = new ArrayList<>(newData);
// fireTableDataChanged();
// }
//
// public URL getURL(int rowIndex) {
// if (rowIndex >= getRowCount()) {
// throw new IllegalArgumentException("Row argument out of bounds.");
// }
// return data.get(rowIndex).getURL();
// }
// }
// Path: src/main/java/de/axxepta/oxygen/actions/CompareVersionsAction.java
import de.axxepta.oxygen.versioncontrol.VersionHistoryTableModel;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.PluginWorkspaceProvider;
import ro.sync.exml.workspace.api.editor.WSEditor;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
package de.axxepta.oxygen.actions;
/**
* @author Markus on 02.02.2016.
*/
public class CompareVersionsAction extends AbstractAction {
private final JTable table;
private static final Logger logger = LogManager.getLogger(CompareVersionsAction.class);
public CompareVersionsAction(String name, JTable table) {
super(name);
this.table = table;
}
@Override
public void actionPerformed(ActionEvent e) {
URL[] urls = selectURLs();
openDiffer(urls);
}
private URL[] selectURLs() {
final URL[] urls = new URL[2];
int[] selection = table.getSelectedRows();
// if only one revision row is selected, it is compared to the last (current) one
if (selection.length == 1) {
int rows = table.getModel().getRowCount();
| urls[0] = ((VersionHistoryTableModel) table.getModel()).getURL(0);
|
axxepta/project-argon | src/main/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtils.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
| import de.axxepta.oxygen.api.ArgonConst;
import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL; | package de.axxepta.oxygen.customprotocol;
public class CustomProtocolURLUtils {
private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);
public static String pathFromURL(URL url) {
String urlString = "";
try {
urlString = java.net.URLDecoder.decode(url.toString(), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException ex) {
logger.error("URLDecoder error decoding " + url.toString(), ex.getMessage());
}
return pathFromURLString(urlString);
}
public static String pathFromURLString(String urlString) {
String[] urlComponents = urlString.split(":/*");
if (urlComponents.length < 2) {
return "";
// ToDo: exception handling
} else {
return urlComponents[1];
}
}
| // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
// Path: src/main/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtils.java
import de.axxepta.oxygen.api.ArgonConst;
import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
package de.axxepta.oxygen.customprotocol;
public class CustomProtocolURLUtils {
private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);
public static String pathFromURL(URL url) {
String urlString = "";
try {
urlString = java.net.URLDecoder.decode(url.toString(), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException ex) {
logger.error("URLDecoder error decoding " + url.toString(), ex.getMessage());
}
return pathFromURLString(urlString);
}
public static String pathFromURLString(String urlString) {
String[] urlComponents = urlString.split(":/*");
if (urlComponents.length < 2) {
return "";
// ToDo: exception handling
} else {
return urlComponents[1];
}
}
| public static BaseXSource sourceFromURL(URL url) { |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtils.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
| import de.axxepta.oxygen.api.ArgonConst;
import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL; | package de.axxepta.oxygen.customprotocol;
public class CustomProtocolURLUtils {
private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);
public static String pathFromURL(URL url) {
String urlString = "";
try {
urlString = java.net.URLDecoder.decode(url.toString(), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException ex) {
logger.error("URLDecoder error decoding " + url.toString(), ex.getMessage());
}
return pathFromURLString(urlString);
}
public static String pathFromURLString(String urlString) {
String[] urlComponents = urlString.split(":/*");
if (urlComponents.length < 2) {
return "";
// ToDo: exception handling
} else {
return urlComponents[1];
}
}
public static BaseXSource sourceFromURL(URL url) {
return sourceFromURLString(url.toString());
}
public static BaseXSource sourceFromURLString(String urlString) {
final URI uri = URI.create(urlString);
if (uri.getScheme() == null) {
return null;
}
switch (uri.getScheme()) {
// case ArgonConst.ARGON_XQ:
// return BaseXSource.RESTXQ; | // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
// Path: src/main/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtils.java
import de.axxepta.oxygen.api.ArgonConst;
import de.axxepta.oxygen.api.BaseXSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URL;
package de.axxepta.oxygen.customprotocol;
public class CustomProtocolURLUtils {
private static final Logger logger = LogManager.getLogger(CustomProtocolURLUtils.class);
public static String pathFromURL(URL url) {
String urlString = "";
try {
urlString = java.net.URLDecoder.decode(url.toString(), "UTF-8");
} catch (UnsupportedEncodingException | IllegalArgumentException ex) {
logger.error("URLDecoder error decoding " + url.toString(), ex.getMessage());
}
return pathFromURLString(urlString);
}
public static String pathFromURLString(String urlString) {
String[] urlComponents = urlString.split(":/*");
if (urlComponents.length < 2) {
return "";
// ToDo: exception handling
} else {
return urlComponents[1];
}
}
public static BaseXSource sourceFromURL(URL url) {
return sourceFromURLString(url.toString());
}
public static BaseXSource sourceFromURLString(String urlString) {
final URI uri = URI.create(urlString);
if (uri.getScheme() == null) {
return null;
}
switch (uri.getScheme()) {
// case ArgonConst.ARGON_XQ:
// return BaseXSource.RESTXQ; | case ArgonConst.ARGON_REPO: |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/customprotocol/ArgonEditorsWatchMap.java | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/event/ListDirEvent.java
// public class ListDirEvent extends MsgTopic {
// public ListDirEvent() {
// super("LIST_DIR");
// }
// }
//
// Path: src/main/java/de/axxepta/oxygen/core/ObserverInterface.java
// public interface ObserverInterface<T> {
//
// //method to update the observer, used by subject
// void update(T type, Object... message);
//
// //attach with subject to observe
// //public void setSubject(SubjectInterface sub);
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public static final ListDirEvent listDir = new ListDirEvent();
| import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.api.event.ListDirEvent;
import de.axxepta.oxygen.core.ObserverInterface;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static de.axxepta.oxygen.api.TopicHolder.listDir;
| package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 28.10.2015.
* The enwraped map contains information about which Argon URLs are opened in editors
*/
public class ArgonEditorsWatchMap implements ObserverInterface<ListDirEvent> {
private static final ArgonEditorsWatchMap instance = new ArgonEditorsWatchMap();
private final Map<URL, EditorInfo> editorMap = new HashMap<>();
/**
* contains all Argon resources with locks, locks owned by current user marked with true value
*/
private final Map<URL, Boolean> lockMap = new HashMap<>();
private ArgonEditorsWatchMap() {
}
public static ArgonEditorsWatchMap getInstance() {
return instance;
}
public void init() {
| // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/event/ListDirEvent.java
// public class ListDirEvent extends MsgTopic {
// public ListDirEvent() {
// super("LIST_DIR");
// }
// }
//
// Path: src/main/java/de/axxepta/oxygen/core/ObserverInterface.java
// public interface ObserverInterface<T> {
//
// //method to update the observer, used by subject
// void update(T type, Object... message);
//
// //attach with subject to observe
// //public void setSubject(SubjectInterface sub);
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public static final ListDirEvent listDir = new ListDirEvent();
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonEditorsWatchMap.java
import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.api.event.ListDirEvent;
import de.axxepta.oxygen.core.ObserverInterface;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static de.axxepta.oxygen.api.TopicHolder.listDir;
package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 28.10.2015.
* The enwraped map contains information about which Argon URLs are opened in editors
*/
public class ArgonEditorsWatchMap implements ObserverInterface<ListDirEvent> {
private static final ArgonEditorsWatchMap instance = new ArgonEditorsWatchMap();
private final Map<URL, EditorInfo> editorMap = new HashMap<>();
/**
* contains all Argon resources with locks, locks owned by current user marked with true value
*/
private final Map<URL, Boolean> lockMap = new HashMap<>();
private ArgonEditorsWatchMap() {
}
public static ArgonEditorsWatchMap getInstance() {
return instance;
}
public void init() {
| TopicHolder.newDir.register(this);
|
axxepta/project-argon | src/main/java/de/axxepta/oxygen/customprotocol/ArgonEditorsWatchMap.java | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/event/ListDirEvent.java
// public class ListDirEvent extends MsgTopic {
// public ListDirEvent() {
// super("LIST_DIR");
// }
// }
//
// Path: src/main/java/de/axxepta/oxygen/core/ObserverInterface.java
// public interface ObserverInterface<T> {
//
// //method to update the observer, used by subject
// void update(T type, Object... message);
//
// //attach with subject to observe
// //public void setSubject(SubjectInterface sub);
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public static final ListDirEvent listDir = new ListDirEvent();
| import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.api.event.ListDirEvent;
import de.axxepta.oxygen.core.ObserverInterface;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static de.axxepta.oxygen.api.TopicHolder.listDir;
| package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 28.10.2015.
* The enwraped map contains information about which Argon URLs are opened in editors
*/
public class ArgonEditorsWatchMap implements ObserverInterface<ListDirEvent> {
private static final ArgonEditorsWatchMap instance = new ArgonEditorsWatchMap();
private final Map<URL, EditorInfo> editorMap = new HashMap<>();
/**
* contains all Argon resources with locks, locks owned by current user marked with true value
*/
private final Map<URL, Boolean> lockMap = new HashMap<>();
private ArgonEditorsWatchMap() {
}
public static ArgonEditorsWatchMap getInstance() {
return instance;
}
public void init() {
TopicHolder.newDir.register(this);
| // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/event/ListDirEvent.java
// public class ListDirEvent extends MsgTopic {
// public ListDirEvent() {
// super("LIST_DIR");
// }
// }
//
// Path: src/main/java/de/axxepta/oxygen/core/ObserverInterface.java
// public interface ObserverInterface<T> {
//
// //method to update the observer, used by subject
// void update(T type, Object... message);
//
// //attach with subject to observe
// //public void setSubject(SubjectInterface sub);
// }
//
// Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public static final ListDirEvent listDir = new ListDirEvent();
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonEditorsWatchMap.java
import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.api.event.ListDirEvent;
import de.axxepta.oxygen.core.ObserverInterface;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static de.axxepta.oxygen.api.TopicHolder.listDir;
package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 28.10.2015.
* The enwraped map contains information about which Argon URLs are opened in editors
*/
public class ArgonEditorsWatchMap implements ObserverInterface<ListDirEvent> {
private static final ArgonEditorsWatchMap instance = new ArgonEditorsWatchMap();
private final Map<URL, EditorInfo> editorMap = new HashMap<>();
/**
* contains all Argon resources with locks, locks owned by current user marked with true value
*/
private final Map<URL, Boolean> lockMap = new HashMap<>();
private ArgonEditorsWatchMap() {
}
public static ArgonEditorsWatchMap getInstance() {
return instance;
}
public void init() {
TopicHolder.newDir.register(this);
| update(listDir, "");
|
axxepta/project-argon | src/test/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtilsTest.java | // Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
| import de.axxepta.oxygen.api.BaseXSource;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import static org.junit.Assert.*; | public void connect() throws IOException {
throw new UnsupportedOperationException();
}
};
}
};
}
return null;
}
});
}
@Test
public void pathFromURL() throws Exception {
assertEquals("foo", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":foo")));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":foo/bar")));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":/foo/bar")));
}
@Test
public void pathFromURLString() throws Exception {
assertEquals("foo", CustomProtocolURLUtils.pathFromURLString(ARGON + ":foo"));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURLString(ARGON + ":foo/bar"));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURLString(ARGON + ":/foo/bar"));
assertEquals("", CustomProtocolURLUtils.pathFromURLString("/foo/bar"));
assertEquals("", CustomProtocolURLUtils.pathFromURLString("foo/bar"));
}
@Test
public void sourceFromURL() throws Exception { | // Path: src/main/java/de/axxepta/oxygen/api/BaseXSource.java
// public enum BaseXSource {
//
// /**
// * Database.
// */
// DATABASE("argon"),
// // /**
// // * RESTXQ.
// // */
// // RESTXQ("argonquery"),
// /**
// * Repository.
// */
// REPO("argonrepo");
//
// private final String protocol;
//
// BaseXSource(String protocol) {
//
// this.protocol = protocol;
// }
//
// public String getProtocol() {
// return protocol;
// }
//
// /**
// * Returns a source.
// *
// * @param string string representation
// * @return enumeration
// */
// public static BaseXSource get(final String string) {
// return BaseXSource.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
// }
// Path: src/test/java/de/axxepta/oxygen/customprotocol/CustomProtocolURLUtilsTest.java
import de.axxepta.oxygen.api.BaseXSource;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import static org.junit.Assert.*;
public void connect() throws IOException {
throw new UnsupportedOperationException();
}
};
}
};
}
return null;
}
});
}
@Test
public void pathFromURL() throws Exception {
assertEquals("foo", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":foo")));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":foo/bar")));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURL(new URL(ARGON + ":/foo/bar")));
}
@Test
public void pathFromURLString() throws Exception {
assertEquals("foo", CustomProtocolURLUtils.pathFromURLString(ARGON + ":foo"));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURLString(ARGON + ":foo/bar"));
assertEquals("foo/bar", CustomProtocolURLUtils.pathFromURLString(ARGON + ":/foo/bar"));
assertEquals("", CustomProtocolURLUtils.pathFromURLString("/foo/bar"));
assertEquals("", CustomProtocolURLUtils.pathFromURLString("foo/bar"));
}
@Test
public void sourceFromURL() throws Exception { | assertEquals(BaseXSource.DATABASE, CustomProtocolURLUtils.sourceFromURL(new URL(ARGON + ":foo/bar"))); |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/utils/ImageUtils.java | // Path: src/main/java/de/axxepta/oxygen/tree/ArgonTree.java
// public class ArgonTree extends Tree {
//
// private static final long serialVersionUID = 1L;
//
// public ArgonTree(final TreeModel root) {
// super(root);
// setCellRenderer(ClassFactory.getInstance().getTreeCellRenderer());
// }
//
// }
| import de.axxepta.oxygen.tree.ArgonTree;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.ui.Icons;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
| if (iconMap == null) {
init();
}
if (iconMap.get(extension.toLowerCase()) == null) {
return iconMap.get("file");
} else {
return iconMap.get(extension.toLowerCase());
}
}
public static Image createImage(String path) {
Icon icon = createImageIcon(path);
if (icon instanceof ImageIcon) {
return ((ImageIcon) icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
public static ImageIcon createImageIcon(String path) {
| // Path: src/main/java/de/axxepta/oxygen/tree/ArgonTree.java
// public class ArgonTree extends Tree {
//
// private static final long serialVersionUID = 1L;
//
// public ArgonTree(final TreeModel root) {
// super(root);
// setCellRenderer(ClassFactory.getInstance().getTreeCellRenderer());
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/utils/ImageUtils.java
import de.axxepta.oxygen.tree.ArgonTree;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ro.sync.ui.Icons;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
if (iconMap == null) {
init();
}
if (iconMap.get(extension.toLowerCase()) == null) {
return iconMap.get("file");
} else {
return iconMap.get(extension.toLowerCase());
}
}
public static Image createImage(String path) {
Icon icon = createImageIcon(path);
if (icon instanceof ImageIcon) {
return ((ImageIcon) icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
public static ImageIcon createImageIcon(String path) {
| java.net.URL imgURL = ArgonTree.class.getResource(path);
|
axxepta/project-argon | src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
| import de.axxepta.oxygen.api.ArgonEntity;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List; | package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 27.07.2016.
*/
public class ArgonChooserListModel extends AbstractListModel {
private final List<Element> data;
ArgonChooserListModel(List<Element> data) {
this.data = new ArrayList<>();
if (data != null)
this.data.addAll(data);
}
@Override
public int getSize() {
return data.size();
}
@Override
public Object getElementAt(int index) {
if (index > getSize())
return null;
else
return data.get(index);
}
| // Path: src/main/java/de/axxepta/oxygen/api/ArgonEntity.java
// public enum ArgonEntity {
//
// FILE,
// DIR,
// DB,
// DB_BASE,
// REPO,
// // XQ,
// ROOT;
//
// public static ArgonEntity get(final String string) {
// return ArgonEntity.valueOf(string.toUpperCase(Locale.ENGLISH));
// }
//
// @Override
// public String toString() {
// return name().toLowerCase(Locale.ENGLISH);
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/customprotocol/ArgonChooserListModel.java
import de.axxepta.oxygen.api.ArgonEntity;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
package de.axxepta.oxygen.customprotocol;
/**
* @author Markus on 27.07.2016.
*/
public class ArgonChooserListModel extends AbstractListModel {
private final List<Element> data;
ArgonChooserListModel(List<Element> data) {
this.data = new ArrayList<>();
if (data != null)
this.data.addAll(data);
}
@Override
public int getSize() {
return data.size();
}
@Override
public Object getElementAt(int index) {
if (index > getSize())
return null;
else
return data.get(index);
}
| ArgonEntity getTypeAt(int index) { |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/api/Connection.java | // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryEntry.java
// public class VersionHistoryEntry {
//
// private final URL url;
// private final int version;
// private final int revision;
// private final LocalDateTime changeDate;
//
// public VersionHistoryEntry(@JsonProperty("url") URL url,
// @JsonProperty("version") int version,
// @JsonProperty("revision") int revision,
// @JsonProperty("changeDate") LocalDateTime changeDate) {
// this.url = url;
// this.version = version;
// this.revision = revision;
// this.changeDate = changeDate;
// }
//
// Object[] getDisplayVector() {
// return new Object[]{version, revision, changeDate };
// }
//
// protected URL getURL() {
// return url;
// }
//
// }
| import de.axxepta.oxygen.versioncontrol.VersionHistoryEntry;
import org.basex.util.Token;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
| package de.axxepta.oxygen.api;
/**
* Connection API.
*
* @author Christian Gruen, BaseX GmbH 2015, BSD License
*/
public interface Connection extends Closeable {
/**
* Returns resources of the given data source and path.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> list(final BaseXSource source, final String path) throws IOException;
/**
* Returns resources of the given data source and path and recursively all it's children.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> listAll(final BaseXSource source, final String path) throws IOException;
/**
* Sets up a database for user management and copies a meta data template file into it.
*
* @throws IOException I/O exception
*/
void init() throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @param chop chop option as string
* @param ftindex ftindex option as string
* @param textindex textindex option as string
* @param attrindex attrindex option as string
* @param tokenindex tokenindex option as string
* @throws IOException I/O exception
*/
void create(final String database, final String chop, final String ftindex, final String textindex,
final String attrindex, final String tokenindex) throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @throws IOException I/O exception
*/
void drop(final String database) throws IOException;
/**
* Returns a resource in its binary representation.
* Texts are encoded as UTF-8 and can be converted via {@link Token#string(byte[])}.
*
* @param source data source
* @param path path
* @param export file has to be prepared for export to file system
* @return entry
* @throws IOException I/O exception
*/
byte[] get(final BaseXSource source, final String path, boolean export) throws IOException;
/**
* Stores a resource.
* Textual resources must be encoded to UTF-8 via {@link Token#token(String)}.
*
* @param source data source
* @param path path
* @param resource resource to be stored
* @param binary flag whether resource should be stored binary
* @param encoding encoding of XML type resource
* @param owner file owner
* @param versionize flag whether version control should be used
* @param versionUp flag whether version should be raised as String
* @throws IOException I/O exception
*/
void put(final BaseXSource source, final String path, final byte[] resource, boolean binary, String encoding,
String owner, String versionize, String versionUp) throws IOException;
/**
* Creates a new directory. Only available for sources REPO and RESTXQ
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void newDir(final BaseXSource source, final String path) throws IOException;
/**
* Deletes a resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void delete(final BaseXSource source, final String path) throws IOException;
/**
* Checks for existence of resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
boolean exists(final BaseXSource source, final String path) throws IOException;
/**
* Renames a resource.
*
* @param source data source
* @param path path
* @param newPath new path
* @throws IOException I/O exception
*/
void rename(final BaseXSource source, final String path, final String newPath) throws IOException;
/**
* Searches for resources containing a filter string in it's name.
*
* @param source data source
* @param path path
* @param filter search filter
* @return resources
* @throws IOException I/O exception
*/
ArrayList<String> search(final BaseXSource source, final String path, final String filter) throws IOException;
/**
* Evaluates a query.
*
* @param query query to be evaluated
* @param args additional parameters as successive name--value pairs
* @return result (string representation)
* @throws IOException I/O exception
*/
String xquery(final String query, String... args) throws IOException;
/**
* Returns the list of history entries to the resource given by path, extracted from meta file
*
* @param path path
* @return List of VersionHistoryEntry
* @throws IOException
*/
| // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryEntry.java
// public class VersionHistoryEntry {
//
// private final URL url;
// private final int version;
// private final int revision;
// private final LocalDateTime changeDate;
//
// public VersionHistoryEntry(@JsonProperty("url") URL url,
// @JsonProperty("version") int version,
// @JsonProperty("revision") int revision,
// @JsonProperty("changeDate") LocalDateTime changeDate) {
// this.url = url;
// this.version = version;
// this.revision = revision;
// this.changeDate = changeDate;
// }
//
// Object[] getDisplayVector() {
// return new Object[]{version, revision, changeDate };
// }
//
// protected URL getURL() {
// return url;
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/api/Connection.java
import de.axxepta.oxygen.versioncontrol.VersionHistoryEntry;
import org.basex.util.Token;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
package de.axxepta.oxygen.api;
/**
* Connection API.
*
* @author Christian Gruen, BaseX GmbH 2015, BSD License
*/
public interface Connection extends Closeable {
/**
* Returns resources of the given data source and path.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> list(final BaseXSource source, final String path) throws IOException;
/**
* Returns resources of the given data source and path and recursively all it's children.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> listAll(final BaseXSource source, final String path) throws IOException;
/**
* Sets up a database for user management and copies a meta data template file into it.
*
* @throws IOException I/O exception
*/
void init() throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @param chop chop option as string
* @param ftindex ftindex option as string
* @param textindex textindex option as string
* @param attrindex attrindex option as string
* @param tokenindex tokenindex option as string
* @throws IOException I/O exception
*/
void create(final String database, final String chop, final String ftindex, final String textindex,
final String attrindex, final String tokenindex) throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @throws IOException I/O exception
*/
void drop(final String database) throws IOException;
/**
* Returns a resource in its binary representation.
* Texts are encoded as UTF-8 and can be converted via {@link Token#string(byte[])}.
*
* @param source data source
* @param path path
* @param export file has to be prepared for export to file system
* @return entry
* @throws IOException I/O exception
*/
byte[] get(final BaseXSource source, final String path, boolean export) throws IOException;
/**
* Stores a resource.
* Textual resources must be encoded to UTF-8 via {@link Token#token(String)}.
*
* @param source data source
* @param path path
* @param resource resource to be stored
* @param binary flag whether resource should be stored binary
* @param encoding encoding of XML type resource
* @param owner file owner
* @param versionize flag whether version control should be used
* @param versionUp flag whether version should be raised as String
* @throws IOException I/O exception
*/
void put(final BaseXSource source, final String path, final byte[] resource, boolean binary, String encoding,
String owner, String versionize, String versionUp) throws IOException;
/**
* Creates a new directory. Only available for sources REPO and RESTXQ
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void newDir(final BaseXSource source, final String path) throws IOException;
/**
* Deletes a resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void delete(final BaseXSource source, final String path) throws IOException;
/**
* Checks for existence of resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
boolean exists(final BaseXSource source, final String path) throws IOException;
/**
* Renames a resource.
*
* @param source data source
* @param path path
* @param newPath new path
* @throws IOException I/O exception
*/
void rename(final BaseXSource source, final String path, final String newPath) throws IOException;
/**
* Searches for resources containing a filter string in it's name.
*
* @param source data source
* @param path path
* @param filter search filter
* @return resources
* @throws IOException I/O exception
*/
ArrayList<String> search(final BaseXSource source, final String path, final String filter) throws IOException;
/**
* Evaluates a query.
*
* @param query query to be evaluated
* @param args additional parameters as successive name--value pairs
* @return result (string representation)
* @throws IOException I/O exception
*/
String xquery(final String query, String... args) throws IOException;
/**
* Returns the list of history entries to the resource given by path, extracted from meta file
*
* @param path path
* @return List of VersionHistoryEntry
* @throws IOException
*/
| List<VersionHistoryEntry> getHistory(final String path) throws IOException;
|
axxepta/project-argon | src/main/java/de/axxepta/oxygen/workspace/ArgonEditorListener.java | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryUpdater.java
// public class VersionHistoryUpdater implements ObserverInterface<MsgTopic> {
//
// private final Logger logger = LogManager.getLogger(VersionHistoryUpdater.class);
//
// private List<VersionHistoryEntry> historyList = new ArrayList<>();
// private final JTable versionHistoryTable;
//
// VersionHistoryUpdater(JTable versionHistoryTable) {
// this.versionHistoryTable = versionHistoryTable;
// }
//
// public void update(MsgTopic type, Object... msg) {
// // ToDo: store data permanently in editor watch map to avoid repeated traffic--refresh historyList if editor is saved
// if ((msg[0] instanceof String) && !(msg[0]).equals("")) {
// String urlString = (String) msg[0];
// String resource = CustomProtocolURLUtils.pathFromURLString(urlString);
//
// if (urlString.startsWith(ArgonConst.ARGON + ":")) {
// try (Connection connection = BaseXConnectionWrapper.getConnection()) {
// historyList = connection.getHistory(resource);
// } catch (IOException ioe) {
// logger.error("Argon connection error while getting meta data from resource " + resource + ": " + ioe.getMessage(), ioe);
// }
// } else {
// historyList = new ArrayList<>();
// }
// }
// updateVersionHistory();
// }
//
// public static String checkVersionHistory(URL editorLocation) {
// if ((editorLocation != null) && (URLUtils.isArgon(editorLocation)))
// return editorLocation.toString();
// else
// return "";
// }
//
// private void updateVersionHistory() {
// ((VersionHistoryTableModel) versionHistoryTable.getModel()).setNewContent(historyList);
// versionHistoryTable.setFillsViewportHeight(true);
// versionHistoryTable.getColumnModel().getColumn(0).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(1).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(2).setCellRenderer(new DateTableCellRenderer());
// }
//
// }
| import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.listeners.WSEditorListener;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;
import java.net.URL; | package de.axxepta.oxygen.workspace;
/**
* @author Markus on 02.07.2016.
*/
class ArgonEditorListener extends WSEditorListener {
private final StandalonePluginWorkspace pluginWorkspaceAccess;
ArgonEditorListener(final StandalonePluginWorkspace pluginWorkspaceAccess) {
this.pluginWorkspaceAccess = pluginWorkspaceAccess;
}
@Override
public void editorSaved(final int operationType) {
final URL editorLocation = pluginWorkspaceAccess.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA).getEditorLocation(); | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryUpdater.java
// public class VersionHistoryUpdater implements ObserverInterface<MsgTopic> {
//
// private final Logger logger = LogManager.getLogger(VersionHistoryUpdater.class);
//
// private List<VersionHistoryEntry> historyList = new ArrayList<>();
// private final JTable versionHistoryTable;
//
// VersionHistoryUpdater(JTable versionHistoryTable) {
// this.versionHistoryTable = versionHistoryTable;
// }
//
// public void update(MsgTopic type, Object... msg) {
// // ToDo: store data permanently in editor watch map to avoid repeated traffic--refresh historyList if editor is saved
// if ((msg[0] instanceof String) && !(msg[0]).equals("")) {
// String urlString = (String) msg[0];
// String resource = CustomProtocolURLUtils.pathFromURLString(urlString);
//
// if (urlString.startsWith(ArgonConst.ARGON + ":")) {
// try (Connection connection = BaseXConnectionWrapper.getConnection()) {
// historyList = connection.getHistory(resource);
// } catch (IOException ioe) {
// logger.error("Argon connection error while getting meta data from resource " + resource + ": " + ioe.getMessage(), ioe);
// }
// } else {
// historyList = new ArrayList<>();
// }
// }
// updateVersionHistory();
// }
//
// public static String checkVersionHistory(URL editorLocation) {
// if ((editorLocation != null) && (URLUtils.isArgon(editorLocation)))
// return editorLocation.toString();
// else
// return "";
// }
//
// private void updateVersionHistory() {
// ((VersionHistoryTableModel) versionHistoryTable.getModel()).setNewContent(historyList);
// versionHistoryTable.setFillsViewportHeight(true);
// versionHistoryTable.getColumnModel().getColumn(0).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(1).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(2).setCellRenderer(new DateTableCellRenderer());
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/workspace/ArgonEditorListener.java
import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.listeners.WSEditorListener;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;
import java.net.URL;
package de.axxepta.oxygen.workspace;
/**
* @author Markus on 02.07.2016.
*/
class ArgonEditorListener extends WSEditorListener {
private final StandalonePluginWorkspace pluginWorkspaceAccess;
ArgonEditorListener(final StandalonePluginWorkspace pluginWorkspaceAccess) {
this.pluginWorkspaceAccess = pluginWorkspaceAccess;
}
@Override
public void editorSaved(final int operationType) {
final URL editorLocation = pluginWorkspaceAccess.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA).getEditorLocation(); | TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/workspace/ArgonEditorListener.java | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryUpdater.java
// public class VersionHistoryUpdater implements ObserverInterface<MsgTopic> {
//
// private final Logger logger = LogManager.getLogger(VersionHistoryUpdater.class);
//
// private List<VersionHistoryEntry> historyList = new ArrayList<>();
// private final JTable versionHistoryTable;
//
// VersionHistoryUpdater(JTable versionHistoryTable) {
// this.versionHistoryTable = versionHistoryTable;
// }
//
// public void update(MsgTopic type, Object... msg) {
// // ToDo: store data permanently in editor watch map to avoid repeated traffic--refresh historyList if editor is saved
// if ((msg[0] instanceof String) && !(msg[0]).equals("")) {
// String urlString = (String) msg[0];
// String resource = CustomProtocolURLUtils.pathFromURLString(urlString);
//
// if (urlString.startsWith(ArgonConst.ARGON + ":")) {
// try (Connection connection = BaseXConnectionWrapper.getConnection()) {
// historyList = connection.getHistory(resource);
// } catch (IOException ioe) {
// logger.error("Argon connection error while getting meta data from resource " + resource + ": " + ioe.getMessage(), ioe);
// }
// } else {
// historyList = new ArrayList<>();
// }
// }
// updateVersionHistory();
// }
//
// public static String checkVersionHistory(URL editorLocation) {
// if ((editorLocation != null) && (URLUtils.isArgon(editorLocation)))
// return editorLocation.toString();
// else
// return "";
// }
//
// private void updateVersionHistory() {
// ((VersionHistoryTableModel) versionHistoryTable.getModel()).setNewContent(historyList);
// versionHistoryTable.setFillsViewportHeight(true);
// versionHistoryTable.getColumnModel().getColumn(0).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(1).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(2).setCellRenderer(new DateTableCellRenderer());
// }
//
// }
| import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.listeners.WSEditorListener;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;
import java.net.URL; | package de.axxepta.oxygen.workspace;
/**
* @author Markus on 02.07.2016.
*/
class ArgonEditorListener extends WSEditorListener {
private final StandalonePluginWorkspace pluginWorkspaceAccess;
ArgonEditorListener(final StandalonePluginWorkspace pluginWorkspaceAccess) {
this.pluginWorkspaceAccess = pluginWorkspaceAccess;
}
@Override
public void editorSaved(final int operationType) {
final URL editorLocation = pluginWorkspaceAccess.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA).getEditorLocation(); | // Path: src/main/java/de/axxepta/oxygen/api/TopicHolder.java
// public class TopicHolder {
//
// // public static MsgTopic openFile = new openFileEvent();
// // public static MsgTopic changeFile = new changeFileEvent();
// public static final SaveFileEvent saveFile = new SaveFileEvent();
// public static final NewDirEvent newDir = new NewDirEvent();
// public static final DeleteFileEvent deleteFile = new DeleteFileEvent();
// public static final ChangedEditorStatusEvent changedEditorStatus = new ChangedEditorStatusEvent();
// public static final TemplateUpdateRequestedEvent templateUpdateRequested = new TemplateUpdateRequestedEvent();
// public static final ChangedServerStatusEvent changedServerStatus = new ChangedServerStatusEvent();
// public static final TreeNodeRequestedEvent treeNodeRequested = new TreeNodeRequestedEvent();
// public static final ConsoleNotifiedEvent consoleNotified = new ConsoleNotifiedEvent();
// public static final ListDirEvent listDir = new ListDirEvent();
// }
//
// Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryUpdater.java
// public class VersionHistoryUpdater implements ObserverInterface<MsgTopic> {
//
// private final Logger logger = LogManager.getLogger(VersionHistoryUpdater.class);
//
// private List<VersionHistoryEntry> historyList = new ArrayList<>();
// private final JTable versionHistoryTable;
//
// VersionHistoryUpdater(JTable versionHistoryTable) {
// this.versionHistoryTable = versionHistoryTable;
// }
//
// public void update(MsgTopic type, Object... msg) {
// // ToDo: store data permanently in editor watch map to avoid repeated traffic--refresh historyList if editor is saved
// if ((msg[0] instanceof String) && !(msg[0]).equals("")) {
// String urlString = (String) msg[0];
// String resource = CustomProtocolURLUtils.pathFromURLString(urlString);
//
// if (urlString.startsWith(ArgonConst.ARGON + ":")) {
// try (Connection connection = BaseXConnectionWrapper.getConnection()) {
// historyList = connection.getHistory(resource);
// } catch (IOException ioe) {
// logger.error("Argon connection error while getting meta data from resource " + resource + ": " + ioe.getMessage(), ioe);
// }
// } else {
// historyList = new ArrayList<>();
// }
// }
// updateVersionHistory();
// }
//
// public static String checkVersionHistory(URL editorLocation) {
// if ((editorLocation != null) && (URLUtils.isArgon(editorLocation)))
// return editorLocation.toString();
// else
// return "";
// }
//
// private void updateVersionHistory() {
// ((VersionHistoryTableModel) versionHistoryTable.getModel()).setNewContent(historyList);
// versionHistoryTable.setFillsViewportHeight(true);
// versionHistoryTable.getColumnModel().getColumn(0).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(1).setPreferredWidth(20);
// versionHistoryTable.getColumnModel().getColumn(2).setCellRenderer(new DateTableCellRenderer());
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/workspace/ArgonEditorListener.java
import de.axxepta.oxygen.api.TopicHolder;
import de.axxepta.oxygen.versioncontrol.VersionHistoryUpdater;
import ro.sync.exml.workspace.api.PluginWorkspace;
import ro.sync.exml.workspace.api.listeners.WSEditorListener;
import ro.sync.exml.workspace.api.standalone.StandalonePluginWorkspace;
import java.net.URL;
package de.axxepta.oxygen.workspace;
/**
* @author Markus on 02.07.2016.
*/
class ArgonEditorListener extends WSEditorListener {
private final StandalonePluginWorkspace pluginWorkspaceAccess;
ArgonEditorListener(final StandalonePluginWorkspace pluginWorkspaceAccess) {
this.pluginWorkspaceAccess = pluginWorkspaceAccess;
}
@Override
public void editorSaved(final int operationType) {
final URL editorLocation = pluginWorkspaceAccess.getCurrentEditorAccess(PluginWorkspace.MAIN_EDITING_AREA).getEditorLocation(); | TopicHolder.changedEditorStatus.postMessage(VersionHistoryUpdater.checkVersionHistory(editorLocation)); |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/tree/ArgonTree.java | // Path: src/main/java/de/axxepta/oxygen/core/ClassFactory.java
// public class ClassFactory {
//
// private static final Logger logger = LogManager.getLogger(ClassFactory.class);
// private static final ClassFactory ourInstance = new ClassFactory();
//
// public static ClassFactory getInstance() {
// return ourInstance;
// }
//
// private ClassFactory() {
// }
//
// public DefaultMutableTreeNode getTreeNode(String obj) {
// return new ArgonTreeNode(obj);
// }
//
// public DefaultMutableTreeNode getTreeNode(String obj, String url) {
// return new ArgonTreeNode(obj, url);
// }
//
// public ArgonPopupMenu getTreePopupMenu(ArgonTree tree, TreeModel treeModel) {
// return new ArgonPopupMenu(tree, treeModel);
// }
//
// public Connection getRestConnection(String host, int port, String user, String password) throws URISyntaxException {
// return new RestConnection(host, port, user, password);
// }
//
// public Action getSearchInPathAction(String name, Icon icon, JTree tree) {
// return new SearchInPathAction(name, icon, tree);
// }
//
// public TreeCellRenderer getTreeCellRenderer() {
// return new ArgonTreeCellRenderer();
// }
//
// public ListCellRenderer getChooserListCellRenderer() {
// return new ArgonChooserListCellRenderer();
// }
//
// public ArgonTreeTransferHandler getTransferHandler(ArgonTree tree) {
// return new ArgonTreeTransferHandler(tree);
// }
//
// }
| import de.axxepta.oxygen.core.ClassFactory;
import ro.sync.exml.workspace.api.standalone.ui.Tree;
import javax.swing.tree.TreeModel; | package de.axxepta.oxygen.tree;
/**
* Tree using custom TreeCellRenderer
*/
public class ArgonTree extends Tree {
private static final long serialVersionUID = 1L;
public ArgonTree(final TreeModel root) {
super(root); | // Path: src/main/java/de/axxepta/oxygen/core/ClassFactory.java
// public class ClassFactory {
//
// private static final Logger logger = LogManager.getLogger(ClassFactory.class);
// private static final ClassFactory ourInstance = new ClassFactory();
//
// public static ClassFactory getInstance() {
// return ourInstance;
// }
//
// private ClassFactory() {
// }
//
// public DefaultMutableTreeNode getTreeNode(String obj) {
// return new ArgonTreeNode(obj);
// }
//
// public DefaultMutableTreeNode getTreeNode(String obj, String url) {
// return new ArgonTreeNode(obj, url);
// }
//
// public ArgonPopupMenu getTreePopupMenu(ArgonTree tree, TreeModel treeModel) {
// return new ArgonPopupMenu(tree, treeModel);
// }
//
// public Connection getRestConnection(String host, int port, String user, String password) throws URISyntaxException {
// return new RestConnection(host, port, user, password);
// }
//
// public Action getSearchInPathAction(String name, Icon icon, JTree tree) {
// return new SearchInPathAction(name, icon, tree);
// }
//
// public TreeCellRenderer getTreeCellRenderer() {
// return new ArgonTreeCellRenderer();
// }
//
// public ListCellRenderer getChooserListCellRenderer() {
// return new ArgonChooserListCellRenderer();
// }
//
// public ArgonTreeTransferHandler getTransferHandler(ArgonTree tree) {
// return new ArgonTreeTransferHandler(tree);
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/tree/ArgonTree.java
import de.axxepta.oxygen.core.ClassFactory;
import ro.sync.exml.workspace.api.standalone.ui.Tree;
import javax.swing.tree.TreeModel;
package de.axxepta.oxygen.tree;
/**
* Tree using custom TreeCellRenderer
*/
public class ArgonTree extends Tree {
private static final long serialVersionUID = 1L;
public ArgonTree(final TreeModel root) {
super(root); | setCellRenderer(ClassFactory.getInstance().getTreeCellRenderer()); |
axxepta/project-argon | src/main/java/de/axxepta/oxygen/utils/URLUtils.java | // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
| import de.axxepta.oxygen.api.ArgonConst;
import java.net.URL;
| * @return true if non-xml type for sure
*/
public static boolean isBinary(String file) {
return (file.toLowerCase().endsWith(".gif") ||
file.toLowerCase().endsWith(".png") ||
file.toLowerCase().endsWith(".eps") ||
file.toLowerCase().endsWith(".tiff") ||
file.toLowerCase().endsWith(".jpg") ||
file.toLowerCase().endsWith(".jpeg") ||
file.toLowerCase().endsWith(".doc") ||
file.toLowerCase().endsWith(".docx") ||
file.toLowerCase().endsWith(".ppt") ||
file.toLowerCase().endsWith(".xls") ||
file.toLowerCase().endsWith(".xlsx") ||
file.toLowerCase().endsWith(".pdf") ||
file.toLowerCase().endsWith(".dll") ||
file.toLowerCase().endsWith(".exe") ||
file.toLowerCase().endsWith(".htm") || // store only XML as text
file.toLowerCase().endsWith(".html") ||
file.toLowerCase().endsWith(".php") ||
file.toLowerCase().endsWith(".css") ||
file.toLowerCase().endsWith(".txt") ||
isQuery(file));
}
public static boolean isQuery(URL url) {
return isQuery(url.toString());
}
public static boolean isArgon(URL url) {
| // Path: src/main/java/de/axxepta/oxygen/api/ArgonConst.java
// public class ArgonConst {
//
// // PROTOCOL NAMES
// public static final String ARGON = "argon";
// public static final String ARGON_XQ = "argonquery";
// public static final String ARGON_REPO = "argonrepo";
//
// // DATABASE NAMES
// public static final String ARGON_DB = "~argon";
//
// public static final String BACKUP_DB_BASE = "~history_";
//
// public static final String BACKUP_RESTXQ_BASE = "~history_~restxq/";
// public static final String BACKUP_REPO_BASE = "~history_~repo/";
//
// public static final String META_DB_BASE = "~meta_";
// public static final String META_RESTXQ_BASE = "~meta_~restxq/";
// public static final String META_REPO_BASE = "~meta_~repo/";
//
// public static final String DATE_FORMAT = "yyyy-MM-dd_HH-mm";
//
// // RESOURCE NAMES
// public static final String META_TEMPLATE = "MetaTemplate.xml";
// public static final String LOCK_FILE = "~usermanagement";
// public static final String EMPTY_FILE = ".empty.xml";
//
// public static final String BXERR_PERMISSION = "BASX0001";
// }
// Path: src/main/java/de/axxepta/oxygen/utils/URLUtils.java
import de.axxepta.oxygen.api.ArgonConst;
import java.net.URL;
* @return true if non-xml type for sure
*/
public static boolean isBinary(String file) {
return (file.toLowerCase().endsWith(".gif") ||
file.toLowerCase().endsWith(".png") ||
file.toLowerCase().endsWith(".eps") ||
file.toLowerCase().endsWith(".tiff") ||
file.toLowerCase().endsWith(".jpg") ||
file.toLowerCase().endsWith(".jpeg") ||
file.toLowerCase().endsWith(".doc") ||
file.toLowerCase().endsWith(".docx") ||
file.toLowerCase().endsWith(".ppt") ||
file.toLowerCase().endsWith(".xls") ||
file.toLowerCase().endsWith(".xlsx") ||
file.toLowerCase().endsWith(".pdf") ||
file.toLowerCase().endsWith(".dll") ||
file.toLowerCase().endsWith(".exe") ||
file.toLowerCase().endsWith(".htm") || // store only XML as text
file.toLowerCase().endsWith(".html") ||
file.toLowerCase().endsWith(".php") ||
file.toLowerCase().endsWith(".css") ||
file.toLowerCase().endsWith(".txt") ||
isQuery(file));
}
public static boolean isQuery(URL url) {
return isQuery(url.toString());
}
public static boolean isArgon(URL url) {
| return url.toString().toLowerCase().startsWith(ArgonConst.ARGON);
|
axxepta/project-argon | src/main/java/de/axxepta/oxygen/api/BasexConnection.java | // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryEntry.java
// public class VersionHistoryEntry {
//
// private final URL url;
// private final int version;
// private final int revision;
// private final LocalDateTime changeDate;
//
// public VersionHistoryEntry(@JsonProperty("url") URL url,
// @JsonProperty("version") int version,
// @JsonProperty("revision") int revision,
// @JsonProperty("changeDate") LocalDateTime changeDate) {
// this.url = url;
// this.version = version;
// this.revision = revision;
// this.changeDate = changeDate;
// }
//
// Object[] getDisplayVector() {
// return new Object[]{version, revision, changeDate };
// }
//
// protected URL getURL() {
// return url;
// }
//
// }
| import de.axxepta.oxygen.versioncontrol.VersionHistoryEntry;
import org.basex.util.Token;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List; | package de.axxepta.oxygen.api;
/**
* Connection API.
*
* @author Christian Gruen, BaseX GmbH 2015, BSD License
*
* TODO: superseded by RestConnection
*/
@Deprecated
public interface BasexConnection extends Closeable {
/**
* Returns resources of the given data source and path.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<Resource> list(final BaseXSource source, final String path) throws IOException;
/**
* Returns resources of the given data source and path and recursively all it's children.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> listAll(final BaseXSource source, final String path) throws IOException;
/**
* Sets up a database for user management and copies a meta data template file into it.
*
* @throws IOException I/O exception
*/
void init() throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @param chop chop option as string
* @param ftindex ftindex option as string
* @param textindex textindex option as string
* @param attrindex attrindex option as string
* @param tokenindex tokenindex option as string
* @throws IOException I/O exception
*/
void create(final String database, final String chop, final String ftindex, final String textindex,
final String attrindex, final String tokenindex) throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @throws IOException I/O exception
*/
void drop(final String database) throws IOException;
/**
* Returns a resource in its binary representation.
* Texts are encoded as UTF-8 and can be converted via {@link Token#string(byte[])}.
*
* @param source data source
* @param path path
* @param export file has to be prepared for export to file system
* @return entry
* @throws IOException I/O exception
*/
byte[] get(final BaseXSource source, final String path, boolean export) throws IOException;
/**
* Stores a resource.
* Textual resources must be encoded to UTF-8 via {@link Token#token(String)}.
*
* @param source data source
* @param path path
* @param resource resource to be stored
* @param binary flag whether resource should be stored binary
* @param encoding encoding of XML type resource
* @param owner file owner
* @param versionize flag whether version control should be used
* @param versionUp flag whether version should be raised as String
* @throws IOException I/O exception
*/
void put(final BaseXSource source, final String path, final byte[] resource, boolean binary, String encoding,
String owner, String versionize, String versionUp) throws IOException;
/**
* Creates a new directory. Only available for sources REPO and RESTXQ
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void newDir(final BaseXSource source, final String path) throws IOException;
/**
* Deletes a resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void delete(final BaseXSource source, final String path) throws IOException;
/**
* Checks for existence of resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
boolean exists(final BaseXSource source, final String path) throws IOException;
/**
* Renames a resource.
*
* @param source data source
* @param path path
* @param newPath new path
* @throws IOException I/O exception
*/
void rename(final BaseXSource source, final String path, final String newPath) throws IOException;
/**
* Searches for resources containing a filter string in it's name.
*
* @param source data source
* @param path path
* @param filter search filter
* @return resources
* @throws IOException I/O exception
*/
ArrayList<String> search(final BaseXSource source, final String path, final String filter) throws IOException;
/**
* Evaluates a query.
*
* @param query query to be evaluated
* @param args additional parameters as successive name--value pairs
* @return result (string representation)
* @throws IOException I/O exception
*/
String xquery(final String query, String... args) throws IOException;
/**
* Returns the list of history entries to the resource given by path, extracted from meta file
*
* @param path path
* @return List of VersionHistoryEntry
* @throws IOException
*/ | // Path: src/main/java/de/axxepta/oxygen/versioncontrol/VersionHistoryEntry.java
// public class VersionHistoryEntry {
//
// private final URL url;
// private final int version;
// private final int revision;
// private final LocalDateTime changeDate;
//
// public VersionHistoryEntry(@JsonProperty("url") URL url,
// @JsonProperty("version") int version,
// @JsonProperty("revision") int revision,
// @JsonProperty("changeDate") LocalDateTime changeDate) {
// this.url = url;
// this.version = version;
// this.revision = revision;
// this.changeDate = changeDate;
// }
//
// Object[] getDisplayVector() {
// return new Object[]{version, revision, changeDate };
// }
//
// protected URL getURL() {
// return url;
// }
//
// }
// Path: src/main/java/de/axxepta/oxygen/api/BasexConnection.java
import de.axxepta.oxygen.versioncontrol.VersionHistoryEntry;
import org.basex.util.Token;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
package de.axxepta.oxygen.api;
/**
* Connection API.
*
* @author Christian Gruen, BaseX GmbH 2015, BSD License
*
* TODO: superseded by RestConnection
*/
@Deprecated
public interface BasexConnection extends Closeable {
/**
* Returns resources of the given data source and path.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<Resource> list(final BaseXSource source, final String path) throws IOException;
/**
* Returns resources of the given data source and path and recursively all it's children.
*
* @param source data source
* @param path path
* @return entries
* @throws IOException I/O exception
*/
List<BaseXResource> listAll(final BaseXSource source, final String path) throws IOException;
/**
* Sets up a database for user management and copies a meta data template file into it.
*
* @throws IOException I/O exception
*/
void init() throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @param chop chop option as string
* @param ftindex ftindex option as string
* @param textindex textindex option as string
* @param attrindex attrindex option as string
* @param tokenindex tokenindex option as string
* @throws IOException I/O exception
*/
void create(final String database, final String chop, final String ftindex, final String textindex,
final String attrindex, final String tokenindex) throws IOException;
/**
* Creates a new database.
*
* @param database new database name
* @throws IOException I/O exception
*/
void drop(final String database) throws IOException;
/**
* Returns a resource in its binary representation.
* Texts are encoded as UTF-8 and can be converted via {@link Token#string(byte[])}.
*
* @param source data source
* @param path path
* @param export file has to be prepared for export to file system
* @return entry
* @throws IOException I/O exception
*/
byte[] get(final BaseXSource source, final String path, boolean export) throws IOException;
/**
* Stores a resource.
* Textual resources must be encoded to UTF-8 via {@link Token#token(String)}.
*
* @param source data source
* @param path path
* @param resource resource to be stored
* @param binary flag whether resource should be stored binary
* @param encoding encoding of XML type resource
* @param owner file owner
* @param versionize flag whether version control should be used
* @param versionUp flag whether version should be raised as String
* @throws IOException I/O exception
*/
void put(final BaseXSource source, final String path, final byte[] resource, boolean binary, String encoding,
String owner, String versionize, String versionUp) throws IOException;
/**
* Creates a new directory. Only available for sources REPO and RESTXQ
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void newDir(final BaseXSource source, final String path) throws IOException;
/**
* Deletes a resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
void delete(final BaseXSource source, final String path) throws IOException;
/**
* Checks for existence of resource.
*
* @param source data source
* @param path path
* @throws IOException I/O exception
*/
boolean exists(final BaseXSource source, final String path) throws IOException;
/**
* Renames a resource.
*
* @param source data source
* @param path path
* @param newPath new path
* @throws IOException I/O exception
*/
void rename(final BaseXSource source, final String path, final String newPath) throws IOException;
/**
* Searches for resources containing a filter string in it's name.
*
* @param source data source
* @param path path
* @param filter search filter
* @return resources
* @throws IOException I/O exception
*/
ArrayList<String> search(final BaseXSource source, final String path, final String filter) throws IOException;
/**
* Evaluates a query.
*
* @param query query to be evaluated
* @param args additional parameters as successive name--value pairs
* @return result (string representation)
* @throws IOException I/O exception
*/
String xquery(final String query, String... args) throws IOException;
/**
* Returns the list of history entries to the resource given by path, extracted from meta file
*
* @param path path
* @return List of VersionHistoryEntry
* @throws IOException
*/ | List<VersionHistoryEntry> getHistory(final String path) throws IOException; |
Hevelian/hevelian-olastic | olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
| import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult; | package com.hevelian.olastic.core.api.uri.queryoption.expression;
/**
* @author Taras Kohut
*/
public class ElasticSearchExpressionRelationsTest extends ElasticSearchExpressionVisitorTest {
@Test
public void visitMember_lambdaAny_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/title eq 'name')";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath); | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult;
package com.hevelian.olastic.core.api.uri.queryoption.expression;
/**
* @author Taras Kohut
*/
public class ElasticSearchExpressionRelationsTest extends ElasticSearchExpressionVisitorTest {
@Test
public void visitMember_lambdaAny_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/title eq 'name')";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath); | ExpressionMember result = uriInfo.getFilterOption().getExpression() |
Hevelian/hevelian-olastic | olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
| import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult; | package com.hevelian.olastic.core.api.uri.queryoption.expression;
/**
* @author Taras Kohut
*/
public class ElasticSearchExpressionRelationsTest extends ElasticSearchExpressionVisitorTest {
@Test
public void visitMember_lambdaAny_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/title eq 'name')";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor()); | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult;
package com.hevelian.olastic.core.api.uri.queryoption.expression;
/**
* @author Taras Kohut
*/
public class ElasticSearchExpressionRelationsTest extends ElasticSearchExpressionVisitorTest {
@Test
public void visitMember_lambdaAny_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/title eq 'name')";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor()); | String query = ((ExpressionResult) result).getQueryBuilder().toString(); |
Hevelian/hevelian-olastic | olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
| import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult; | JSONObject rootObj = queryObj.getJSONObject("nested");
String pagesPath = (String) rootObj.get("path");
JSONObject pagesQueryObject = rootObj.getJSONObject("query");
JSONArray shouldQueryObj = pagesQueryObject.getJSONObject("bool").getJSONArray("should");
JSONArray mustQueryObj = ((JSONObject) shouldQueryObj.get(0)).getJSONObject("bool")
.getJSONArray("must");
JSONObject wordsTerm = ((JSONObject) mustQueryObj.get(0)).getJSONObject("wildcard");
JSONObject pageNameTerm = ((JSONObject) mustQueryObj.get(1)).getJSONObject("term");
JSONObject pageNumberTerm = ((JSONObject) shouldQueryObj.get(1)).getJSONObject("term");
String wordsTermValue = wordsTerm.getJSONObject("info.pages.analyzedWords.keyword")
.getString("wildcard");
String pageTermValue = pageNameTerm.getJSONObject("info.pages.analyzedPageName.keyword")
.getString("value");
int pageNumberValue = pageNumberTerm.getJSONObject("info.pages.pageNumber").getInt("value");
assertEquals("info.pages", pagesPath);
assertEquals("*w*", wordsTermValue);
assertEquals("page name", pageTermValue);
assertEquals(5, pageNumberValue);
}
@Test
public void visitMember_ParentsProperty_correctESQuery() throws Exception {
String rawODataPath = "/book";
String rawQueryPath = "$filter=author/name eq 'Dawkins'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
| // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult;
JSONObject rootObj = queryObj.getJSONObject("nested");
String pagesPath = (String) rootObj.get("path");
JSONObject pagesQueryObject = rootObj.getJSONObject("query");
JSONArray shouldQueryObj = pagesQueryObject.getJSONObject("bool").getJSONArray("should");
JSONArray mustQueryObj = ((JSONObject) shouldQueryObj.get(0)).getJSONObject("bool")
.getJSONArray("must");
JSONObject wordsTerm = ((JSONObject) mustQueryObj.get(0)).getJSONObject("wildcard");
JSONObject pageNameTerm = ((JSONObject) mustQueryObj.get(1)).getJSONObject("term");
JSONObject pageNumberTerm = ((JSONObject) shouldQueryObj.get(1)).getJSONObject("term");
String wordsTermValue = wordsTerm.getJSONObject("info.pages.analyzedWords.keyword")
.getString("wildcard");
String pageTermValue = pageNameTerm.getJSONObject("info.pages.analyzedPageName.keyword")
.getString("value");
int pageNumberValue = pageNumberTerm.getJSONObject("info.pages.pageNumber").getInt("value");
assertEquals("info.pages", pagesPath);
assertEquals("*w*", wordsTermValue);
assertEquals("page name", pageTermValue);
assertEquals(5, pageNumberValue);
}
@Test
public void visitMember_ParentsProperty_correctESQuery() throws Exception {
String rawODataPath = "/book";
String rawQueryPath = "$filter=author/name eq 'Dawkins'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
| checkFilterParentEqualsQuery(query, "author", "name", "'Dawkins'"); |
Hevelian/hevelian-olastic | olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
| import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult; | int pageNumberValue = pageNumberTerm.getJSONObject("info.pages.pageNumber").getInt("value");
assertEquals("info.pages", pagesPath);
assertEquals("*w*", wordsTermValue);
assertEquals("page name", pageTermValue);
assertEquals(5, pageNumberValue);
}
@Test
public void visitMember_ParentsProperty_correctESQuery() throws Exception {
String rawODataPath = "/book";
String rawQueryPath = "$filter=author/name eq 'Dawkins'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
checkFilterParentEqualsQuery(query, "author", "name", "'Dawkins'");
}
@Test
public void visitMember_GrandChildProperty_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/character/any(c:c/name eq 'Oliver Twist'))";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Oliver Twist'";
String field = "name"; | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult;
int pageNumberValue = pageNumberTerm.getJSONObject("info.pages.pageNumber").getInt("value");
assertEquals("info.pages", pagesPath);
assertEquals("*w*", wordsTermValue);
assertEquals("page name", pageTermValue);
assertEquals(5, pageNumberValue);
}
@Test
public void visitMember_ParentsProperty_correctESQuery() throws Exception {
String rawODataPath = "/book";
String rawQueryPath = "$filter=author/name eq 'Dawkins'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
checkFilterParentEqualsQuery(query, "author", "name", "'Dawkins'");
}
@Test
public void visitMember_GrandChildProperty_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/character/any(c:c/name eq 'Oliver Twist'))";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Oliver Twist'";
String field = "name"; | checkFilterGrandChildEqualsQuery(query, field, value, "book", "character"); |
Hevelian/hevelian-olastic | olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
| import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult; | ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
checkFilterParentEqualsQuery(query, "author", "name", "'Dawkins'");
}
@Test
public void visitMember_GrandChildProperty_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/character/any(c:c/name eq 'Oliver Twist'))";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Oliver Twist'";
String field = "name";
checkFilterGrandChildEqualsQuery(query, field, value, "book", "character");
}
@Test
public void visitMember_GrandParentProperty_correctESQuery() throws Exception {
String rawODataPath = "/character";
String rawQueryPath = "$filter=book/author/name eq 'Duma'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Duma'";
String field = "name"; | // Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandChildEqualsQuery(String query, String field, String value,
// String child, String grandChild) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_child");
// String childType = (String) childObj.get("type");
// assertEquals(child, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_child");
// String subChildType = (String) subChildObj.get("type");
// assertEquals(grandChild, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject("term");
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get("value");
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterGrandParentEqualsQuery(String query, String field, String value,
// String parent, String grandParent, String queryKey, String valueKey) {
// JSONObject childObj = new JSONObject(query).getJSONObject("has_parent");
// String childType = (String) childObj.get("parent_type");
// assertEquals(parent, childType);
// JSONObject subChildObj = childObj.getJSONObject("query").getJSONObject("has_parent");
// String subChildType = (String) subChildObj.get("parent_type");
// assertEquals(grandParent, subChildType);
// JSONObject rootObj;
// rootObj = subChildObj.getJSONObject("query").getJSONObject(queryKey);
//
// String fieldName = field + ".keyword";
// JSONObject valueObject = rootObj.getJSONObject(fieldName);
// String actualValue = (String) valueObject.get(valueKey);
// assertEquals(value.substring(1, value.length() - 1), actualValue);
// }
//
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/TestUtils.java
// public static void checkFilterParentEqualsQuery(String query, String parent, String field,
// String value) {
// checkFilterParentEqualsQueryInternal(query, parent, field, value, false);
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/ExpressionResult.java
// @AllArgsConstructor
// @Getter
// public class ExpressionResult extends BaseMember {
//
// private final QueryBuilder queryBuilder;
//
// @Override
// public ExpressionResult and(ExpressionMember expressionMember)
// throws ODataApplicationException {
// return new ExpressionResult(boolQuery().must(queryBuilder)
// .must(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult or(ExpressionMember expressionMember) throws ODataApplicationException {
// return new ExpressionResult(boolQuery().should(queryBuilder)
// .should(((ExpressionResult) expressionMember).getQueryBuilder()));
// }
//
// @Override
// public ExpressionResult not() throws ODataApplicationException {
// return new ExpressionResult(boolQuery().mustNot(queryBuilder));
// }
// }
// Path: olastic-core/src/test/java/com/hevelian/olastic/core/api/uri/queryoption/expression/ElasticSearchExpressionRelationsTest.java
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandChildEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterGrandParentEqualsQuery;
import static com.hevelian.olastic.core.TestUtils.checkFilterParentEqualsQuery;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfo;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl.ExpressionResult;
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
checkFilterParentEqualsQuery(query, "author", "name", "'Dawkins'");
}
@Test
public void visitMember_GrandChildProperty_correctESQuery() throws Exception {
String rawODataPath = "/author";
String rawQueryPath = "$filter=book/any(b:b/character/any(c:c/name eq 'Oliver Twist'))";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Oliver Twist'";
String field = "name";
checkFilterGrandChildEqualsQuery(query, field, value, "book", "character");
}
@Test
public void visitMember_GrandParentProperty_correctESQuery() throws Exception {
String rawODataPath = "/character";
String rawQueryPath = "$filter=book/author/name eq 'Duma'";
UriInfo uriInfo = buildUriInfo(defaultMetadata, defaultOData, rawODataPath, rawQueryPath);
ExpressionMember result = uriInfo.getFilterOption().getExpression()
.accept(new ElasticSearchExpressionVisitor());
String query = ((ExpressionResult) result).getQueryBuilder().toString();
String value = "'Duma'";
String field = "name"; | checkFilterGrandParentEqualsQuery(query, field, value, "book", "author", "term", "value"); |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/serializer/xml/ElasticODataXmlSerializer.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/utils/SerializeUtils.java
// public static FullQualifiedName getPropertyType(Object value) {
// FullQualifiedName fqn = null;
// if (value instanceof String) {
// fqn = EdmPrimitiveTypeKind.String.getFullQualifiedName();
// } else if (value instanceof Byte) {
// fqn = EdmPrimitiveTypeKind.Byte.getFullQualifiedName();
// } else if (value instanceof Short) {
// fqn = EdmPrimitiveTypeKind.Int16.getFullQualifiedName();
// } else if (value instanceof Integer) {
// fqn = EdmPrimitiveTypeKind.Int32.getFullQualifiedName();
// } else if (value instanceof Long) {
// fqn = EdmPrimitiveTypeKind.Int64.getFullQualifiedName();
// } else if (value instanceof Double) {
// fqn = EdmPrimitiveTypeKind.Double.getFullQualifiedName();
// } else if (value instanceof Boolean) {
// fqn = EdmPrimitiveTypeKind.Boolean.getFullQualifiedName();
// } else if (value instanceof Date) {
// fqn = EdmPrimitiveTypeKind.Date.getFullQualifiedName();
// } else {
// throw new ODataRuntimeException("Property type is not supported.");
// }
// return fqn;
// }
| import static com.hevelian.olastic.core.serializer.utils.SerializeUtils.getPropertyType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.core.edm.EdmPropertyImpl;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.core.serializer.utils.ExpandSelectHelper;
import org.apache.olingo.server.core.serializer.xml.ODataXmlSerializer; | package com.hevelian.olastic.core.serializer.xml;
/**
* Custom implementation of {@link ODataXmlSerializer} to override some default
* behavior.
*
* @author rdidyk
*/
public class ElasticODataXmlSerializer extends ODataXmlSerializer {
@Override
protected void writeProperties(ServiceMetadata metadata, EdmStructuredType type,
List<Property> properties, SelectOption select, String xml10InvalidCharReplacement,
XMLStreamWriter writer) throws XMLStreamException, SerializerException {
boolean all = ExpandSelectHelper.isAll(select);
Set<String> selected = all ? new HashSet<>()
: ExpandSelectHelper.getSelectedPropertyNames(select.getSelectItems());
for (Property property : properties) {
String propertyName = property.getName();
if (all || selected.contains(propertyName)) {
EdmProperty edmProperty = type.getStructuralProperty(propertyName);
if (edmProperty == null) {
edmProperty = new EdmPropertyImpl(metadata.getEdm(), new CsdlProperty() | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/utils/SerializeUtils.java
// public static FullQualifiedName getPropertyType(Object value) {
// FullQualifiedName fqn = null;
// if (value instanceof String) {
// fqn = EdmPrimitiveTypeKind.String.getFullQualifiedName();
// } else if (value instanceof Byte) {
// fqn = EdmPrimitiveTypeKind.Byte.getFullQualifiedName();
// } else if (value instanceof Short) {
// fqn = EdmPrimitiveTypeKind.Int16.getFullQualifiedName();
// } else if (value instanceof Integer) {
// fqn = EdmPrimitiveTypeKind.Int32.getFullQualifiedName();
// } else if (value instanceof Long) {
// fqn = EdmPrimitiveTypeKind.Int64.getFullQualifiedName();
// } else if (value instanceof Double) {
// fqn = EdmPrimitiveTypeKind.Double.getFullQualifiedName();
// } else if (value instanceof Boolean) {
// fqn = EdmPrimitiveTypeKind.Boolean.getFullQualifiedName();
// } else if (value instanceof Date) {
// fqn = EdmPrimitiveTypeKind.Date.getFullQualifiedName();
// } else {
// throw new ODataRuntimeException("Property type is not supported.");
// }
// return fqn;
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/xml/ElasticODataXmlSerializer.java
import static com.hevelian.olastic.core.serializer.utils.SerializeUtils.getPropertyType;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.core.edm.EdmPropertyImpl;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.core.serializer.utils.ExpandSelectHelper;
import org.apache.olingo.server.core.serializer.xml.ODataXmlSerializer;
package com.hevelian.olastic.core.serializer.xml;
/**
* Custom implementation of {@link ODataXmlSerializer} to override some default
* behavior.
*
* @author rdidyk
*/
public class ElasticODataXmlSerializer extends ODataXmlSerializer {
@Override
protected void writeProperties(ServiceMetadata metadata, EdmStructuredType type,
List<Property> properties, SelectOption select, String xml10InvalidCharReplacement,
XMLStreamWriter writer) throws XMLStreamException, SerializerException {
boolean all = ExpandSelectHelper.isAll(select);
Set<String> selected = all ? new HashSet<>()
: ExpandSelectHelper.getSelectedPropertyNames(select.getSelectItems());
for (Property property : properties) {
String propertyName = property.getName();
if (all || selected.contains(propertyName)) {
EdmProperty edmProperty = type.getStructuralProperty(propertyName);
if (edmProperty == null) {
edmProperty = new EdmPropertyImpl(metadata.getEdm(), new CsdlProperty() | .setType(getPropertyType(property.getValue())).setName(propertyName)); |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/processors/AbstractESCollectionProcessor.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java
// public class ElasticEdmEntitySet extends EdmEntitySetImpl {
//
// private ElasticCsdlEntitySet csdlEntitySet;
// private ElasticEdmProvider provider;
//
// /**
// * Initialize fields.
// *
// * @param provider
// * the EDM provider
// * @param container
// * the EDM entity container
// * @param entitySet
// * the EDM entity set
// */
// public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container,
// ElasticCsdlEntitySet entitySet) {
// super(provider, container, entitySet);
// this.provider = provider;
// this.csdlEntitySet = entitySet;
// }
//
// /**
// * Get's index name in Elasticsearch.
// *
// * @return index name
// */
// public String getESIndex() {
// return csdlEntitySet.getESIndex();
// }
//
// /**
// * Get's type name in Elasticsearch.
// *
// * @return type name
// */
// public String getESType() {
// return csdlEntitySet.getESType();
// }
//
// @Override
// public ElasticEdmEntityType getEntityType() {
// EdmEntityType entityType = provider.getEntityType(new FullQualifiedName(
// csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType()));
// return entityType != null ? (ElasticEdmEntityType) entityType
// : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN());
// }
//
// /**
// * Sets index to entity set.
// *
// * @param esIntex
// * ES index
// */
// public void setESIndex(String esIntex) {
// csdlEntitySet.setESIndex(esIntex);
// }
//
// /**
// * Sets type to entity set.
// *
// * @param esType
// * ES type
// */
// public void setESType(String esType) {
// csdlEntitySet.setESType(esType);
// }
//
// /**
// * Override because of if child entity type has name which starts with as
// * parent entity type name, then wrong entity set is returning.
// */
// @Override
// public EdmBindingTarget getRelatedBindingTarget(final String path) {
// if (path == null) {
// return null;
// }
// EdmBindingTarget bindingTarget = null;
// boolean found = false;
// for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings()
// .iterator(); itor.hasNext() && !found;) {
// EdmNavigationPropertyBinding binding = itor.next();
// checkBinding(binding);
// // Replace 'startsWith' to 'equals'
// if (path.equals(binding.getPath())) {
// Target target = new Target(binding.getTarget(), getEntityContainer());
// EdmEntityContainer entityContainer = getEntityContainer(
// target.getEntityContainer());
// try {
// bindingTarget = entityContainer.getEntitySet(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find EntitySet " + target.getTargetName());
// }
// } catch (EdmException e) {
// bindingTarget = entityContainer.getSingleton(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find Singleton " + target.getTargetName(),
// e);
// }
// } finally {
// found = bindingTarget != null;
// }
// }
// }
// return bindingTarget;
// }
//
// private void checkBinding(EdmNavigationPropertyBinding binding) {
// if (binding.getPath() == null || binding.getTarget() == null) {
// throw new EdmException(
// "Path or Target in navigation property binding must not be null!");
// }
// }
//
// private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) {
// EdmEntityContainer entityContainer = edm.getEntityContainer(containerName);
// if (entityContainer == null) {
// throw new EdmException("Cannot find entity container with name: " + containerName);
// }
// return entityContainer;
// }
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java
// @AllArgsConstructor
// @Getter
// public class InstanceData<T, V> {
//
// private final T type;
// private final V value;
//
// }
| import org.apache.olingo.commons.api.data.AbstractEntityCollection;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions;
import org.apache.olingo.server.api.serializer.ODataSerializer;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.hevelian.olastic.core.edm.ElasticEdmEntitySet;
import com.hevelian.olastic.core.processors.data.InstanceData; | package com.hevelian.olastic.core.processors;
/**
* Abstract class with common logic for all collection processors.
*
* @author rdidyk
*/
public abstract class AbstractESCollectionProcessor
extends AbstractESReadProcessor<EdmEntityType, AbstractEntityCollection> {
@Override
protected SerializerResult serialize(ODataSerializer serializer, | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java
// public class ElasticEdmEntitySet extends EdmEntitySetImpl {
//
// private ElasticCsdlEntitySet csdlEntitySet;
// private ElasticEdmProvider provider;
//
// /**
// * Initialize fields.
// *
// * @param provider
// * the EDM provider
// * @param container
// * the EDM entity container
// * @param entitySet
// * the EDM entity set
// */
// public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container,
// ElasticCsdlEntitySet entitySet) {
// super(provider, container, entitySet);
// this.provider = provider;
// this.csdlEntitySet = entitySet;
// }
//
// /**
// * Get's index name in Elasticsearch.
// *
// * @return index name
// */
// public String getESIndex() {
// return csdlEntitySet.getESIndex();
// }
//
// /**
// * Get's type name in Elasticsearch.
// *
// * @return type name
// */
// public String getESType() {
// return csdlEntitySet.getESType();
// }
//
// @Override
// public ElasticEdmEntityType getEntityType() {
// EdmEntityType entityType = provider.getEntityType(new FullQualifiedName(
// csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType()));
// return entityType != null ? (ElasticEdmEntityType) entityType
// : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN());
// }
//
// /**
// * Sets index to entity set.
// *
// * @param esIntex
// * ES index
// */
// public void setESIndex(String esIntex) {
// csdlEntitySet.setESIndex(esIntex);
// }
//
// /**
// * Sets type to entity set.
// *
// * @param esType
// * ES type
// */
// public void setESType(String esType) {
// csdlEntitySet.setESType(esType);
// }
//
// /**
// * Override because of if child entity type has name which starts with as
// * parent entity type name, then wrong entity set is returning.
// */
// @Override
// public EdmBindingTarget getRelatedBindingTarget(final String path) {
// if (path == null) {
// return null;
// }
// EdmBindingTarget bindingTarget = null;
// boolean found = false;
// for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings()
// .iterator(); itor.hasNext() && !found;) {
// EdmNavigationPropertyBinding binding = itor.next();
// checkBinding(binding);
// // Replace 'startsWith' to 'equals'
// if (path.equals(binding.getPath())) {
// Target target = new Target(binding.getTarget(), getEntityContainer());
// EdmEntityContainer entityContainer = getEntityContainer(
// target.getEntityContainer());
// try {
// bindingTarget = entityContainer.getEntitySet(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find EntitySet " + target.getTargetName());
// }
// } catch (EdmException e) {
// bindingTarget = entityContainer.getSingleton(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find Singleton " + target.getTargetName(),
// e);
// }
// } finally {
// found = bindingTarget != null;
// }
// }
// }
// return bindingTarget;
// }
//
// private void checkBinding(EdmNavigationPropertyBinding binding) {
// if (binding.getPath() == null || binding.getTarget() == null) {
// throw new EdmException(
// "Path or Target in navigation property binding must not be null!");
// }
// }
//
// private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) {
// EdmEntityContainer entityContainer = edm.getEntityContainer(containerName);
// if (entityContainer == null) {
// throw new EdmException("Cannot find entity container with name: " + containerName);
// }
// return entityContainer;
// }
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java
// @AllArgsConstructor
// @Getter
// public class InstanceData<T, V> {
//
// private final T type;
// private final V value;
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/AbstractESCollectionProcessor.java
import org.apache.olingo.commons.api.data.AbstractEntityCollection;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions;
import org.apache.olingo.server.api.serializer.ODataSerializer;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.hevelian.olastic.core.edm.ElasticEdmEntitySet;
import com.hevelian.olastic.core.processors.data.InstanceData;
package com.hevelian.olastic.core.processors;
/**
* Abstract class with common logic for all collection processors.
*
* @author rdidyk
*/
public abstract class AbstractESCollectionProcessor
extends AbstractESReadProcessor<EdmEntityType, AbstractEntityCollection> {
@Override
protected SerializerResult serialize(ODataSerializer serializer, | InstanceData<EdmEntityType, AbstractEntityCollection> data, |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/processors/AbstractESCollectionProcessor.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java
// public class ElasticEdmEntitySet extends EdmEntitySetImpl {
//
// private ElasticCsdlEntitySet csdlEntitySet;
// private ElasticEdmProvider provider;
//
// /**
// * Initialize fields.
// *
// * @param provider
// * the EDM provider
// * @param container
// * the EDM entity container
// * @param entitySet
// * the EDM entity set
// */
// public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container,
// ElasticCsdlEntitySet entitySet) {
// super(provider, container, entitySet);
// this.provider = provider;
// this.csdlEntitySet = entitySet;
// }
//
// /**
// * Get's index name in Elasticsearch.
// *
// * @return index name
// */
// public String getESIndex() {
// return csdlEntitySet.getESIndex();
// }
//
// /**
// * Get's type name in Elasticsearch.
// *
// * @return type name
// */
// public String getESType() {
// return csdlEntitySet.getESType();
// }
//
// @Override
// public ElasticEdmEntityType getEntityType() {
// EdmEntityType entityType = provider.getEntityType(new FullQualifiedName(
// csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType()));
// return entityType != null ? (ElasticEdmEntityType) entityType
// : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN());
// }
//
// /**
// * Sets index to entity set.
// *
// * @param esIntex
// * ES index
// */
// public void setESIndex(String esIntex) {
// csdlEntitySet.setESIndex(esIntex);
// }
//
// /**
// * Sets type to entity set.
// *
// * @param esType
// * ES type
// */
// public void setESType(String esType) {
// csdlEntitySet.setESType(esType);
// }
//
// /**
// * Override because of if child entity type has name which starts with as
// * parent entity type name, then wrong entity set is returning.
// */
// @Override
// public EdmBindingTarget getRelatedBindingTarget(final String path) {
// if (path == null) {
// return null;
// }
// EdmBindingTarget bindingTarget = null;
// boolean found = false;
// for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings()
// .iterator(); itor.hasNext() && !found;) {
// EdmNavigationPropertyBinding binding = itor.next();
// checkBinding(binding);
// // Replace 'startsWith' to 'equals'
// if (path.equals(binding.getPath())) {
// Target target = new Target(binding.getTarget(), getEntityContainer());
// EdmEntityContainer entityContainer = getEntityContainer(
// target.getEntityContainer());
// try {
// bindingTarget = entityContainer.getEntitySet(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find EntitySet " + target.getTargetName());
// }
// } catch (EdmException e) {
// bindingTarget = entityContainer.getSingleton(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find Singleton " + target.getTargetName(),
// e);
// }
// } finally {
// found = bindingTarget != null;
// }
// }
// }
// return bindingTarget;
// }
//
// private void checkBinding(EdmNavigationPropertyBinding binding) {
// if (binding.getPath() == null || binding.getTarget() == null) {
// throw new EdmException(
// "Path or Target in navigation property binding must not be null!");
// }
// }
//
// private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) {
// EdmEntityContainer entityContainer = edm.getEntityContainer(containerName);
// if (entityContainer == null) {
// throw new EdmException("Cannot find entity container with name: " + containerName);
// }
// return entityContainer;
// }
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java
// @AllArgsConstructor
// @Getter
// public class InstanceData<T, V> {
//
// private final T type;
// private final V value;
//
// }
| import org.apache.olingo.commons.api.data.AbstractEntityCollection;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions;
import org.apache.olingo.server.api.serializer.ODataSerializer;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.hevelian.olastic.core.edm.ElasticEdmEntitySet;
import com.hevelian.olastic.core.processors.data.InstanceData; | package com.hevelian.olastic.core.processors;
/**
* Abstract class with common logic for all collection processors.
*
* @author rdidyk
*/
public abstract class AbstractESCollectionProcessor
extends AbstractESReadProcessor<EdmEntityType, AbstractEntityCollection> {
@Override
protected SerializerResult serialize(ODataSerializer serializer,
InstanceData<EdmEntityType, AbstractEntityCollection> data, | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/edm/ElasticEdmEntitySet.java
// public class ElasticEdmEntitySet extends EdmEntitySetImpl {
//
// private ElasticCsdlEntitySet csdlEntitySet;
// private ElasticEdmProvider provider;
//
// /**
// * Initialize fields.
// *
// * @param provider
// * the EDM provider
// * @param container
// * the EDM entity container
// * @param entitySet
// * the EDM entity set
// */
// public ElasticEdmEntitySet(ElasticEdmProvider provider, EdmEntityContainer container,
// ElasticCsdlEntitySet entitySet) {
// super(provider, container, entitySet);
// this.provider = provider;
// this.csdlEntitySet = entitySet;
// }
//
// /**
// * Get's index name in Elasticsearch.
// *
// * @return index name
// */
// public String getESIndex() {
// return csdlEntitySet.getESIndex();
// }
//
// /**
// * Get's type name in Elasticsearch.
// *
// * @return type name
// */
// public String getESType() {
// return csdlEntitySet.getESType();
// }
//
// @Override
// public ElasticEdmEntityType getEntityType() {
// EdmEntityType entityType = provider.getEntityType(new FullQualifiedName(
// csdlEntitySet.getTypeFQN().getNamespace(), csdlEntitySet.getESType()));
// return entityType != null ? (ElasticEdmEntityType) entityType
// : (ElasticEdmEntityType) provider.getEntityType(csdlEntitySet.getTypeFQN());
// }
//
// /**
// * Sets index to entity set.
// *
// * @param esIntex
// * ES index
// */
// public void setESIndex(String esIntex) {
// csdlEntitySet.setESIndex(esIntex);
// }
//
// /**
// * Sets type to entity set.
// *
// * @param esType
// * ES type
// */
// public void setESType(String esType) {
// csdlEntitySet.setESType(esType);
// }
//
// /**
// * Override because of if child entity type has name which starts with as
// * parent entity type name, then wrong entity set is returning.
// */
// @Override
// public EdmBindingTarget getRelatedBindingTarget(final String path) {
// if (path == null) {
// return null;
// }
// EdmBindingTarget bindingTarget = null;
// boolean found = false;
// for (Iterator<EdmNavigationPropertyBinding> itor = getNavigationPropertyBindings()
// .iterator(); itor.hasNext() && !found;) {
// EdmNavigationPropertyBinding binding = itor.next();
// checkBinding(binding);
// // Replace 'startsWith' to 'equals'
// if (path.equals(binding.getPath())) {
// Target target = new Target(binding.getTarget(), getEntityContainer());
// EdmEntityContainer entityContainer = getEntityContainer(
// target.getEntityContainer());
// try {
// bindingTarget = entityContainer.getEntitySet(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find EntitySet " + target.getTargetName());
// }
// } catch (EdmException e) {
// bindingTarget = entityContainer.getSingleton(target.getTargetName());
// if (bindingTarget == null) {
// throw new EdmException("Cannot find Singleton " + target.getTargetName(),
// e);
// }
// } finally {
// found = bindingTarget != null;
// }
// }
// }
// return bindingTarget;
// }
//
// private void checkBinding(EdmNavigationPropertyBinding binding) {
// if (binding.getPath() == null || binding.getTarget() == null) {
// throw new EdmException(
// "Path or Target in navigation property binding must not be null!");
// }
// }
//
// private EdmEntityContainer getEntityContainer(FullQualifiedName containerName) {
// EdmEntityContainer entityContainer = edm.getEntityContainer(containerName);
// if (entityContainer == null) {
// throw new EdmException("Cannot find entity container with name: " + containerName);
// }
// return entityContainer;
// }
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/data/InstanceData.java
// @AllArgsConstructor
// @Getter
// public class InstanceData<T, V> {
//
// private final T type;
// private final V value;
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/processors/AbstractESCollectionProcessor.java
import org.apache.olingo.commons.api.data.AbstractEntityCollection;
import org.apache.olingo.commons.api.edm.EdmEntityType;
import org.apache.olingo.server.api.serializer.EntityCollectionSerializerOptions;
import org.apache.olingo.server.api.serializer.ODataSerializer;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.UriInfo;
import org.apache.olingo.server.api.uri.queryoption.CountOption;
import org.apache.olingo.server.api.uri.queryoption.ExpandOption;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import com.hevelian.olastic.core.edm.ElasticEdmEntitySet;
import com.hevelian.olastic.core.processors.data.InstanceData;
package com.hevelian.olastic.core.processors;
/**
* Abstract class with common logic for all collection processors.
*
* @author rdidyk
*/
public abstract class AbstractESCollectionProcessor
extends AbstractESReadProcessor<EdmEntityType, AbstractEntityCollection> {
@Override
protected SerializerResult serialize(ODataSerializer serializer,
InstanceData<EdmEntityType, AbstractEntityCollection> data, | ElasticEdmEntitySet entitySet, UriInfo uriInfo) throws SerializerException { |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/serializer/json/ElasticODataJsonSerializer.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/utils/SerializeUtils.java
// public static FullQualifiedName getPropertyType(Object value) {
// FullQualifiedName fqn = null;
// if (value instanceof String) {
// fqn = EdmPrimitiveTypeKind.String.getFullQualifiedName();
// } else if (value instanceof Byte) {
// fqn = EdmPrimitiveTypeKind.Byte.getFullQualifiedName();
// } else if (value instanceof Short) {
// fqn = EdmPrimitiveTypeKind.Int16.getFullQualifiedName();
// } else if (value instanceof Integer) {
// fqn = EdmPrimitiveTypeKind.Int32.getFullQualifiedName();
// } else if (value instanceof Long) {
// fqn = EdmPrimitiveTypeKind.Int64.getFullQualifiedName();
// } else if (value instanceof Double) {
// fqn = EdmPrimitiveTypeKind.Double.getFullQualifiedName();
// } else if (value instanceof Boolean) {
// fqn = EdmPrimitiveTypeKind.Boolean.getFullQualifiedName();
// } else if (value instanceof Date) {
// fqn = EdmPrimitiveTypeKind.Date.getFullQualifiedName();
// } else {
// throw new ODataRuntimeException("Property type is not supported.");
// }
// return fqn;
// }
| import static com.hevelian.olastic.core.serializer.utils.SerializeUtils.getPropertyType;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.ContextURL;
import org.apache.olingo.commons.api.data.Operation;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.core.edm.EdmPropertyImpl;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.serializer.PrimitiveSerializerOptions;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.core.serializer.SerializerResultImpl;
import org.apache.olingo.server.core.serializer.json.ODataJsonSerializer;
import org.apache.olingo.server.core.serializer.utils.CircleStreamBuffer;
import org.apache.olingo.server.core.serializer.utils.ContentTypeHelper;
import org.apache.olingo.server.core.serializer.utils.ContextURLBuilder;
import org.apache.olingo.server.core.serializer.utils.ExpandSelectHelper;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator; | package com.hevelian.olastic.core.serializer.json;
/**
* Custom implementation of {@link ODataJsonSerializer} to override some default
* behavior. Some code duplication present here, because of bugs on Olingo
* library. Remove code duplication when bugs will be fixed.
*
*
* @author rdidyk
*/
public class ElasticODataJsonSerializer extends ODataJsonSerializer {
// Because Constans.JSON_NULL = "odata.null" but should be like below
private static final String JSON_NULL = "@odata.null";
private final boolean isODataMetadataNone;
private final boolean isODataMetadataFull;
/**
* Constructor to initialize content type.
*
* @param contentType
* content type
*/
public ElasticODataJsonSerializer(ContentType contentType) {
super(contentType);
isODataMetadataNone = ContentTypeHelper.isODataMetadataNone(contentType);
isODataMetadataFull = ContentTypeHelper.isODataMetadataFull(contentType);
}
@Override
protected void writeProperties(ServiceMetadata metadata, EdmStructuredType type,
List<Property> properties, SelectOption select, JsonGenerator json)
throws IOException, SerializerException {
boolean all = ExpandSelectHelper.isAll(select);
Set<String> selected = all ? new HashSet<>()
: ExpandSelectHelper.getSelectedPropertyNames(select.getSelectItems());
for (Property property : properties) {
String propertyName = property.getName();
if (all || selected.contains(propertyName)) {
EdmProperty edmProperty = type.getStructuralProperty(propertyName);
if (edmProperty == null) {
edmProperty = new EdmPropertyImpl(metadata.getEdm(), new CsdlProperty() | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/utils/SerializeUtils.java
// public static FullQualifiedName getPropertyType(Object value) {
// FullQualifiedName fqn = null;
// if (value instanceof String) {
// fqn = EdmPrimitiveTypeKind.String.getFullQualifiedName();
// } else if (value instanceof Byte) {
// fqn = EdmPrimitiveTypeKind.Byte.getFullQualifiedName();
// } else if (value instanceof Short) {
// fqn = EdmPrimitiveTypeKind.Int16.getFullQualifiedName();
// } else if (value instanceof Integer) {
// fqn = EdmPrimitiveTypeKind.Int32.getFullQualifiedName();
// } else if (value instanceof Long) {
// fqn = EdmPrimitiveTypeKind.Int64.getFullQualifiedName();
// } else if (value instanceof Double) {
// fqn = EdmPrimitiveTypeKind.Double.getFullQualifiedName();
// } else if (value instanceof Boolean) {
// fqn = EdmPrimitiveTypeKind.Boolean.getFullQualifiedName();
// } else if (value instanceof Date) {
// fqn = EdmPrimitiveTypeKind.Date.getFullQualifiedName();
// } else {
// throw new ODataRuntimeException("Property type is not supported.");
// }
// return fqn;
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/serializer/json/ElasticODataJsonSerializer.java
import static com.hevelian.olastic.core.serializer.utils.SerializeUtils.getPropertyType;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.olingo.commons.api.Constants;
import org.apache.olingo.commons.api.data.ContextURL;
import org.apache.olingo.commons.api.data.Operation;
import org.apache.olingo.commons.api.data.Property;
import org.apache.olingo.commons.api.edm.EdmPrimitiveType;
import org.apache.olingo.commons.api.edm.EdmPrimitiveTypeException;
import org.apache.olingo.commons.api.edm.EdmProperty;
import org.apache.olingo.commons.api.edm.EdmStructuredType;
import org.apache.olingo.commons.api.edm.provider.CsdlProperty;
import org.apache.olingo.commons.api.format.ContentType;
import org.apache.olingo.commons.core.edm.EdmPropertyImpl;
import org.apache.olingo.server.api.ServiceMetadata;
import org.apache.olingo.server.api.serializer.PrimitiveSerializerOptions;
import org.apache.olingo.server.api.serializer.SerializerException;
import org.apache.olingo.server.api.serializer.SerializerResult;
import org.apache.olingo.server.api.uri.queryoption.SelectOption;
import org.apache.olingo.server.core.serializer.SerializerResultImpl;
import org.apache.olingo.server.core.serializer.json.ODataJsonSerializer;
import org.apache.olingo.server.core.serializer.utils.CircleStreamBuffer;
import org.apache.olingo.server.core.serializer.utils.ContentTypeHelper;
import org.apache.olingo.server.core.serializer.utils.ContextURLBuilder;
import org.apache.olingo.server.core.serializer.utils.ExpandSelectHelper;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
package com.hevelian.olastic.core.serializer.json;
/**
* Custom implementation of {@link ODataJsonSerializer} to override some default
* behavior. Some code duplication present here, because of bugs on Olingo
* library. Remove code duplication when bugs will be fixed.
*
*
* @author rdidyk
*/
public class ElasticODataJsonSerializer extends ODataJsonSerializer {
// Because Constans.JSON_NULL = "odata.null" but should be like below
private static final String JSON_NULL = "@odata.null";
private final boolean isODataMetadataNone;
private final boolean isODataMetadataFull;
/**
* Constructor to initialize content type.
*
* @param contentType
* content type
*/
public ElasticODataJsonSerializer(ContentType contentType) {
super(contentType);
isODataMetadataNone = ContentTypeHelper.isODataMetadataNone(contentType);
isODataMetadataFull = ContentTypeHelper.isODataMetadataFull(contentType);
}
@Override
protected void writeProperties(ServiceMetadata metadata, EdmStructuredType type,
List<Property> properties, SelectOption select, JsonGenerator json)
throws IOException, SerializerException {
boolean all = ExpandSelectHelper.isAll(select);
Set<String> selected = all ? new HashSet<>()
: ExpandSelectHelper.getSelectedPropertyNames(select.getSelectItems());
for (Property property : properties) {
String propertyName = property.getName();
if (all || selected.contains(propertyName)) {
EdmProperty edmProperty = type.getStructuralProperty(propertyName);
if (edmProperty == null) {
edmProperty = new EdmPropertyImpl(metadata.getEdm(), new CsdlProperty() | .setType(getPropertyType(property.getValue())).setName(propertyName)); |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/common/NestedPerIndexMapper.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/ElasticToCsdlMapper.java
// public interface ElasticToCsdlMapper {
//
// /**
// * Map Elasticsearch field to CSDL property name. By default returns the
// * name of the corresponding field.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @param field
// * name of the field
// * @return name of the corresponding field
// */
// String esFieldToCsdlProperty(String index, String type, String field);
//
// /**
// * Map Elasticsearch field to CSDL property isCollection value. By default
// * returns false.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @param field
// * name of the field
// * @return name of the corresponding field
// */
// boolean esFieldIsCollection(String index, String type, String field);
//
// /**
// * Map Elasticsearch type name to CSDL entity type. By default returns the
// * name of the corresponding entity type.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @return the corresponding entity type
// */
// FullQualifiedName esTypeToEntityType(String index, String type);
//
// /**
// * Map Elasticsearch index name to CSDL namespace. By default returns the
// * name of the corresponding index.
// *
// * @param index
// * name of the index
// * @return the corresponding namespace
// */
// String esIndexToCsdlNamespace(String index);
//
// /**
// * Map Elasticsearch type name to CSDL entity set name. By default returns
// * the name of the corresponding entity type.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @return name of the corresponding entity set
// */
// String esTypeToEntitySet(String index, String type);
//
// /**
// * Convert a child relationship of Elasticsearch to a navigation property
// * name.
// *
// * @param index
// * name of the index
// * @param child
// * name of the child type
// * @param parent
// * name of the parent type
// * @return Navigation property name for child relationship. Default
// * implementation returns the corresponding child entity type's name
// */
// String esChildRelationToNavPropName(String index, String child, String parent);
//
// /**
// * Convert a parent relationship of Elasticsearch to a navigation property
// * name.
// *
// * @param index
// * name of the index
// * @param parent
// * name of the parent type
// * @param child
// * name of the child type
// * @return Navigation property name for parent relationship. Default
// * implementation returns the corresponding parent entity type's
// * name
// */
// String esParentRelationToNavPropName(String index, String parent, String child);
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/MappingMetaDataProvider.java
// public interface MappingMetaDataProvider {
// /**
// * Return all the mappings for all the types inside a single index.
// *
// * @param index
// * name of the index.
// * @return Type/Mapping map.
// */
// ImmutableOpenMap<String, MappingMetaData> getAllMappings(String index);
//
// /**
// * Get mapping for a single type. The {@link #getAllMappings(String)} should
// * be used if the mappings for all the types are required.
// *
// * @param index
// * name of the index.
// * @param type
// * name of the type within the index.
// * @return mapping metadata for a single type.
// */
// MappingMetaData getMappingForType(String index, String type);
//
// /**
// * Get all mappings for fields with the requested name within a single
// * instance.
// *
// * @param index
// * name of the index.
// * @param field
// * name of the field.
// * @return type/field mapping map.
// */
// ImmutableOpenMap<String, FieldMappingMetaData> getMappingsForField(String index, String field);
//
// /**
// * Get mapping for a single field within a single type.
// *
// * @param index
// * name of the index.
// * @param type
// * name of the type.
// * @param field
// * name of the field.
// * @return mapping metadata for a single field.
// */
// FieldMappingMetaData getMappingForField(String index, String type, String field);
// }
| import com.hevelian.olastic.core.elastic.mappings.ElasticToCsdlMapper;
import com.hevelian.olastic.core.elastic.mappings.MappingMetaDataProvider; | package com.hevelian.olastic.core.common;
/**
* Default implementation of nested type mapper when types have same properties
* names for nested object.
*
* @author rdidyk
*/
public class NestedPerIndexMapper extends AbstractNestedTypeMapper {
/**
* Constructor to initialize values.
*
* @param mappingMetaDataProvider
* mapping meta data provide
* @param csdlMapper
* Elasticsearch to CSDL mapper
*/
public NestedPerIndexMapper(MappingMetaDataProvider mappingMetaDataProvider, | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/ElasticToCsdlMapper.java
// public interface ElasticToCsdlMapper {
//
// /**
// * Map Elasticsearch field to CSDL property name. By default returns the
// * name of the corresponding field.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @param field
// * name of the field
// * @return name of the corresponding field
// */
// String esFieldToCsdlProperty(String index, String type, String field);
//
// /**
// * Map Elasticsearch field to CSDL property isCollection value. By default
// * returns false.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @param field
// * name of the field
// * @return name of the corresponding field
// */
// boolean esFieldIsCollection(String index, String type, String field);
//
// /**
// * Map Elasticsearch type name to CSDL entity type. By default returns the
// * name of the corresponding entity type.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @return the corresponding entity type
// */
// FullQualifiedName esTypeToEntityType(String index, String type);
//
// /**
// * Map Elasticsearch index name to CSDL namespace. By default returns the
// * name of the corresponding index.
// *
// * @param index
// * name of the index
// * @return the corresponding namespace
// */
// String esIndexToCsdlNamespace(String index);
//
// /**
// * Map Elasticsearch type name to CSDL entity set name. By default returns
// * the name of the corresponding entity type.
// *
// * @param index
// * name of the index
// * @param type
// * name of the type within the index
// * @return name of the corresponding entity set
// */
// String esTypeToEntitySet(String index, String type);
//
// /**
// * Convert a child relationship of Elasticsearch to a navigation property
// * name.
// *
// * @param index
// * name of the index
// * @param child
// * name of the child type
// * @param parent
// * name of the parent type
// * @return Navigation property name for child relationship. Default
// * implementation returns the corresponding child entity type's name
// */
// String esChildRelationToNavPropName(String index, String child, String parent);
//
// /**
// * Convert a parent relationship of Elasticsearch to a navigation property
// * name.
// *
// * @param index
// * name of the index
// * @param parent
// * name of the parent type
// * @param child
// * name of the child type
// * @return Navigation property name for parent relationship. Default
// * implementation returns the corresponding parent entity type's
// * name
// */
// String esParentRelationToNavPropName(String index, String parent, String child);
//
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/mappings/MappingMetaDataProvider.java
// public interface MappingMetaDataProvider {
// /**
// * Return all the mappings for all the types inside a single index.
// *
// * @param index
// * name of the index.
// * @return Type/Mapping map.
// */
// ImmutableOpenMap<String, MappingMetaData> getAllMappings(String index);
//
// /**
// * Get mapping for a single type. The {@link #getAllMappings(String)} should
// * be used if the mappings for all the types are required.
// *
// * @param index
// * name of the index.
// * @param type
// * name of the type within the index.
// * @return mapping metadata for a single type.
// */
// MappingMetaData getMappingForType(String index, String type);
//
// /**
// * Get all mappings for fields with the requested name within a single
// * instance.
// *
// * @param index
// * name of the index.
// * @param field
// * name of the field.
// * @return type/field mapping map.
// */
// ImmutableOpenMap<String, FieldMappingMetaData> getMappingsForField(String index, String field);
//
// /**
// * Get mapping for a single field within a single type.
// *
// * @param index
// * name of the index.
// * @param type
// * name of the type.
// * @param field
// * name of the field.
// * @return mapping metadata for a single field.
// */
// FieldMappingMetaData getMappingForField(String index, String type, String field);
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/common/NestedPerIndexMapper.java
import com.hevelian.olastic.core.elastic.mappings.ElasticToCsdlMapper;
import com.hevelian.olastic.core.elastic.mappings.MappingMetaDataProvider;
package com.hevelian.olastic.core.common;
/**
* Default implementation of nested type mapper when types have same properties
* names for nested object.
*
* @author rdidyk
*/
public class NestedPerIndexMapper extends AbstractNestedTypeMapper {
/**
* Constructor to initialize values.
*
* @param mappingMetaDataProvider
* mapping meta data provide
* @param csdlMapper
* Elasticsearch to CSDL mapper
*/
public NestedPerIndexMapper(MappingMetaDataProvider mappingMetaDataProvider, | ElasticToCsdlMapper csdlMapper) { |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
| import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter; | package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/ | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java
import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/ | protected QueryBuilder getEqQuery(ExpressionMember expressionMember) |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
| import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter; | package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/
protected QueryBuilder getEqQuery(ExpressionMember expressionMember)
throws ODataApplicationException {
Object value = ((LiteralMember) expressionMember).getValue(); | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java
import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/
protected QueryBuilder getEqQuery(ExpressionMember expressionMember)
throws ODataApplicationException {
Object value = ((LiteralMember) expressionMember).getValue(); | if (getField().equals(ID_FIELD_NAME)) { |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
| import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter; | package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/
protected QueryBuilder getEqQuery(ExpressionMember expressionMember)
throws ODataApplicationException {
Object value = ((LiteralMember) expressionMember).getValue();
if (getField().equals(ID_FIELD_NAME)) {
if (value == null) {
throw new ODataApplicationException("Id value can not be null",
HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
}
return idsQuery().addIds(value.toString());
} else { | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/ElasticConstants.java
// public static final String ID_FIELD_NAME = "_id";
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/elastic/utils/ElasticUtils.java
// public static String addKeywordIfNeeded(String name, List<EdmAnnotation> annotations) {
// boolean isAnalyzed = false;
// Optional<EdmAnnotation> analyzedAnnotation = annotations.stream()
// .filter(annotation -> annotation.getTerm().getName()
// .equals(AnnotationProvider.ANALYZED_TERM_NAME))
// .findFirst();
// if (analyzedAnnotation.isPresent()) {
// isAnalyzed = (Boolean) (analyzedAnnotation.get().getExpression().asConstant()
// .asPrimitive());
// }
// return isAnalyzed ? addKeyword(name) : name;
// }
//
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/AnnotatedMember.java
import static com.hevelian.olastic.core.elastic.ElasticConstants.ID_FIELD_NAME;
import static com.hevelian.olastic.core.elastic.utils.ElasticUtils.addKeywordIfNeeded;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.idsQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import java.util.List;
import java.util.Locale;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.server.api.ODataApplicationException;
import org.elasticsearch.index.query.QueryBuilder;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
import lombok.AllArgsConstructor;
import lombok.Getter;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Represents expression member with type.
*
* @author Taras Kohut
*/
@AllArgsConstructor
@Getter
public abstract class AnnotatedMember extends BaseMember {
private final String field;
private final List<EdmAnnotation> annotations;
/**
* Gets query for equals and not equals operations.
*
* @param expressionMember
* member with value
* @return appropriate query
* @throws ODataApplicationException
* if any error occurred during creating query
*/
protected QueryBuilder getEqQuery(ExpressionMember expressionMember)
throws ODataApplicationException {
Object value = ((LiteralMember) expressionMember).getValue();
if (getField().equals(ID_FIELD_NAME)) {
if (value == null) {
throw new ODataApplicationException("Id value can not be null",
HttpStatusCode.BAD_REQUEST.getStatusCode(), Locale.ROOT);
}
return idsQuery().addIds(value.toString());
} else { | String fieldName = addKeywordIfNeeded(getField(), getAnnotations()); |
Hevelian/hevelian-olastic | olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMember.java | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
| import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.server.api.ODataApplicationException;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember; | package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Wraps raw olingo primitive.
*
* @author Taras Kohut
*/
public class PrimitiveMember extends AnnotatedMember {
/**
* Initialize fields.
*
* @param field
* field name
* @param annotations
* annotations list
*/
public PrimitiveMember(String field, List<EdmAnnotation> annotations) {
super(field, annotations);
}
@Override | // Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/ExpressionMember.java
// public interface ExpressionMember extends LogicalExpression, LambdaExpression, MethodExpression {
//
// }
// Path: olastic-core/src/main/java/com/hevelian/olastic/core/api/uri/queryoption/expression/member/impl/PrimitiveMember.java
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import java.util.List;
import org.apache.olingo.commons.api.edm.EdmAnnotation;
import org.apache.olingo.server.api.ODataApplicationException;
import com.hevelian.olastic.core.api.uri.queryoption.expression.member.ExpressionMember;
package com.hevelian.olastic.core.api.uri.queryoption.expression.member.impl;
/**
* Wraps raw olingo primitive.
*
* @author Taras Kohut
*/
public class PrimitiveMember extends AnnotatedMember {
/**
* Initialize fields.
*
* @param field
* field name
* @param annotations
* annotations list
*/
public PrimitiveMember(String field, List<EdmAnnotation> annotations) {
super(field, annotations);
}
@Override | public ExpressionResult eq(ExpressionMember expressionMember) throws ODataApplicationException { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.