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 |
|---|---|---|---|---|---|---|
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/EventBasedExtension.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ModeExtension.java
// public interface ModeExtension {
//
// /**
// * The {@link CommandExecutor} runs this for each command before executing it.
// *
// * <p>Check the existing implementations to see what to do in your implementation.</p>
// */
// @NotNull
// <A, R> Command<A, R> extend(@NotNull Command<A, R> cmd, @NotNull Mode mode);
//
// }
//
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java
// public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
//
// @NotNull
// protected final Command<A, R> delegate;
//
// protected BaseCommandInterceptor(@NotNull Command<A, R> delegate) {
// this.delegate = delegate;
// }
//
// /**
// * @return The name of the intercepted command.
// */
// @Override
// public String getName() {
// return delegate.getName();
// }
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.ModeExtension;
import com.optimaize.command4j.commands.BaseCommandInterceptor;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Base class for extensions that don't want to wrap the command themselves. Instead they just
* implement the event callbacks.
*
* @author Fabian Kessler
*/
public abstract class EventBasedExtension implements ModeExtension {
public static class Interceptor<A, R> extends BaseCommandInterceptor<A, R> {
private final CommandListener<A,R> commandListener;
| // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ModeExtension.java
// public interface ModeExtension {
//
// /**
// * The {@link CommandExecutor} runs this for each command before executing it.
// *
// * <p>Check the existing implementations to see what to do in your implementation.</p>
// */
// @NotNull
// <A, R> Command<A, R> extend(@NotNull Command<A, R> cmd, @NotNull Mode mode);
//
// }
//
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java
// public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
//
// @NotNull
// protected final Command<A, R> delegate;
//
// protected BaseCommandInterceptor(@NotNull Command<A, R> delegate) {
// this.delegate = delegate;
// }
//
// /**
// * @return The name of the intercepted command.
// */
// @Override
// public String getName() {
// return delegate.getName();
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/EventBasedExtension.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.ModeExtension;
import com.optimaize.command4j.commands.BaseCommandInterceptor;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Base class for extensions that don't want to wrap the command themselves. Instead they just
* implement the event callbacks.
*
* @author Fabian Kessler
*/
public abstract class EventBasedExtension implements ModeExtension {
public static class Interceptor<A, R> extends BaseCommandInterceptor<A, R> {
private final CommandListener<A,R> commandListener;
| public Interceptor(@NotNull Command<A, R> delegate, @NotNull CommandListener<A,R> commandListener) { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/EventBasedExtension.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ModeExtension.java
// public interface ModeExtension {
//
// /**
// * The {@link CommandExecutor} runs this for each command before executing it.
// *
// * <p>Check the existing implementations to see what to do in your implementation.</p>
// */
// @NotNull
// <A, R> Command<A, R> extend(@NotNull Command<A, R> cmd, @NotNull Mode mode);
//
// }
//
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java
// public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
//
// @NotNull
// protected final Command<A, R> delegate;
//
// protected BaseCommandInterceptor(@NotNull Command<A, R> delegate) {
// this.delegate = delegate;
// }
//
// /**
// * @return The name of the intercepted command.
// */
// @Override
// public String getName() {
// return delegate.getName();
// }
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.ModeExtension;
import com.optimaize.command4j.commands.BaseCommandInterceptor;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Base class for extensions that don't want to wrap the command themselves. Instead they just
* implement the event callbacks.
*
* @author Fabian Kessler
*/
public abstract class EventBasedExtension implements ModeExtension {
public static class Interceptor<A, R> extends BaseCommandInterceptor<A, R> {
private final CommandListener<A,R> commandListener;
public Interceptor(@NotNull Command<A, R> delegate, @NotNull CommandListener<A,R> commandListener) {
super(delegate);
this.commandListener = commandListener;
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
//
// Path: src/main/java/com/optimaize/command4j/ModeExtension.java
// public interface ModeExtension {
//
// /**
// * The {@link CommandExecutor} runs this for each command before executing it.
// *
// * <p>Check the existing implementations to see what to do in your implementation.</p>
// */
// @NotNull
// <A, R> Command<A, R> extend(@NotNull Command<A, R> cmd, @NotNull Mode mode);
//
// }
//
// Path: src/main/java/com/optimaize/command4j/commands/BaseCommandInterceptor.java
// public abstract class BaseCommandInterceptor<A, R> extends BaseCommand<A, R> {
//
// @NotNull
// protected final Command<A, R> delegate;
//
// protected BaseCommandInterceptor(@NotNull Command<A, R> delegate) {
// this.delegate = delegate;
// }
//
// /**
// * @return The name of the intercepted command.
// */
// @Override
// public String getName() {
// return delegate.getName();
// }
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/EventBasedExtension.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import com.optimaize.command4j.ModeExtension;
import com.optimaize.command4j.commands.BaseCommandInterceptor;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Base class for extensions that don't want to wrap the command themselves. Instead they just
* implement the event callbacks.
*
* @author Fabian Kessler
*/
public abstract class EventBasedExtension implements ModeExtension {
public static class Interceptor<A, R> extends BaseCommandInterceptor<A, R> {
private final CommandListener<A,R> commandListener;
public Interceptor(@NotNull Command<A, R> delegate, @NotNull CommandListener<A,R> commandListener) {
super(delegate);
this.commandListener = commandListener;
}
@Override | public R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerFactory.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
| import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* The factory is needed because only at runtime the generic types A and R are known of the command for which
* logging is performed. (feel free to refactor if you know how to do it without...)
*
* @author Fabian Kessler
*/
public interface CommandExecutionLoggerFactory {
/**
* @param command Only needed for the generic types.
* @param <A> The argument.
* @param <R> The result.
*/
@NotNull | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerFactory.java
import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* The factory is needed because only at runtime the generic types A and R are known of the command for which
* logging is performed. (feel free to refactor if you know how to do it without...)
*
* @author Fabian Kessler
*/
public interface CommandExecutionLoggerFactory {
/**
* @param command Only needed for the generic types.
* @param <A> The argument.
* @param <R> The result.
*/
@NotNull | <A,R> CommandExecutionLogger<A, R> make(@NotNull Command<A, R> command); |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/Sleep.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Sleeps a bit and then returns.
*
* @author Fabian Kessler
*/
public class Sleep extends BaseCommand<Void, Void> {
private final long sleepMs;
public Sleep(long sleepMs) {
this.sleepMs = sleepMs;
}
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/Sleep.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Sleeps a bit and then returns.
*
* @author Fabian Kessler
*/
public class Sleep extends BaseCommand<Void, Void> {
private final long sleepMs;
public Sleep(long sleepMs) {
this.sleepMs = sleepMs;
}
@Override | public Void call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/CallCounter.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Counts each execution and returns the current number of calls (including the current).
*
* @author Fabian Kessler
*/
public class CallCounter extends BaseCommand<Void, Integer> {
public static class Counter {
private volatile int i;
public synchronized int incrementAndGet() {
i++;
return i;
}
public int get() {
return i;
}
}
private final Counter counter;
public CallCounter(@NotNull Counter counter) {
this.counter = counter;
}
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/CallCounter.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Counts each execution and returns the current number of calls (including the current).
*
* @author Fabian Kessler
*/
public class CallCounter extends BaseCommand<Void, Integer> {
public static class Counter {
private volatile int i;
public synchronized int incrementAndGet() {
i++;
return i;
}
public int get() {
return i;
}
}
private final Counter counter;
public CallCounter(@NotNull Counter counter) {
this.counter = counter;
}
@Override | public Integer call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/AutoRetryStrategy.java | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
| import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
public interface AutoRetryStrategy {
/**
* Decides if auto-retry should take place.
* @param executionCounter When this method is called for the first time the number is 1 (one
* execution failed already). The second time it's 2, and so on.
* You need to return <code>null</code> when this number gets too high to
* prevent endless retrying and waiting.
* Also, you may increase the duration as the counter increases.
* @param exception The exception that occurred. The method is encouraged to respond based on this.
* @return <code>null</code> to not retry, otherwise a Duration for how long to wait until the retry
* should take place.
*/
@Nullable | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/AutoRetryStrategy.java
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
public interface AutoRetryStrategy {
/**
* Decides if auto-retry should take place.
* @param executionCounter When this method is called for the first time the number is 1 (one
* execution failed already). The second time it's 2, and so on.
* You need to return <code>null</code> when this number gets too high to
* prevent endless retrying and waiting.
* Also, you may increase the duration as the counter increases.
* @param exception The exception that occurred. The method is encouraged to respond based on this.
* @return <code>null</code> to not retry, otherwise a Duration for how long to wait until the retry
* should take place.
*/
@Nullable | Duration doRetry(int executionCounter, @NotNull Exception exception); |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/ReturnInputString.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.commands;
/**
* Returns the input.
*
* @author Fabian Kessler
*/
public class ReturnInputString extends BaseCommand<String, String> {
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/ReturnInputString.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.commands;
/**
* Returns the input.
*
* @author Fabian Kessler
*/
public class ReturnInputString extends BaseCommand<String, String> {
@Override | public String call(@NotNull Optional<String> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/impl/Runner.java | // Path: src/main/java/com/optimaize/command4j/cache/ExecutorCache.java
// public final class ExecutorCache {
//
// private final Cache<ExecutorCacheKey, Object> cache;
//
// /**
// * Creates a cache with the given Guava cache.
// */
// public ExecutorCache(@NotNull Cache<ExecutorCacheKey, Object> cache) {
// this.cache = cache;
// }
//
// /**
// * Creates a cache with a default Guava cache that works for most scenarios.
// */
// public ExecutorCache() {
// this.cache = CacheBuilder
// .newBuilder()
// .softValues() //disputable.
// .maximumSize(500)
// .build();
// }
//
// @Nullable
// public <V> V getIfPresent(@NotNull ExecutorCacheKey<V> key) {
// //noinspection unchecked
// return (V) cache.getIfPresent(key);
// }
//
// public <V> V get(@NotNull ExecutorCacheKey<V> key, @NotNull Callable<? extends V> valueLoader) throws Exception {
// //to understand this, see what cache.get() throws. we want to unwrap the throwable, whatever it was.
// try {
// //noinspection unchecked
// return (V) cache.get(key, valueLoader);
// } catch (UncheckedExecutionException | ExecutionError e) {
// throw Throwables.propagate(e.getCause());
// } catch (ExecutionException e) {
// Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
// throw Throwables.propagate(e.getCause());
// }
// }
//
// public <V> void put(@NotNull ExecutorCacheKey<V> key, V value) {
// cache.put(key, value);
// }
//
// public void invalidate(@NotNull ExecutorCacheKey<?> key) {
// cache.invalidate(key);
// }
//
// public long size() {
// return cache.size();
// }
//
// public void invalidateAll() {
// cache.invalidateAll();
// }
//
// public ImmutableMap<ExecutorCacheKey, Object> getAllPresent(@NotNull Iterable<?> keys) {
// return cache.getAllPresent(keys);
// }
// }
| import com.optimaize.command4j.*;
import com.optimaize.command4j.cache.ExecutorCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import org.jetbrains.annotations.NotNull; | package com.optimaize.command4j.impl;
/**
* Runs a setup command.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
class Runner {
private static final Logger log = LoggerFactory.getLogger(Runner.class);
private final CommandExecutor executor; | // Path: src/main/java/com/optimaize/command4j/cache/ExecutorCache.java
// public final class ExecutorCache {
//
// private final Cache<ExecutorCacheKey, Object> cache;
//
// /**
// * Creates a cache with the given Guava cache.
// */
// public ExecutorCache(@NotNull Cache<ExecutorCacheKey, Object> cache) {
// this.cache = cache;
// }
//
// /**
// * Creates a cache with a default Guava cache that works for most scenarios.
// */
// public ExecutorCache() {
// this.cache = CacheBuilder
// .newBuilder()
// .softValues() //disputable.
// .maximumSize(500)
// .build();
// }
//
// @Nullable
// public <V> V getIfPresent(@NotNull ExecutorCacheKey<V> key) {
// //noinspection unchecked
// return (V) cache.getIfPresent(key);
// }
//
// public <V> V get(@NotNull ExecutorCacheKey<V> key, @NotNull Callable<? extends V> valueLoader) throws Exception {
// //to understand this, see what cache.get() throws. we want to unwrap the throwable, whatever it was.
// try {
// //noinspection unchecked
// return (V) cache.get(key, valueLoader);
// } catch (UncheckedExecutionException | ExecutionError e) {
// throw Throwables.propagate(e.getCause());
// } catch (ExecutionException e) {
// Throwables.propagateIfInstanceOf(e.getCause(), Exception.class);
// throw Throwables.propagate(e.getCause());
// }
// }
//
// public <V> void put(@NotNull ExecutorCacheKey<V> key, V value) {
// cache.put(key, value);
// }
//
// public void invalidate(@NotNull ExecutorCacheKey<?> key) {
// cache.invalidate(key);
// }
//
// public long size() {
// return cache.size();
// }
//
// public void invalidateAll() {
// cache.invalidateAll();
// }
//
// public ImmutableMap<ExecutorCacheKey, Object> getAllPresent(@NotNull Iterable<?> keys) {
// return cache.getAllPresent(keys);
// }
// }
// Path: src/main/java/com/optimaize/command4j/impl/Runner.java
import com.optimaize.command4j.*;
import com.optimaize.command4j.cache.ExecutorCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import org.jetbrains.annotations.NotNull;
package com.optimaize.command4j.impl;
/**
* Runs a setup command.
*
* @author Eike Kettner
* @author Fabian Kessler
*/
class Runner {
private static final Logger log = LoggerFactory.getLogger(Runner.class);
private final CommandExecutor executor; | private final ExecutorCache cache; |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/ExceptionBarrierCommandListener.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Logs and swallows exceptions.
*
* <p>This works as an exception stopper an does not let any Exception go through. An Error however is not
* caught and thus goes through.</p>
*
* <p>In case the logger throws then its exception is caught and ignored.</p>
*
* @author Fabian Kessler
*/
public class ExceptionBarrierCommandListener<A,R> extends CommandListenerWrapper<A, R> {
private static final Logger defaultLogger = LoggerFactory.getLogger(ExceptionBarrierCommandListener.class);
@NotNull
private final Logger logger;
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener) {
this(commandListener, defaultLogger);
}
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener,
@NotNull Logger logger) {
super(commandListener);
this.logger = logger;
}
private void log(@NotNull String when, @NotNull Exception e) {
try {
//atm we don't try to be smart and log the A arg or R result.
//if you do then make sure to catch exceptions while making toString() of those
//separately... maybe those are the causes of the original exception!
logger.error("Exception when calling a '"+when+"' listener!", e);
} catch (Exception loggerEx) {
//ugh. bad. so this one goes unnoticed.
}
}
@Override | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/ExceptionBarrierCommandListener.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Logs and swallows exceptions.
*
* <p>This works as an exception stopper an does not let any Exception go through. An Error however is not
* caught and thus goes through.</p>
*
* <p>In case the logger throws then its exception is caught and ignored.</p>
*
* @author Fabian Kessler
*/
public class ExceptionBarrierCommandListener<A,R> extends CommandListenerWrapper<A, R> {
private static final Logger defaultLogger = LoggerFactory.getLogger(ExceptionBarrierCommandListener.class);
@NotNull
private final Logger logger;
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener) {
this(commandListener, defaultLogger);
}
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener,
@NotNull Logger logger) {
super(commandListener);
this.logger = logger;
}
private void log(@NotNull String when, @NotNull Exception e) {
try {
//atm we don't try to be smart and log the A arg or R result.
//if you do then make sure to catch exceptions while making toString() of those
//separately... maybe those are the causes of the original exception!
logger.error("Exception when calling a '"+when+"' listener!", e);
} catch (Exception loggerEx) {
//ugh. bad. so this one goes unnoticed.
}
}
@Override | public void before(@NotNull Command<A, R> command, |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/ExceptionBarrierCommandListener.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Logs and swallows exceptions.
*
* <p>This works as an exception stopper an does not let any Exception go through. An Error however is not
* caught and thus goes through.</p>
*
* <p>In case the logger throws then its exception is caught and ignored.</p>
*
* @author Fabian Kessler
*/
public class ExceptionBarrierCommandListener<A,R> extends CommandListenerWrapper<A, R> {
private static final Logger defaultLogger = LoggerFactory.getLogger(ExceptionBarrierCommandListener.class);
@NotNull
private final Logger logger;
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener) {
this(commandListener, defaultLogger);
}
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener,
@NotNull Logger logger) {
super(commandListener);
this.logger = logger;
}
private void log(@NotNull String when, @NotNull Exception e) {
try {
//atm we don't try to be smart and log the A arg or R result.
//if you do then make sure to catch exceptions while making toString() of those
//separately... maybe those are the causes of the original exception!
logger.error("Exception when calling a '"+when+"' listener!", e);
} catch (Exception loggerEx) {
//ugh. bad. so this one goes unnoticed.
}
}
@Override
public void before(@NotNull Command<A, R> command, | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
//
// Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/main/java/com/optimaize/command4j/ext/util/eventbasedextension/ExceptionBarrierCommandListener.java
import com.google.common.base.Optional;
import com.optimaize.command4j.Command;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
package com.optimaize.command4j.ext.util.eventbasedextension;
/**
* Logs and swallows exceptions.
*
* <p>This works as an exception stopper an does not let any Exception go through. An Error however is not
* caught and thus goes through.</p>
*
* <p>In case the logger throws then its exception is caught and ignored.</p>
*
* @author Fabian Kessler
*/
public class ExceptionBarrierCommandListener<A,R> extends CommandListenerWrapper<A, R> {
private static final Logger defaultLogger = LoggerFactory.getLogger(ExceptionBarrierCommandListener.class);
@NotNull
private final Logger logger;
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener) {
this(commandListener, defaultLogger);
}
public ExceptionBarrierCommandListener(@NotNull CommandListener<A, R> commandListener,
@NotNull Logger logger) {
super(commandListener);
this.logger = logger;
}
private void log(@NotNull String when, @NotNull Exception e) {
try {
//atm we don't try to be smart and log the A arg or R result.
//if you do then make sure to catch exceptions while making toString() of those
//separately... maybe those are the causes of the original exception!
logger.error("Exception when calling a '"+when+"' listener!", e);
} catch (Exception loggerEx) {
//ugh. bad. so this one goes unnoticed.
}
}
@Override
public void before(@NotNull Command<A, R> command, | @NotNull ExecutionContext ec, |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerFactoryImpl.java | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
| import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger; | package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to create your own and return a different logger implementation.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerFactoryImpl implements CommandExecutionLoggerFactory {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerFactoryImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerFactoryImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override @NotNull | // Path: src/main/java/com/optimaize/command4j/Command.java
// public interface Command<A, R> {
//
// /**
// * Runs the remote command.
// *
// * <p>This method always blocks until either the command finishes successfully, aborts by throwing an
// * exception, or is cancelled early. (The {@link CommandExecutorService} allows you to execute
// * commands in a non-blocking way.)</p>
// *
// * @param arg The {@link Optional} argument. If you need more than 1 argument then you may create a
// * request class as container, or maybe it's enough to just use {@link Tuples tuples}.
// * @param ec
// * @return Commands may return null, since null values are handled by the framework in that they're wrapped
// * into an {@link Optional}.
// * @throws Exception
// *
// * TODO Eike: The return value is nullable and the framework makes an Optional out of it.
// * Why not the same for the argument? We could make the interface more consistent.
// * Is there a reason against that?
// */
// @Nullable
// R call(@NotNull Optional<A> arg, @NotNull ExecutionContext ec) throws Exception;
//
// /**
// * Like Java's Thread, a Command has a name.
// *
// * <p>Because toString() can become long with all the interceptors wrapping a base command, this
// * keeps it simple to what it actually does.</p>
// *
// * <p>Certain kinds of combined commands, like a ComposedCommand or a ConditionCommand, don't have a single
// * name, they show the names of the contained commands.</p>
// *
// * @return an identifier, not unique but usually distinguishable
// */
// String getName();
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/logging/customlogging/CommandExecutionLoggerFactoryImpl.java
import com.optimaize.command4j.Command;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
package com.optimaize.command4j.ext.extensions.logging.customlogging;
/**
* You are encouraged to create your own and return a different logger implementation.
*
* @author Fabian Kessler
*/
public class CommandExecutionLoggerFactoryImpl implements CommandExecutionLoggerFactory {
@NotNull
private final Logger logger;
private final boolean logArgumentInResult;
/**
* Uses logArgumentInResult=false.
*/
public CommandExecutionLoggerFactoryImpl(@NotNull Logger logger) {
this(logger, false);
}
/**
* @param logArgumentInResult Optionally writes the argument with the result line again.
* This is useful when either you only log results (and not requests), or you want it more convenient and don't mind generating larger log files.
*/
public CommandExecutionLoggerFactoryImpl(@NotNull Logger logger, boolean logArgumentInResult) {
this.logger = logger;
this.logArgumentInResult = logArgumentInResult;
}
@Override @NotNull | public <A,R> CommandExecutionLogger<A, R> make(@NotNull Command<A, R> command) { |
optimaize/command4j | src/test/java/com/optimaize/command4j/commands/ReturnConstructorString.java | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
| import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.commands;
/**
* Always returns the string passed in the constructor.
*
* @author Fabian Kessler
*/
public class ReturnConstructorString extends BaseCommand<Void, String> {
@Nullable
private final String string;
public ReturnConstructorString(@Nullable String string) {
this.string = string;
}
@Override | // Path: src/main/java/com/optimaize/command4j/ExecutionContext.java
// public interface ExecutionContext {
//
// /**
// * @return the mode that was supplied to the initial invocation.
// */
// @NotNull
// Mode getMode();
//
// /**
// * @return the global cache to store/retrieve objects to/from.
// */
// @NotNull
// ExecutorCache getCache();
//
// /**
// * Overloaded method that uses the same <code>mode</code> as supplied
// * to the parent invocation.
// *
// * @see #execute(Command, Mode, com.google.common.base.Optional)
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, Optional<A> arg) throws Exception;
//
// /**
// * Runs the given <code>command</code> using the given <code>mode</code>.
// *
// * <p>This method is for commands that want to execute yet another command.
// * One example is an auto-retry extension that executes the command again.
// * </p>
// */
// @NotNull
// <A, R> Optional<R> execute(@NotNull Command<A, R> task, @NotNull Mode mode, Optional<A> arg) throws Exception;
//
// }
// Path: src/test/java/com/optimaize/command4j/commands/ReturnConstructorString.java
import com.google.common.base.Optional;
import com.optimaize.command4j.ExecutionContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.commands;
/**
* Always returns the string passed in the constructor.
*
* @author Fabian Kessler
*/
public class ReturnConstructorString extends BaseCommand<Void, String> {
@Nullable
private final String string;
public ReturnConstructorString(@Nullable String string) {
this.string = string;
}
@Override | public String call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception { |
optimaize/command4j | src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/AlwaysOnceInstantAutoRetryStrategy.java | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
| import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; | package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
class AlwaysOnceInstantAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new AlwaysOnceInstantAutoRetryStrategy();
private AlwaysOnceInstantAutoRetryStrategy(){}
@Override @Nullable | // Path: src/main/java/com/optimaize/command4j/lang/Duration.java
// @Immutable
// public final class Duration {
//
// private final long time;
// @NotNull
// private final TimeUnit timeUnit;
//
// @NotNull
// public static Duration of(long time, @NotNull TimeUnit unit) {
// return new Duration(time, unit);
// }
//
// @NotNull
// public static Duration millis(long time) {
// return of(time, TimeUnit.MILLISECONDS);
// }
//
// @NotNull
// public static Duration seconds(long time) {
// return of(time, TimeUnit.SECONDS);
// }
//
// private Duration(long time, @NotNull TimeUnit timeUnit) {
// this.time = time;
// this.timeUnit = timeUnit;
// }
//
//
// public long getTime() {
// return time;
// }
//
// @NotNull
// public TimeUnit getTimeUnit() {
// return timeUnit;
// }
//
// public long toMillis() {
// return timeUnit.toMillis(time);
// }
//
// public boolean isZero() {
// return time==0;
// }
//
// @Override
// public String toString() {
// return "Duration[" + time + toString(timeUnit) + ']';
// }
//
// @NotNull
// private String toString(@NotNull TimeUnit timeUnit) {
// switch (timeUnit) {
// case MILLISECONDS:
// return "ms";
// case SECONDS:
// return "s";
// case MINUTES:
// return "m";
// case HOURS:
// return "h";
// case DAYS:
// return "d";
// default:
// return timeUnit.name();
// }
// }
// }
// Path: src/main/java/com/optimaize/command4j/ext/extensions/failover/autoretry/AlwaysOnceInstantAutoRetryStrategy.java
import com.optimaize.command4j.lang.Duration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
package com.optimaize.command4j.ext.extensions.failover.autoretry;
/**
* @author Fabian Kessler
*/
class AlwaysOnceInstantAutoRetryStrategy implements AutoRetryStrategy {
public static final AutoRetryStrategy INSTANCE = new AlwaysOnceInstantAutoRetryStrategy();
private AlwaysOnceInstantAutoRetryStrategy(){}
@Override @Nullable | public Duration doRetry(int executionCounter, @NotNull Exception exception) { |
monkeyk/spring-oauth-server | src/test/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbcTest.java | // Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
//
// Path: src/test/java/com/monkeyk/sos/infrastructure/AbstractRepositoryTest.java
// public abstract class AbstractRepositoryTest extends ContextTest {
//
//
// @Autowired
// private JdbcTemplate jdbcTemplate;
//
//
// public JdbcTemplate jdbcTemplate() {
// return jdbcTemplate;
// }
//
//
// }
| import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import com.monkeyk.sos.infrastructure.AbstractRepositoryTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static org.junit.Assert.*; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/*
* @author Shengzhao Li
*/
public class UserRepositoryJdbcTest extends AbstractRepositoryTest {
@Autowired | // Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
//
// Path: src/test/java/com/monkeyk/sos/infrastructure/AbstractRepositoryTest.java
// public abstract class AbstractRepositoryTest extends ContextTest {
//
//
// @Autowired
// private JdbcTemplate jdbcTemplate;
//
//
// public JdbcTemplate jdbcTemplate() {
// return jdbcTemplate;
// }
//
//
// }
// Path: src/test/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbcTest.java
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import com.monkeyk.sos.infrastructure.AbstractRepositoryTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static org.junit.Assert.*;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/*
* @author Shengzhao Li
*/
public class UserRepositoryJdbcTest extends AbstractRepositoryTest {
@Autowired | private UserRepository userRepository; |
monkeyk/spring-oauth-server | src/test/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbcTest.java | // Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
//
// Path: src/test/java/com/monkeyk/sos/infrastructure/AbstractRepositoryTest.java
// public abstract class AbstractRepositoryTest extends ContextTest {
//
//
// @Autowired
// private JdbcTemplate jdbcTemplate;
//
//
// public JdbcTemplate jdbcTemplate() {
// return jdbcTemplate;
// }
//
//
// }
| import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import com.monkeyk.sos.infrastructure.AbstractRepositoryTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static org.junit.Assert.*; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/*
* @author Shengzhao Li
*/
public class UserRepositoryJdbcTest extends AbstractRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void findByGuid() { | // Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
//
// Path: src/test/java/com/monkeyk/sos/infrastructure/AbstractRepositoryTest.java
// public abstract class AbstractRepositoryTest extends ContextTest {
//
//
// @Autowired
// private JdbcTemplate jdbcTemplate;
//
//
// public JdbcTemplate jdbcTemplate() {
// return jdbcTemplate;
// }
//
//
// }
// Path: src/test/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbcTest.java
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import com.monkeyk.sos.infrastructure.AbstractRepositoryTest;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import static org.junit.Assert.*;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/*
* @author Shengzhao Li
*/
public class UserRepositoryJdbcTest extends AbstractRepositoryTest {
@Autowired
private UserRepository userRepository;
@Test
public void findByGuid() { | User user = userRepository.findByGuid("oood"); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; | package com.monkeyk.sos.service.dto;
/**
* @author Shengzhao Li
*/
public class UserJsonDto implements Serializable {
private String guid;
private boolean archived;
private String username;
private String phone;
private String email;
private List<String> privileges = new ArrayList<>();
public UserJsonDto() {
}
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
package com.monkeyk.sos.service.dto;
/**
* @author Shengzhao Li
*/
public class UserJsonDto implements Serializable {
private String guid;
private boolean archived;
private String username;
private String phone;
private String email;
private List<String> privileges = new ArrayList<>();
public UserJsonDto() {
}
| public UserJsonDto(User user) { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List; | package com.monkeyk.sos.service.dto;
/**
* @author Shengzhao Li
*/
public class UserJsonDto implements Serializable {
private String guid;
private boolean archived;
private String username;
private String phone;
private String email;
private List<String> privileges = new ArrayList<>();
public UserJsonDto() {
}
public UserJsonDto(User user) {
this.guid = user.guid();
this.archived = user.archived();
this.username = user.username();
this.phone = user.phone();
this.email = user.email();
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
package com.monkeyk.sos.service.dto;
/**
* @author Shengzhao Li
*/
public class UserJsonDto implements Serializable {
private String guid;
private boolean archived;
private String username;
private String phone;
private String email;
private List<String> privileges = new ArrayList<>();
public UserJsonDto() {
}
public UserJsonDto(User user) {
this.guid = user.guid();
this.archived = user.archived();
this.username = user.username();
this.phone = user.phone();
this.email = user.email();
| final List<Privilege> privilegeList = user.privileges(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/resource/MobileController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/m/")
public class MobileController {
@Autowired | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/resource/MobileController.java
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/m/")
public class MobileController {
@Autowired | private UserService userService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/resource/MobileController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/m/")
public class MobileController {
@Autowired
private UserService userService;
@RequestMapping("dashboard")
public String dashboard() {
return "mobile/dashboard";
}
@RequestMapping("user_info")
@ResponseBody | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/resource/MobileController.java
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/m/")
public class MobileController {
@Autowired
private UserService userService;
@RequestMapping("dashboard")
public String dashboard() {
return "mobile/dashboard";
}
@RequestMapping("user_info")
@ResponseBody | public UserJsonDto userInfo() { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/domain/AbstractDomain.java | // Path: src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java
// public abstract class GuidGenerator {
//
//
// private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32);
//
//
// /**
// * private constructor
// */
// private GuidGenerator() {
// }
//
// public static String generate() {
// return UUID.randomUUID().toString().replaceAll("-", "");
// }
//
// public static String generateClientSecret() {
// return defaultClientSecretGenerator.generate();
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
| import com.monkeyk.sos.domain.shared.GuidGenerator;
import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime; | package com.monkeyk.sos.domain;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
private static final long serialVersionUID = 6569365774429340632L;
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/ | // Path: src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java
// public abstract class GuidGenerator {
//
//
// private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32);
//
//
// /**
// * private constructor
// */
// private GuidGenerator() {
// }
//
// public static String generate() {
// return UUID.randomUUID().toString().replaceAll("-", "");
// }
//
// public static String generateClientSecret() {
// return defaultClientSecretGenerator.generate();
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
// Path: src/main/java/com/monkeyk/sos/domain/AbstractDomain.java
import com.monkeyk.sos.domain.shared.GuidGenerator;
import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime;
package com.monkeyk.sos.domain;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
private static final long serialVersionUID = 6569365774429340632L;
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/ | protected String guid = GuidGenerator.generate(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/domain/AbstractDomain.java | // Path: src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java
// public abstract class GuidGenerator {
//
//
// private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32);
//
//
// /**
// * private constructor
// */
// private GuidGenerator() {
// }
//
// public static String generate() {
// return UUID.randomUUID().toString().replaceAll("-", "");
// }
//
// public static String generateClientSecret() {
// return defaultClientSecretGenerator.generate();
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
| import com.monkeyk.sos.domain.shared.GuidGenerator;
import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime; | package com.monkeyk.sos.domain;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
private static final long serialVersionUID = 6569365774429340632L;
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/
protected String guid = GuidGenerator.generate();
/**
* The domain create time.
*/ | // Path: src/main/java/com/monkeyk/sos/domain/shared/GuidGenerator.java
// public abstract class GuidGenerator {
//
//
// private static RandomValueStringGenerator defaultClientSecretGenerator = new RandomValueStringGenerator(32);
//
//
// /**
// * private constructor
// */
// private GuidGenerator() {
// }
//
// public static String generate() {
// return UUID.randomUUID().toString().replaceAll("-", "");
// }
//
// public static String generateClientSecret() {
// return defaultClientSecretGenerator.generate();
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
// Path: src/main/java/com/monkeyk/sos/domain/AbstractDomain.java
import com.monkeyk.sos.domain.shared.GuidGenerator;
import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime;
package com.monkeyk.sos.domain;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
private static final long serialVersionUID = 6569365774429340632L;
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/
protected String guid = GuidGenerator.generate();
/**
* The domain create time.
*/ | protected LocalDateTime createTime = DateUtils.now(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/WebSecurityConfigurer.java | // Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder; | package com.monkeyk.sos.config;
/**
* 2016/4/3
* <p/>
* Replace security.xml
*
* @author Shengzhao Li
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired | // Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/config/WebSecurityConfigurer.java
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
package com.monkeyk.sos.config;
/**
* 2016/4/3
* <p/>
* Replace security.xml
*
* @author Shengzhao Li
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {
@Autowired | private UserService userService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler; | package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler;
package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
| public Privilege[] getAllPrivileges() { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler; | package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
public Privilege[] getAllPrivileges() {
return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler;
package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
public Privilege[] getAllPrivileges() {
return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
| public User newUser() { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler; | package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
public Privilege[] getAllPrivileges() {
return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User newUser() {
final User user = new User()
.username(getUsername())
.phone(getPhone())
.email(getEmail()) | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/infrastructure/PasswordHandler.java
// public abstract class PasswordHandler {
//
//
// private PasswordHandler() {
// }
//
//
// public static String encode(String password) {
// BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
// return encoder.encode(password);
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.infrastructure.PasswordHandler;
package com.monkeyk.sos.service.dto;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
public class UserFormDto extends UserDto {
private static final long serialVersionUID = 7959857016962260738L;
private String password;
public UserFormDto() {
}
public Privilege[] getAllPrivileges() {
return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User newUser() {
final User user = new User()
.username(getUsername())
.phone(getPhone())
.email(getEmail()) | .password(PasswordHandler.encode(getPassword())); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource; | package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java
import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired | private OauthService oauthService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource; | package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OauthService oauthService;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java
import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OauthService oauthService;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired | private UserService userDetailsService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource; | package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OauthService oauthService;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired
private UserService userDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Bean
public TokenStore tokenStore(DataSource dataSource) {
return new JdbcTokenStore(dataSource);
}
@Bean
public ClientDetailsService clientDetailsService(DataSource dataSource) { | // Path: src/main/java/com/monkeyk/sos/domain/oauth/CustomJdbcClientDetailsService.java
// public class CustomJdbcClientDetailsService extends JdbcClientDetailsService {
//
// private static final String SELECT_CLIENT_DETAILS_SQL = "select client_id, client_secret, resource_ids, scope, authorized_grant_types, " +
// "web_server_redirect_uri, authorities, access_token_validity, refresh_token_validity, additional_information, autoapprove " +
// "from oauth_client_details where client_id = ? and archived = 0 ";
//
//
// public CustomJdbcClientDetailsService(DataSource dataSource) {
// super(dataSource);
// setSelectClientDetailsSql(SELECT_CLIENT_DETAILS_SQL);
// }
//
//
// }
//
// Path: src/main/java/com/monkeyk/sos/service/OauthService.java
// public interface OauthService {
//
// OauthClientDetails loadOauthClientDetails(String clientId);
//
// List<OauthClientDetailsDto> loadAllOauthClientDetailsDtos();
//
// void archiveOauthClientDetails(String clientId);
//
// OauthClientDetailsDto loadOauthClientDetailsDto(String clientId);
//
// void registerClientDetails(OauthClientDetailsDto formDto);
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/config/OAuth2ServerConfiguration.java
import com.monkeyk.sos.domain.oauth.CustomJdbcClientDetailsService;
import com.monkeyk.sos.service.OauthService;
import com.monkeyk.sos.service.UserService;
import com.monkeyk.sos.web.oauth.OauthUserApprovalHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
package com.monkeyk.sos.config;
/**
* 2018/2/8
* <p>
* <p>
* OAuth2 config
*
* @author Shengzhao Li
*/
@Configuration
public class OAuth2ServerConfiguration {
/*Fixed, resource-id */
public static final String RESOURCE_ID = "sos-resource";
// unity resource
@Configuration
@EnableResourceServer
protected static class UnityResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/unity/**")
.and()
.authorizeRequests()
.antMatchers("/unity/**").access("#oauth2.hasScope('read') and hasRole('ROLE_UNITY')");
}
}
// mobile resource
@Configuration
@EnableResourceServer
protected static class MobileResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID).stateless(false);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
// Since we want the protected resources to be accessible in the UI as well we need
// session creation to be allowed (it's disabled by default in 2.0.6)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.and()
.requestMatchers().antMatchers("/m/**")
.and()
.authorizeRequests()
.antMatchers("/m/**").access("#oauth2.hasScope('read') and hasRole('ROLE_MOBILE')");
}
}
@Configuration
@EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private OauthService oauthService;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired
private UserService userDetailsService;
@Autowired
@Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Bean
public TokenStore tokenStore(DataSource dataSource) {
return new JdbcTokenStore(dataSource);
}
@Bean
public ClientDetailsService clientDetailsService(DataSource dataSource) { | return new CustomJdbcClientDetailsService(dataSource); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List; | package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List;
package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired | private UserService userService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List; | package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired
private UserService userService;
@Override
public boolean supports(Class<?> clazz) { | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List;
package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired
private UserService userService;
@Override
public boolean supports(Class<?> clazz) { | return UserFormDto.class.equals(clazz); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List; | package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired
private UserService userService;
@Override
public boolean supports(Class<?> clazz) {
return UserFormDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserFormDto formDto = (UserFormDto) target;
validateUsername(errors, formDto);
validatePassword(errors, formDto);
validatePrivileges(errors, formDto);
}
private void validatePrivileges(Errors errors, UserFormDto formDto) { | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserFormDtoValidator.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import java.util.List;
package com.monkeyk.sos.web.controller;
/**
* 2016/3/25
*
* @author Shengzhao Li
*/
@Component
public class UserFormDtoValidator implements Validator {
@Autowired
private UserService userService;
@Override
public boolean supports(Class<?> clazz) {
return UserFormDto.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
UserFormDto formDto = (UserFormDto) target;
validateUsername(errors, formDto);
validatePassword(errors, formDto);
validatePrivileges(errors, formDto);
}
private void validatePrivileges(Errors errors, UserFormDto formDto) { | final List<Privilege> privileges = formDto.getPrivileges(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/MVCConfiguration.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
| import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List; | package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters); | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
// Path: src/main/java/com/monkeyk/sos/config/MVCConfiguration.java
import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List;
package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters); | converters.add(new StringHttpMessageConverter(Charset.forName(WebUtils.UTF_8))); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/MVCConfiguration.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
| import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List; | package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters);
converters.add(new StringHttpMessageConverter(Charset.forName(WebUtils.UTF_8)));
}
/**
* 字符编码配置 UTF-8
*/
@Bean
public FilterRegistrationBean encodingFilter() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
// Path: src/main/java/com/monkeyk/sos/config/MVCConfiguration.java
import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List;
package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters);
converters.add(new StringHttpMessageConverter(Charset.forName(WebUtils.UTF_8)));
}
/**
* 字符编码配置 UTF-8
*/
@Bean
public FilterRegistrationBean encodingFilter() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); | registrationBean.setFilter(new CharacterEncodingIPFilter()); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/config/MVCConfiguration.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
| import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List; | package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters);
converters.add(new StringHttpMessageConverter(Charset.forName(WebUtils.UTF_8)));
}
/**
* 字符编码配置 UTF-8
*/
@Bean
public FilterRegistrationBean encodingFilter() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CharacterEncodingIPFilter());
registrationBean.addUrlPatterns("/*");
//值越小越靠前
registrationBean.setOrder(1);
return registrationBean;
}
/**
* sitemesh filter
*/
@Bean
public FilterRegistrationBean sitemesh() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
// public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
//
// private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
//
//
// @Override
// protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// recordIP(request);
// super.doFilterInternal(request, response, filterChain);
// }
//
// private void recordIP(HttpServletRequest request) {
// final String ip = WebUtils.retrieveClientIp(request);
// WebUtils.setIp(ip);
// LOG.debug("Send request uri: {}, from IP: {}", request.getRequestURI(), ip);
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/web/filter/SOSSiteMeshFilter.java
// public class SOSSiteMeshFilter extends ConfigurableSiteMeshFilter {
//
//
// public SOSSiteMeshFilter() {
// }
//
//
// @Override
// protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//
// builder.addDecoratorPath("/*", "/WEB-INF/jsp/decorators/main.jsp")
//
// .addExcludedPath("/static/**");
//
//
// }
// }
// Path: src/main/java/com/monkeyk/sos/config/MVCConfiguration.java
import com.monkeyk.sos.web.WebUtils;
import com.monkeyk.sos.web.filter.CharacterEncodingIPFilter;
import com.monkeyk.sos.web.filter.SOSSiteMeshFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.Filter;
import java.nio.charset.Charset;
import java.util.List;
package com.monkeyk.sos.config;
/**
* 2018/1/30
* <p>
* Spring MVC 扩展配置
* <p>
*
* @author Shengzhao Li
*/
@Configuration
public class MVCConfiguration implements WebMvcConfigurer {
/**
* 扩展拦截器
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
WebMvcConfigurer.super.addInterceptors(registry);
}
/**
* 解决乱码问题
* For UTF-8
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
WebMvcConfigurer.super.configureMessageConverters(converters);
converters.add(new StringHttpMessageConverter(Charset.forName(WebUtils.UTF_8)));
}
/**
* 字符编码配置 UTF-8
*/
@Bean
public FilterRegistrationBean encodingFilter() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CharacterEncodingIPFilter());
registrationBean.addUrlPatterns("/*");
//值越小越靠前
registrationBean.setOrder(1);
return registrationBean;
}
/**
* sitemesh filter
*/
@Bean
public FilterRegistrationBean sitemesh() {
FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean<>(); | registrationBean.setFilter(new SOSSiteMeshFilter()); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/UserService.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import org.springframework.security.core.userdetails.UserDetailsService; | package com.monkeyk.sos.service;
/**
* @author Shengzhao Li
*/
public interface UserService extends UserDetailsService {
UserJsonDto loadCurrentUserJsonDto();
| // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import org.springframework.security.core.userdetails.UserDetailsService;
package com.monkeyk.sos.service;
/**
* @author Shengzhao Li
*/
public interface UserService extends UserDetailsService {
UserJsonDto loadCurrentUserJsonDto();
| UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/UserService.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import org.springframework.security.core.userdetails.UserDetailsService; | package com.monkeyk.sos.service;
/**
* @author Shengzhao Li
*/
public interface UserService extends UserDetailsService {
UserJsonDto loadCurrentUserJsonDto();
UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
boolean isExistedUsername(String username);
| // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import org.springframework.security.core.userdetails.UserDetailsService;
package com.monkeyk.sos.service;
/**
* @author Shengzhao Li
*/
public interface UserService extends UserDetailsService {
UserJsonDto loadCurrentUserJsonDto();
UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
boolean isExistedUsername(String username);
| String saveUser(UserFormDto formDto); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
| import com.monkeyk.sos.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; | package com.monkeyk.sos.web.filter;
/**
* 2016/1/30
*
* @author Shengzhao Li
*/
public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
recordIP(request);
super.doFilterInternal(request, response, filterChain);
}
private void recordIP(HttpServletRequest request) { | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
// Path: src/main/java/com/monkeyk/sos/web/filter/CharacterEncodingIPFilter.java
import com.monkeyk.sos.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.CharacterEncodingFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
package com.monkeyk.sos.web.filter;
/**
* 2016/1/30
*
* @author Shengzhao Li
*/
public class CharacterEncodingIPFilter extends CharacterEncodingFilter {
private static final Logger LOG = LoggerFactory.getLogger(CharacterEncodingIPFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
recordIP(request);
super.doFilterInternal(request, response, filterChain);
}
private void recordIP(HttpServletRequest request) { | final String ip = WebUtils.retrieveClientIp(request); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.service.dto;
/**
* 2016/3/12
*
* @author Shengzhao Li
*/
public class UserDto implements Serializable {
private static final long serialVersionUID = -2502329463915439215L;
private String guid;
private String username;
private String phone;
private String email;
private String createTime;
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.service.dto;
/**
* 2016/3/12
*
* @author Shengzhao Li
*/
public class UserDto implements Serializable {
private static final long serialVersionUID = -2502329463915439215L;
private String guid;
private String username;
private String phone;
private String email;
private String createTime;
| private List<Privilege> privileges = new ArrayList<>(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/service/dto/UserDto.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.service.dto;
/**
* 2016/3/12
*
* @author Shengzhao Li
*/
public class UserDto implements Serializable {
private static final long serialVersionUID = -2502329463915439215L;
private String guid;
private String username;
private String phone;
private String email;
private String createTime;
private List<Privilege> privileges = new ArrayList<>();
public UserDto() {
}
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/service/dto/UserDto.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import java.io.Serializable;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.service.dto;
/**
* 2016/3/12
*
* @author Shengzhao Li
*/
public class UserDto implements Serializable {
private static final long serialVersionUID = -2502329463915439215L;
private String guid;
private String username;
private String phone;
private String email;
private String createTime;
private List<Privilege> privileges = new ArrayList<>();
public UserDto() {
}
| public UserDto(User user) { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/SpringOauthServerServletInitializer.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
| import com.monkeyk.sos.web.WebUtils;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException; | package com.monkeyk.sos;
/**
* 2017-12-05
*
* @author Shengzhao Li
*/
public class SpringOauthServerServletInitializer extends SpringBootServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
//主版本号 | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
// Path: src/main/java/com/monkeyk/sos/SpringOauthServerServletInitializer.java
import com.monkeyk.sos.web.WebUtils;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
package com.monkeyk.sos;
/**
* 2017-12-05
*
* @author Shengzhao Li
*/
public class SpringOauthServerServletInitializer extends SpringBootServletInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
//主版本号 | servletContext.setAttribute("mainVersion", WebUtils.VERSION); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/SOSController.java | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
| import com.monkeyk.sos.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; | package com.monkeyk.sos.web.controller;
/**
* 2018/4/19
* <p>
* starup
*
* @author Shengzhao Li
*/
@Controller
public class SOSController {
private static final Logger LOG = LoggerFactory.getLogger(SOSController.class);
/**
* 首页
*/
@RequestMapping(value = "/")
public String index(Model model) {
return "index";
}
//Go login
@GetMapping(value = {"/login"})
public String login(Model model) { | // Path: src/main/java/com/monkeyk/sos/web/WebUtils.java
// public abstract class WebUtils {
//
//
// public static final String UTF_8 = "UTF-8";
//
//
// /**
// * Sync by pom.xml <version></version>
// */
// public static final String VERSION = "2.0.1";
//
//
// private static ThreadLocal<String> ipThreadLocal = new ThreadLocal<>();
//
//
// public static void setIp(String ip) {
// ipThreadLocal.set(ip);
// }
//
// public static String getIp() {
// return ipThreadLocal.get();
// }
//
// //private
// private WebUtils() {
// }
//
//
// /**
// * Retrieve client ip address
// *
// * @param request HttpServletRequest
// * @return IP
// */
// public static String retrieveClientIp(HttpServletRequest request) {
// String ip = request.getHeader("x-forwarded-for");
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getHeader("WL-Proxy-Client-IP");
// }
// if (isUnAvailableIp(ip)) {
// ip = request.getRemoteAddr();
// }
// return ip;
// }
//
// private static boolean isUnAvailableIp(String ip) {
// return StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip);
// }
//
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/SOSController.java
import com.monkeyk.sos.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
package com.monkeyk.sos.web.controller;
/**
* 2018/4/19
* <p>
* starup
*
* @author Shengzhao Li
*/
@Controller
public class SOSController {
private static final Logger LOG = LoggerFactory.getLogger(SOSController.class);
/**
* 首页
*/
@RequestMapping(value = "/")
public String index(Model model) {
return "index";
}
//Go login
@GetMapping(value = {"/login"})
public String login(Model model) { | LOG.info("Go to login, IP: {}", WebUtils.getIp()); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/resource/UnityController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/unity/")
public class UnityController {
@Autowired | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/resource/UnityController.java
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/unity/")
public class UnityController {
@Autowired | private UserService userService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/resource/UnityController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; | package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/unity/")
public class UnityController {
@Autowired
private UserService userService;
@RequestMapping("dashboard")
public String dashboard() {
return "unity/dashboard";
}
@RequestMapping("user_info")
@ResponseBody | // Path: src/main/java/com/monkeyk/sos/service/dto/UserJsonDto.java
// public class UserJsonDto implements Serializable {
//
//
// private String guid;
// private boolean archived;
//
// private String username;
// private String phone;
// private String email;
//
// private List<String> privileges = new ArrayList<>();
//
// public UserJsonDto() {
// }
//
// public UserJsonDto(User user) {
// this.guid = user.guid();
// this.archived = user.archived();
// this.username = user.username();
//
// this.phone = user.phone();
// this.email = user.email();
//
// final List<Privilege> privilegeList = user.privileges();
// for (Privilege privilege : privilegeList) {
// this.privileges.add(privilege.name());
// }
// }
//
// public boolean isArchived() {
// return archived;
// }
//
// public void setArchived(boolean archived) {
// this.archived = archived;
// }
//
// public String getGuid() {
// return guid;
// }
//
// public void setGuid(String guid) {
// this.guid = guid;
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public String getPhone() {
// return phone;
// }
//
// public void setPhone(String phone) {
// this.phone = phone;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public List<String> getPrivileges() {
// return privileges;
// }
//
// public void setPrivileges(List<String> privileges) {
// this.privileges = privileges;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/resource/UnityController.java
import com.monkeyk.sos.service.dto.UserJsonDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
package com.monkeyk.sos.web.controller.resource;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/unity/")
public class UnityController {
@Autowired
private UserService userService;
@RequestMapping("dashboard")
public String dashboard() {
return "unity/dashboard";
}
@RequestMapping("user_info")
@ResponseBody | public UserJsonDto userInfo() { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/domain/shared/security/SOSUserDetails.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | package com.monkeyk.sos.domain.shared.security;
/**
* @author Shengzhao Li
*/
public class SOSUserDetails implements UserDetails {
private static final long serialVersionUID = 3957586021470480642L;
protected static final String ROLE_PREFIX = "ROLE_"; | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/domain/shared/security/SOSUserDetails.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
package com.monkeyk.sos.domain.shared.security;
/**
* @author Shengzhao Li
*/
public class SOSUserDetails implements UserDetails {
private static final long serialVersionUID = 3957586021470480642L;
protected static final String ROLE_PREFIX = "ROLE_"; | protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + Privilege.USER.name()); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/domain/shared/security/SOSUserDetails.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List; | package com.monkeyk.sos.domain.shared.security;
/**
* @author Shengzhao Li
*/
public class SOSUserDetails implements UserDetails {
private static final long serialVersionUID = 3957586021470480642L;
protected static final String ROLE_PREFIX = "ROLE_";
protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + Privilege.USER.name());
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
// Path: src/main/java/com/monkeyk/sos/domain/shared/security/SOSUserDetails.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
package com.monkeyk.sos.domain.shared.security;
/**
* @author Shengzhao Li
*/
public class SOSUserDetails implements UserDetails {
private static final long serialVersionUID = 3957586021470480642L;
protected static final String ROLE_PREFIX = "ROLE_";
protected static final GrantedAuthority DEFAULT_USER_ROLE = new SimpleGrantedAuthority(ROLE_PREFIX + Privilege.USER.name());
| protected User user; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbc.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/**
* 2015/11/16
*
* @author Shengzhao Li
*/
@Repository("userRepositoryJdbc")
public class UserRepositoryJdbc implements UserRepository {
private static UserRowMapper userRowMapper = new UserRowMapper();
@Autowired
private JdbcTemplate jdbcTemplate;
@Override | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
// Path: src/main/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbc.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/**
* 2015/11/16
*
* @author Shengzhao Li
*/
@Repository("userRepositoryJdbc")
public class UserRepositoryJdbc implements UserRepository {
private static UserRowMapper userRowMapper = new UserRowMapper();
@Autowired
private JdbcTemplate jdbcTemplate;
@Override | public User findByGuid(String guid) { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbc.java | // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
| import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors; | /*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/**
* 2015/11/16
*
* @author Shengzhao Li
*/
@Repository("userRepositoryJdbc")
public class UserRepositoryJdbc implements UserRepository {
private static UserRowMapper userRowMapper = new UserRowMapper();
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findByGuid(String guid) {
final String sql = " select * from user_ where guid = ? ";
final List<User> list = this.jdbcTemplate.query(sql, new Object[]{guid}, userRowMapper);
User user = null;
if (!list.isEmpty()) {
user = list.get(0);
user.privileges().addAll(findPrivileges(user.id()));
}
return user;
}
| // Path: src/main/java/com/monkeyk/sos/domain/user/Privilege.java
// public enum Privilege {
//
// USER, //Default privilege
//
// ADMIN, //admin
// UNITY,
// MOBILE
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/User.java
// public class User extends AbstractDomain {
//
//
// private static final long serialVersionUID = -2921689304753120556L;
//
//
// private String username;
// private String password;
//
// private String phone;
// private String email;
// //Default user is initial when create database, do not delete
// private boolean defaultUser = false;
//
// private Date lastLoginTime;
//
// private List<Privilege> privileges = new ArrayList<>();
//
// public User() {
// }
//
// public User(String username, String password, String phone, String email) {
// this.username = username;
// this.password = password;
// this.phone = phone;
// this.email = email;
// }
//
// public boolean defaultUser() {
// return defaultUser;
// }
//
// public String username() {
// return username;
// }
//
// public String password() {
// return password;
// }
//
// public String phone() {
// return phone;
// }
//
// public String email() {
// return email;
// }
//
// public List<Privilege> privileges() {
// return privileges;
// }
//
// @Override
// public String toString() {
// final StringBuilder sb = new StringBuilder();
// sb.append("{username='").append(username).append('\'');
// sb.append(", phone='").append(phone).append('\'');
// sb.append(", id='").append(id).append('\'');
// sb.append(", guid='").append(guid).append('\'');
// sb.append(", defaultUser='").append(defaultUser).append('\'');
// sb.append(", email='").append(email).append('\'');
// sb.append('}');
// return sb.toString();
// }
//
// public User email(String email) {
// this.email = email;
// return this;
// }
//
// public User phone(String phone) {
// this.phone = phone;
// return this;
// }
//
//
// public User username(String username) {
// this.username = username;
// return this;
// }
//
//
// public Date lastLoginTime() {
// return lastLoginTime;
// }
//
// public User lastLoginTime(Date lastLoginTime) {
// this.lastLoginTime = lastLoginTime;
// return this;
// }
//
// public User createTime(LocalDateTime createTime) {
// this.createTime = createTime;
// return this;
// }
//
// public User password(String password) {
// this.password = password;
// return this;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/domain/user/UserRepository.java
// public interface UserRepository extends Repository {
//
// User findByGuid(String guid);
//
// void saveUser(User user);
//
// void updateUser(User user);
//
// User findByUsername(String username);
//
// List<User> findUsersByUsername(String username);
// }
// Path: src/main/java/com/monkeyk/sos/infrastructure/jdbc/UserRepositoryJdbc.java
import com.monkeyk.sos.domain.user.Privilege;
import com.monkeyk.sos.domain.user.User;
import com.monkeyk.sos.domain.user.UserRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/*
* Copyright (c) 2015 MONKEYK Information Technology Co. Ltd
* www.monkeyk.com
* All rights reserved.
*
* This software is the confidential and proprietary information of
* MONKEYK Information Technology Co. Ltd ("Confidential Information").
* You shall not disclose such Confidential Information and shall use
* it only in accordance with the terms of the license agreement you
* entered into with MONKEYK Information Technology Co. Ltd.
*/
package com.monkeyk.sos.infrastructure.jdbc;
/**
* 2015/11/16
*
* @author Shengzhao Li
*/
@Repository("userRepositoryJdbc")
public class UserRepositoryJdbc implements UserRepository {
private static UserRowMapper userRowMapper = new UserRowMapper();
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findByGuid(String guid) {
final String sql = " select * from user_ where guid = ? ";
final List<User> list = this.jdbcTemplate.query(sql, new Object[]{guid}, userRowMapper);
User user = null;
if (!list.isEmpty()) {
user = list.get(0);
user.privileges().addAll(findPrivileges(user.id()));
}
return user;
}
| private Collection<Privilege> findPrivileges(int userId) { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/domain/oauth/OauthClientDetails.java | // Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
| import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime; | package com.monkeyk.sos.domain.oauth;
/**
* @author Shengzhao Li
*/
public class OauthClientDetails implements Serializable {
private static final long serialVersionUID = -6947822646185526939L;
| // Path: src/main/java/com/monkeyk/sos/infrastructure/DateUtils.java
// public abstract class DateUtils {
//
// public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
//
//
// /**
// * Private constructor
// */
// private DateUtils() {
// }
//
// public static LocalDateTime now() {
// return LocalDateTime.now();
// }
//
//
// public static String toDateTime(LocalDateTime date) {
// return toDateTime(date, DEFAULT_DATE_TIME_FORMAT);
// }
//
// public static String toDateTime(LocalDateTime dateTime, String pattern) {
// return dateTime.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
//
// public static String toDateText(LocalDate date, String pattern) {
// if (date == null || pattern == null) {
// return null;
// }
// return date.format(DateTimeFormatter.ofPattern(pattern, Locale.SIMPLIFIED_CHINESE));
// }
//
//
// }
// Path: src/main/java/com/monkeyk/sos/domain/oauth/OauthClientDetails.java
import com.monkeyk.sos.infrastructure.DateUtils;
import java.io.Serializable;
import java.time.LocalDateTime;
package com.monkeyk.sos.domain.oauth;
/**
* @author Shengzhao Li
*/
public class OauthClientDetails implements Serializable {
private static final long serialVersionUID = -6947822646185526939L;
| private LocalDateTime createTime = DateUtils.now(); |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; | package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserController.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired | private UserService userService; |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; | package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserFormDtoValidator validator;
/**
* @return View page
*/
@RequestMapping("overview") | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserController.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserFormDtoValidator validator;
/**
* @return View page
*/
@RequestMapping("overview") | public String overview(UserOverviewDto overviewDto, Model model) { |
monkeyk/spring-oauth-server | src/main/java/com/monkeyk/sos/web/controller/UserController.java | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
| import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; | package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserFormDtoValidator validator;
/**
* @return View page
*/
@RequestMapping("overview")
public String overview(UserOverviewDto overviewDto, Model model) {
overviewDto = userService.loadUserOverviewDto(overviewDto);
model.addAttribute("overviewDto", overviewDto);
return "user_overview";
}
@RequestMapping(value = "form/plus", method = RequestMethod.GET)
public String showForm(Model model) { | // Path: src/main/java/com/monkeyk/sos/service/dto/UserFormDto.java
// public class UserFormDto extends UserDto {
// private static final long serialVersionUID = 7959857016962260738L;
//
//
// private String password;
//
// public UserFormDto() {
// }
//
//
// public Privilege[] getAllPrivileges() {
// return new Privilege[]{Privilege.MOBILE, Privilege.UNITY};
// }
//
// public String getPassword() {
// return password;
// }
//
// public void setPassword(String password) {
// this.password = password;
// }
//
// public User newUser() {
// final User user = new User()
// .username(getUsername())
// .phone(getPhone())
// .email(getEmail())
// .password(PasswordHandler.encode(getPassword()));
// user.privileges().addAll(getPrivileges());
// return user;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/dto/UserOverviewDto.java
// public class UserOverviewDto implements Serializable {
// private static final long serialVersionUID = 2023379587030489248L;
//
//
// private String username;
//
//
// private List<UserDto> userDtos = new ArrayList<>();
//
//
// public UserOverviewDto() {
// }
//
// public int getSize() {
// return userDtos.size();
// }
//
// public String getUsername() {
// return username;
// }
//
// public void setUsername(String username) {
// this.username = username;
// }
//
// public List<UserDto> getUserDtos() {
// return userDtos;
// }
//
// public void setUserDtos(List<UserDto> userDtos) {
// this.userDtos = userDtos;
// }
// }
//
// Path: src/main/java/com/monkeyk/sos/service/UserService.java
// public interface UserService extends UserDetailsService {
//
// UserJsonDto loadCurrentUserJsonDto();
//
// UserOverviewDto loadUserOverviewDto(UserOverviewDto overviewDto);
//
// boolean isExistedUsername(String username);
//
// String saveUser(UserFormDto formDto);
// }
// Path: src/main/java/com/monkeyk/sos/web/controller/UserController.java
import com.monkeyk.sos.service.dto.UserFormDto;
import com.monkeyk.sos.service.dto.UserOverviewDto;
import com.monkeyk.sos.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
package com.monkeyk.sos.web.controller;
/**
* @author Shengzhao Li
*/
@Controller
@RequestMapping("/user/")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private UserFormDtoValidator validator;
/**
* @return View page
*/
@RequestMapping("overview")
public String overview(UserOverviewDto overviewDto, Model model) {
overviewDto = userService.loadUserOverviewDto(overviewDto);
model.addAttribute("overviewDto", overviewDto);
return "user_overview";
}
@RequestMapping(value = "form/plus", method = RequestMethod.GET)
public String showForm(Model model) { | model.addAttribute("formDto", new UserFormDto()); |
fracpete/multisearch-weka-package | src/main/java/weka/classifiers/meta/multisearch/Performance.java | // Path: src/main/java/weka/core/setupgenerator/Point.java
// public class Point<E>
// implements Serializable, Cloneable, Comparable<Point<E>> {
//
// /** for serialization. */
// private static final long serialVersionUID = 1061326306122503731L;
//
// /** the values in the various dimensions. */
// protected Object[] m_Values;
//
// /**
// * Initializes the point with the given values.
// *
// * @param values the position in the various dimensions
// */
// public Point(E[] values) {
// m_Values = (E[]) values.clone();
// }
//
// /**
// * Returns a clone of itself.
// *
// * @return a clone of itself
// */
// public Object clone() {
// return new Point(m_Values.clone());
// }
//
// /**
// * Returns the number of dimensions this points uses.
// *
// * @return the number of dimensions
// */
// public int dimensions() {
// return m_Values.length;
// }
//
// /**
// * Returns the value in the specified dimension.
// *
// * @param dimension the dimension to get the value for
// * @return the value
// */
// public E getValue(int dimension) {
// return (E) m_Values[dimension];
// }
//
// /**
// * Determines whether or not two points are equal.
// *
// * @param obj an object to be compared with this PointDouble
// * @return true if the object to be compared has the same values;
// * false otherwise.
// */
// public boolean equals(Object obj) {
// Point<E> pd;
// int i;
//
// if (obj == null)
// return false;
//
// if (!(obj instanceof Point))
// return false;
//
// pd = (Point<E>) obj;
//
// if (dimensions() != pd.dimensions())
// return false;
//
// for (i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != pd.getValue(i).getClass())
// return false;
//
// if (getValue(i) instanceof Double) {
// if (!Utils.eq((Double) getValue(i), (Double) pd.getValue(i)))
// return false;
// }
// else {
// if (!getValue(i).toString().equals(pd.getValue(i).toString()))
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * Compares the given point with this point.
// *
// * @param obj an object to be compared with this point
// * @return -1, 0, +1, in a manner consistent with equals
// */
// public int compareTo(Point<E> obj) {
// if (obj == null)
// return -1;
//
// if (dimensions() != obj.dimensions())
// return -1;
//
// for (int i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != obj.getValue(i).getClass())
// return -1;
//
// if (getValue(i) instanceof Double) {
// if (Utils.sm((Double) getValue(i), (Double) obj.getValue(i))) {
// return -1;
// } else if (Utils.gr((Double) getValue(i), (Double) obj.getValue(i))) {
// return 1;
// }
// } else {
// int r = getValue(i).toString().compareTo(obj.getValue(i).toString());
// if (r != 0) {
// return r;
// }
// }
// }
//
// return 0;
// }
//
// /**
// * returns a string representation of the Point.
// *
// * @return the point as string
// */
// public String toString() {
// String result;
// int i;
// double value;
//
// result = "";
//
// for (i = 0; i < dimensions(); i++) {
// if (i > 0)
// result += ", ";
//
// if (getValue(i) instanceof Double) {
// value = (Double) getValue(i);
// result += Utils.doubleToString(value, 6);
// }
// else {
// result += getValue(i).toString();
// }
// }
//
// return result;
// }
// }
| import weka.classifiers.Classifier;
import weka.core.Tag;
import weka.core.setupgenerator.Point;
import java.io.Serializable;
import java.util.HashMap; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Performance.java
* Copyright (C) 2008-2017 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.meta.multisearch;
/**
* A helper class for storing the performance of values in the parameter
* space. Can be sorted with the PerformanceComparator class.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 9515 $
* @see PerformanceComparator
*/
public class Performance
implements Serializable, Cloneable {
/** for serialization. */
private static final long serialVersionUID = -4374706475277588755L;
/** the values the filter/classifier were built with. */ | // Path: src/main/java/weka/core/setupgenerator/Point.java
// public class Point<E>
// implements Serializable, Cloneable, Comparable<Point<E>> {
//
// /** for serialization. */
// private static final long serialVersionUID = 1061326306122503731L;
//
// /** the values in the various dimensions. */
// protected Object[] m_Values;
//
// /**
// * Initializes the point with the given values.
// *
// * @param values the position in the various dimensions
// */
// public Point(E[] values) {
// m_Values = (E[]) values.clone();
// }
//
// /**
// * Returns a clone of itself.
// *
// * @return a clone of itself
// */
// public Object clone() {
// return new Point(m_Values.clone());
// }
//
// /**
// * Returns the number of dimensions this points uses.
// *
// * @return the number of dimensions
// */
// public int dimensions() {
// return m_Values.length;
// }
//
// /**
// * Returns the value in the specified dimension.
// *
// * @param dimension the dimension to get the value for
// * @return the value
// */
// public E getValue(int dimension) {
// return (E) m_Values[dimension];
// }
//
// /**
// * Determines whether or not two points are equal.
// *
// * @param obj an object to be compared with this PointDouble
// * @return true if the object to be compared has the same values;
// * false otherwise.
// */
// public boolean equals(Object obj) {
// Point<E> pd;
// int i;
//
// if (obj == null)
// return false;
//
// if (!(obj instanceof Point))
// return false;
//
// pd = (Point<E>) obj;
//
// if (dimensions() != pd.dimensions())
// return false;
//
// for (i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != pd.getValue(i).getClass())
// return false;
//
// if (getValue(i) instanceof Double) {
// if (!Utils.eq((Double) getValue(i), (Double) pd.getValue(i)))
// return false;
// }
// else {
// if (!getValue(i).toString().equals(pd.getValue(i).toString()))
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * Compares the given point with this point.
// *
// * @param obj an object to be compared with this point
// * @return -1, 0, +1, in a manner consistent with equals
// */
// public int compareTo(Point<E> obj) {
// if (obj == null)
// return -1;
//
// if (dimensions() != obj.dimensions())
// return -1;
//
// for (int i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != obj.getValue(i).getClass())
// return -1;
//
// if (getValue(i) instanceof Double) {
// if (Utils.sm((Double) getValue(i), (Double) obj.getValue(i))) {
// return -1;
// } else if (Utils.gr((Double) getValue(i), (Double) obj.getValue(i))) {
// return 1;
// }
// } else {
// int r = getValue(i).toString().compareTo(obj.getValue(i).toString());
// if (r != 0) {
// return r;
// }
// }
// }
//
// return 0;
// }
//
// /**
// * returns a string representation of the Point.
// *
// * @return the point as string
// */
// public String toString() {
// String result;
// int i;
// double value;
//
// result = "";
//
// for (i = 0; i < dimensions(); i++) {
// if (i > 0)
// result += ", ";
//
// if (getValue(i) instanceof Double) {
// value = (Double) getValue(i);
// result += Utils.doubleToString(value, 6);
// }
// else {
// result += getValue(i).toString();
// }
// }
//
// return result;
// }
// }
// Path: src/main/java/weka/classifiers/meta/multisearch/Performance.java
import weka.classifiers.Classifier;
import weka.core.Tag;
import weka.core.setupgenerator.Point;
import java.io.Serializable;
import java.util.HashMap;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Performance.java
* Copyright (C) 2008-2017 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.meta.multisearch;
/**
* A helper class for storing the performance of values in the parameter
* space. Can be sorted with the PerformanceComparator class.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 9515 $
* @see PerformanceComparator
*/
public class Performance
implements Serializable, Cloneable {
/** for serialization. */
private static final long serialVersionUID = -4374706475277588755L;
/** the values the filter/classifier were built with. */ | protected Point<Object> m_Values; |
fracpete/multisearch-weka-package | src/main/java/weka/classifiers/meta/multisearch/PerformanceCache.java | // Path: src/main/java/weka/core/setupgenerator/Point.java
// public class Point<E>
// implements Serializable, Cloneable, Comparable<Point<E>> {
//
// /** for serialization. */
// private static final long serialVersionUID = 1061326306122503731L;
//
// /** the values in the various dimensions. */
// protected Object[] m_Values;
//
// /**
// * Initializes the point with the given values.
// *
// * @param values the position in the various dimensions
// */
// public Point(E[] values) {
// m_Values = (E[]) values.clone();
// }
//
// /**
// * Returns a clone of itself.
// *
// * @return a clone of itself
// */
// public Object clone() {
// return new Point(m_Values.clone());
// }
//
// /**
// * Returns the number of dimensions this points uses.
// *
// * @return the number of dimensions
// */
// public int dimensions() {
// return m_Values.length;
// }
//
// /**
// * Returns the value in the specified dimension.
// *
// * @param dimension the dimension to get the value for
// * @return the value
// */
// public E getValue(int dimension) {
// return (E) m_Values[dimension];
// }
//
// /**
// * Determines whether or not two points are equal.
// *
// * @param obj an object to be compared with this PointDouble
// * @return true if the object to be compared has the same values;
// * false otherwise.
// */
// public boolean equals(Object obj) {
// Point<E> pd;
// int i;
//
// if (obj == null)
// return false;
//
// if (!(obj instanceof Point))
// return false;
//
// pd = (Point<E>) obj;
//
// if (dimensions() != pd.dimensions())
// return false;
//
// for (i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != pd.getValue(i).getClass())
// return false;
//
// if (getValue(i) instanceof Double) {
// if (!Utils.eq((Double) getValue(i), (Double) pd.getValue(i)))
// return false;
// }
// else {
// if (!getValue(i).toString().equals(pd.getValue(i).toString()))
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * Compares the given point with this point.
// *
// * @param obj an object to be compared with this point
// * @return -1, 0, +1, in a manner consistent with equals
// */
// public int compareTo(Point<E> obj) {
// if (obj == null)
// return -1;
//
// if (dimensions() != obj.dimensions())
// return -1;
//
// for (int i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != obj.getValue(i).getClass())
// return -1;
//
// if (getValue(i) instanceof Double) {
// if (Utils.sm((Double) getValue(i), (Double) obj.getValue(i))) {
// return -1;
// } else if (Utils.gr((Double) getValue(i), (Double) obj.getValue(i))) {
// return 1;
// }
// } else {
// int r = getValue(i).toString().compareTo(obj.getValue(i).toString());
// if (r != 0) {
// return r;
// }
// }
// }
//
// return 0;
// }
//
// /**
// * returns a string representation of the Point.
// *
// * @return the point as string
// */
// public String toString() {
// String result;
// int i;
// double value;
//
// result = "";
//
// for (i = 0; i < dimensions(); i++) {
// if (i > 0)
// result += ", ";
//
// if (getValue(i) instanceof Double) {
// value = (Double) getValue(i);
// result += Utils.doubleToString(value, 6);
// }
// else {
// result += getValue(i).toString();
// }
// }
//
// return result;
// }
// }
| import weka.core.setupgenerator.Point;
import java.io.Serializable;
import java.util.Hashtable; | /*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PerformanceCache.java
* Copyright (C) 2008-2010 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.meta.multisearch;
/**
* Represents a simple cache for performance objects.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 5156 $
*/
public class PerformanceCache
implements Serializable {
/** for serialization. */
private static final long serialVersionUID = 5838863230451530252L;
/** the cache for points in the space that got calculated. */
protected Hashtable<String,Performance> m_Cache = new Hashtable<String,Performance>();
/**
* returns the ID string for a cache item.
*
* @param cv the number of folds in the cross-validation
* @param values the point in the space
* @return the ID string
*/ | // Path: src/main/java/weka/core/setupgenerator/Point.java
// public class Point<E>
// implements Serializable, Cloneable, Comparable<Point<E>> {
//
// /** for serialization. */
// private static final long serialVersionUID = 1061326306122503731L;
//
// /** the values in the various dimensions. */
// protected Object[] m_Values;
//
// /**
// * Initializes the point with the given values.
// *
// * @param values the position in the various dimensions
// */
// public Point(E[] values) {
// m_Values = (E[]) values.clone();
// }
//
// /**
// * Returns a clone of itself.
// *
// * @return a clone of itself
// */
// public Object clone() {
// return new Point(m_Values.clone());
// }
//
// /**
// * Returns the number of dimensions this points uses.
// *
// * @return the number of dimensions
// */
// public int dimensions() {
// return m_Values.length;
// }
//
// /**
// * Returns the value in the specified dimension.
// *
// * @param dimension the dimension to get the value for
// * @return the value
// */
// public E getValue(int dimension) {
// return (E) m_Values[dimension];
// }
//
// /**
// * Determines whether or not two points are equal.
// *
// * @param obj an object to be compared with this PointDouble
// * @return true if the object to be compared has the same values;
// * false otherwise.
// */
// public boolean equals(Object obj) {
// Point<E> pd;
// int i;
//
// if (obj == null)
// return false;
//
// if (!(obj instanceof Point))
// return false;
//
// pd = (Point<E>) obj;
//
// if (dimensions() != pd.dimensions())
// return false;
//
// for (i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != pd.getValue(i).getClass())
// return false;
//
// if (getValue(i) instanceof Double) {
// if (!Utils.eq((Double) getValue(i), (Double) pd.getValue(i)))
// return false;
// }
// else {
// if (!getValue(i).toString().equals(pd.getValue(i).toString()))
// return false;
// }
// }
//
// return true;
// }
//
// /**
// * Compares the given point with this point.
// *
// * @param obj an object to be compared with this point
// * @return -1, 0, +1, in a manner consistent with equals
// */
// public int compareTo(Point<E> obj) {
// if (obj == null)
// return -1;
//
// if (dimensions() != obj.dimensions())
// return -1;
//
// for (int i = 0; i < dimensions(); i++) {
// if (getValue(i).getClass() != obj.getValue(i).getClass())
// return -1;
//
// if (getValue(i) instanceof Double) {
// if (Utils.sm((Double) getValue(i), (Double) obj.getValue(i))) {
// return -1;
// } else if (Utils.gr((Double) getValue(i), (Double) obj.getValue(i))) {
// return 1;
// }
// } else {
// int r = getValue(i).toString().compareTo(obj.getValue(i).toString());
// if (r != 0) {
// return r;
// }
// }
// }
//
// return 0;
// }
//
// /**
// * returns a string representation of the Point.
// *
// * @return the point as string
// */
// public String toString() {
// String result;
// int i;
// double value;
//
// result = "";
//
// for (i = 0; i < dimensions(); i++) {
// if (i > 0)
// result += ", ";
//
// if (getValue(i) instanceof Double) {
// value = (Double) getValue(i);
// result += Utils.doubleToString(value, 6);
// }
// else {
// result += getValue(i).toString();
// }
// }
//
// return result;
// }
// }
// Path: src/main/java/weka/classifiers/meta/multisearch/PerformanceCache.java
import weka.core.setupgenerator.Point;
import java.io.Serializable;
import java.util.Hashtable;
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PerformanceCache.java
* Copyright (C) 2008-2010 University of Waikato, Hamilton, New Zealand
*/
package weka.classifiers.meta.multisearch;
/**
* Represents a simple cache for performance objects.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 5156 $
*/
public class PerformanceCache
implements Serializable {
/** for serialization. */
private static final long serialVersionUID = 5838863230451530252L;
/** the cache for points in the space that got calculated. */
protected Hashtable<String,Performance> m_Cache = new Hashtable<String,Performance>();
/**
* returns the ID string for a cache item.
*
* @param cv the number of folds in the cross-validation
* @param values the point in the space
* @return the ID string
*/ | protected String getID(int cv, Point<Object> values) { |
sigram/pcl-parser | src/java/org/getopt/pcl5/PCL5Interpreter/IPrint.java | // Path: src/java/org/getopt/pcl5/IPrinterState.java
// public interface IPrinterState {
// /**
// * Returns current font used by printer. <b>Do not cache this value.<b>
// *
// * @return current Font class
// */
// Font getFont();
//
// /**
// * Returns current font attributes
// *
// * @return current font attribute
// */
// Map getFontAttributes();
//
// /**
// * Return current color used by printer <b>Do not cache this value.<b>
// *
// * @return Current color
// */
// Color getCurrentColor();
//
// /**
// * Return true is printer has selected condensed font
// *
// * @return condensed printer state
// */
// boolean isCondensed();
//
// int getUnderliningMode();
// }
| import org.getopt.pcl5.IPrinterState;
import java.awt.image.BufferedImage;
| /*
* Created on 2004-09-12
*
*/
package org.getopt.pcl5.PCL5Interpreter;
/**
* Callback interface, called when something to print happens Should be
* implemented by rasterizer
*
* Every parameter is scaled in 72 DPI
*
*/
public interface IPrint {
/**
* Called when new page
*
*/
void newPage();
/**
* Called when page size changed
*
* @param w
* New width of page, in 72 DPI
* @param h
* New height of page, in 72 DPI
*/
void pageSize(float w, float h);
/**
* Called after every margins change and after each new page
*
* @param top
* top margin, in 72 DPI
* @param bottom
* bottom margin, in 72 DPI
* @param left
* left margin, in 72 DPI
* @param right
* right margin, in 72 DPI
*/
void newMargins(float top, float bottom, float left, float right);
/**
* Called on beginning of processing, before any other method from this
* interface is called
*
*/
void processingStart();
/**
* Called on end of processing, after last method from this interface was
* called
*
*/
void processingEnd();
/**
* Called when text should be printed, text is limited to end of line (CR) or
* to change in pronter state (ie font)
*
* @param x
* Print location X in 72 DPI
* @param y
* Print location Y in 72 DPI
* @param w
* Width of text (bound box) in 72 DPI
* @param h
* Height of text in (bound box) 72 DPI
* @param text
* Text to print
* @param state
* Interface to query state of printer
*/
void printText(float x, float y, float w, float h, String text,
| // Path: src/java/org/getopt/pcl5/IPrinterState.java
// public interface IPrinterState {
// /**
// * Returns current font used by printer. <b>Do not cache this value.<b>
// *
// * @return current Font class
// */
// Font getFont();
//
// /**
// * Returns current font attributes
// *
// * @return current font attribute
// */
// Map getFontAttributes();
//
// /**
// * Return current color used by printer <b>Do not cache this value.<b>
// *
// * @return Current color
// */
// Color getCurrentColor();
//
// /**
// * Return true is printer has selected condensed font
// *
// * @return condensed printer state
// */
// boolean isCondensed();
//
// int getUnderliningMode();
// }
// Path: src/java/org/getopt/pcl5/PCL5Interpreter/IPrint.java
import org.getopt.pcl5.IPrinterState;
import java.awt.image.BufferedImage;
/*
* Created on 2004-09-12
*
*/
package org.getopt.pcl5.PCL5Interpreter;
/**
* Callback interface, called when something to print happens Should be
* implemented by rasterizer
*
* Every parameter is scaled in 72 DPI
*
*/
public interface IPrint {
/**
* Called when new page
*
*/
void newPage();
/**
* Called when page size changed
*
* @param w
* New width of page, in 72 DPI
* @param h
* New height of page, in 72 DPI
*/
void pageSize(float w, float h);
/**
* Called after every margins change and after each new page
*
* @param top
* top margin, in 72 DPI
* @param bottom
* bottom margin, in 72 DPI
* @param left
* left margin, in 72 DPI
* @param right
* right margin, in 72 DPI
*/
void newMargins(float top, float bottom, float left, float right);
/**
* Called on beginning of processing, before any other method from this
* interface is called
*
*/
void processingStart();
/**
* Called on end of processing, after last method from this interface was
* called
*
*/
void processingEnd();
/**
* Called when text should be printed, text is limited to end of line (CR) or
* to change in pronter state (ie font)
*
* @param x
* Print location X in 72 DPI
* @param y
* Print location Y in 72 DPI
* @param w
* Width of text (bound box) in 72 DPI
* @param h
* Height of text in (bound box) 72 DPI
* @param text
* Text to print
* @param state
* Interface to query state of printer
*/
void printText(float x, float y, float w, float h, String text,
| IPrinterState state);
|
sigram/pcl-parser | src/gui/TextRasterizer.java | // Path: src/java/org/getopt/pcl5/IPrint.java
// public interface IPrint {
// /**
// * Called when new page
// *
// */
// void newPage();
//
// /**
// * Called when page size changed
// *
// * @param w
// * New width of page, in 72 DPI
// * @param h
// * New height of page, in 72 DPI
// */
// void pageSize(float w, float h);
//
// /**
// * Called after every margins change and after each new page
// *
// * @param top
// * top margin, in 72 DPI
// * @param bottom
// * bottom margin, in 72 DPI
// * @param left
// * left margin, in 72 DPI
// * @param right
// * right margin, in 72 DPI
// */
// void newMargins(float top, float bottom, float left, float right);
//
// /**
// * Called on beginning of processing, before any other method from this
// * interface is called
// *
// */
// void processingStart();
//
// /**
// * Called on end of processing, after last method from this interface was
// * called
// *
// */
// void processingEnd();
//
// /**
// * Called when text should be printed, text is limited to end of line (CR) or
// * to change in pronter state (ie font)
// *
// * @param x
// * Print location X in 72 DPI
// * @param y
// * Print location Y in 72 DPI
// * @param w
// * Width of text (bound box) in 72 DPI
// * @param h
// * Height of text in (bound box) 72 DPI
// * @param text
// * Text to print
// * @param state
// * Interface to query state of printer
// */
// void printText(float x, float y, float w, float h, String text,
// int[] kerning, IPrinterState state);
//
// /**
// * Called when bitmap should be printed, bitmap is always complete method is
// * called when graphics mode is terminated
// *
// * @param x
// * X location of image in 72 DPI
// * @param y
// * Y location of image in 72 DPI
// * @param w
// * Width of bitmap in (bound box) 72 DPI
// * @param h
// * Height of bitmap in (bound box) 72 DPI
// * @param image
// * Image for output
// * @param state
// * Interface to query state of printer
// */
// void printBitmap(float x, float y, float w, float h, BufferedImage image,
// IPrinterState state);
//
// /**
// * Called on condition like command without meaning for interpreter like BEL
// *
// * @param command
// * class
// * @param message
// * command name
// */
// void trace(Object command, String message);
//
// /**
// * Called when command parameters are incorrect ie out of range
// *
// * @param command
// * class that detected problem
// * @param message
// * kind of problem
// */
// void assertCondition(Object command, String message);
//
// /**
// * Called when found command that shouldn't be implemented ie CAN Cancel line
// *
// * @param command
// * class that detected problem
// * @param message
// * kind of problem
// */
// void notImplemented(Object command, String message);
// }
//
// Path: src/java/org/getopt/pcl5/IPrinterState.java
// public interface IPrinterState {
// /**
// * Returns current font used by printer. <b>Do not cache this value.<b>
// *
// * @return current Font class
// */
// Font getFont();
//
// /**
// * Returns current font attributes
// *
// * @return current font attribute
// */
// Map getFontAttributes();
//
// /**
// * Return current color used by printer <b>Do not cache this value.<b>
// *
// * @return Current color
// */
// Color getCurrentColor();
//
// /**
// * Return true is printer has selected condensed font
// *
// * @return condensed printer state
// */
// boolean isCondensed();
//
// int getUnderliningMode();
// }
| import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import org.getopt.pcl5.IPrint;
import org.getopt.pcl5.IPrinterState;
| /*
* Created on 2004-09-12
*
*/
/**
* @author Piotrm
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TextRasterizer implements IPrint
{
private PrintWriter writer;
public TextRasterizer(PrintWriter wr)
{
writer = wr;
}
public void pageSize(float w, float h)
{
writer.println("New page size: [" + w + ", " + h + "]");
}
| // Path: src/java/org/getopt/pcl5/IPrint.java
// public interface IPrint {
// /**
// * Called when new page
// *
// */
// void newPage();
//
// /**
// * Called when page size changed
// *
// * @param w
// * New width of page, in 72 DPI
// * @param h
// * New height of page, in 72 DPI
// */
// void pageSize(float w, float h);
//
// /**
// * Called after every margins change and after each new page
// *
// * @param top
// * top margin, in 72 DPI
// * @param bottom
// * bottom margin, in 72 DPI
// * @param left
// * left margin, in 72 DPI
// * @param right
// * right margin, in 72 DPI
// */
// void newMargins(float top, float bottom, float left, float right);
//
// /**
// * Called on beginning of processing, before any other method from this
// * interface is called
// *
// */
// void processingStart();
//
// /**
// * Called on end of processing, after last method from this interface was
// * called
// *
// */
// void processingEnd();
//
// /**
// * Called when text should be printed, text is limited to end of line (CR) or
// * to change in pronter state (ie font)
// *
// * @param x
// * Print location X in 72 DPI
// * @param y
// * Print location Y in 72 DPI
// * @param w
// * Width of text (bound box) in 72 DPI
// * @param h
// * Height of text in (bound box) 72 DPI
// * @param text
// * Text to print
// * @param state
// * Interface to query state of printer
// */
// void printText(float x, float y, float w, float h, String text,
// int[] kerning, IPrinterState state);
//
// /**
// * Called when bitmap should be printed, bitmap is always complete method is
// * called when graphics mode is terminated
// *
// * @param x
// * X location of image in 72 DPI
// * @param y
// * Y location of image in 72 DPI
// * @param w
// * Width of bitmap in (bound box) 72 DPI
// * @param h
// * Height of bitmap in (bound box) 72 DPI
// * @param image
// * Image for output
// * @param state
// * Interface to query state of printer
// */
// void printBitmap(float x, float y, float w, float h, BufferedImage image,
// IPrinterState state);
//
// /**
// * Called on condition like command without meaning for interpreter like BEL
// *
// * @param command
// * class
// * @param message
// * command name
// */
// void trace(Object command, String message);
//
// /**
// * Called when command parameters are incorrect ie out of range
// *
// * @param command
// * class that detected problem
// * @param message
// * kind of problem
// */
// void assertCondition(Object command, String message);
//
// /**
// * Called when found command that shouldn't be implemented ie CAN Cancel line
// *
// * @param command
// * class that detected problem
// * @param message
// * kind of problem
// */
// void notImplemented(Object command, String message);
// }
//
// Path: src/java/org/getopt/pcl5/IPrinterState.java
// public interface IPrinterState {
// /**
// * Returns current font used by printer. <b>Do not cache this value.<b>
// *
// * @return current Font class
// */
// Font getFont();
//
// /**
// * Returns current font attributes
// *
// * @return current font attribute
// */
// Map getFontAttributes();
//
// /**
// * Return current color used by printer <b>Do not cache this value.<b>
// *
// * @return Current color
// */
// Color getCurrentColor();
//
// /**
// * Return true is printer has selected condensed font
// *
// * @return condensed printer state
// */
// boolean isCondensed();
//
// int getUnderliningMode();
// }
// Path: src/gui/TextRasterizer.java
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import org.getopt.pcl5.IPrint;
import org.getopt.pcl5.IPrinterState;
/*
* Created on 2004-09-12
*
*/
/**
* @author Piotrm
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class TextRasterizer implements IPrint
{
private PrintWriter writer;
public TextRasterizer(PrintWriter wr)
{
writer = wr;
}
public void pageSize(float w, float h)
{
writer.println("New page size: [" + w + ", " + h + "]");
}
| public void printText(float x, float y, float w, float h, String text, int[] kerning, IPrinterState state)
|
Noahs-ARK/semafor | src/main/java/edu/cmu/cs/lti/ark/fn/parsing/TrainingMain.java | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
| import java.util.ArrayList;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import java.io.IOException; | /*******************************************************************************
* Copyright (c) 2011 Dipanjan Das
* Language Technologies Institute,
* Carnegie Mellon University,
* All Rights Reserved.
*
* TrainingMain.java is part of SEMAFOR 2.0.
*
* SEMAFOR 2.0 is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SEMAFOR 2.0 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with SEMAFOR 2.0. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.cmu.cs.lti.ark.fn.parsing;
public class TrainingMain
{
public static void main(String[] args) throws IOException {
FNModelOptions opts = new FNModelOptions(args);
String modelFile = opts.modelFile.get();
String alphabetFile = opts.alphabetFile.get();
String frameFeaturesCacheFile = opts.frameFeaturesCacheFile.get();
String frFile = opts.trainFrameFile.get();
String lexiconObj = opts.lexiconDir.get();
int totalpasses = opts.totalPasses.get();
int batchsize = opts.batchSize.get();
String reg = opts.reg.get();
double lambda = opts.lambda.get();
String binaryFactorPresent = opts.binaryOverlapConstraint.get(); | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
// Path: src/main/java/edu/cmu/cs/lti/ark/fn/parsing/TrainingMain.java
import java.util.ArrayList;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import java.io.IOException;
/*******************************************************************************
* Copyright (c) 2011 Dipanjan Das
* Language Technologies Institute,
* Carnegie Mellon University,
* All Rights Reserved.
*
* TrainingMain.java is part of SEMAFOR 2.0.
*
* SEMAFOR 2.0 is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SEMAFOR 2.0 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with SEMAFOR 2.0. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package edu.cmu.cs.lti.ark.fn.parsing;
public class TrainingMain
{
public static void main(String[] args) throws IOException {
FNModelOptions opts = new FNModelOptions(args);
String modelFile = opts.modelFile.get();
String alphabetFile = opts.alphabetFile.get();
String frameFeaturesCacheFile = opts.frameFeaturesCacheFile.get();
String frFile = opts.trainFrameFile.get();
String lexiconObj = opts.lexiconDir.get();
int totalpasses = opts.totalPasses.get();
int batchsize = opts.batchSize.get();
String reg = opts.reg.get();
double lambda = opts.lambda.get();
String binaryFactorPresent = opts.binaryOverlapConstraint.get(); | ArrayList<FrameFeatures> list = (ArrayList<FrameFeatures>)SerializedObjects.readSerializedObject(frameFeaturesCacheFile); |
Noahs-ARK/semafor | src/main/java/edu/cmu/cs/lti/ark/fn/identification/FrameIdentificationGoldTargets.java | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
| import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import edu.cmu.cs.lti.ark.fn.data.prep.ParsePreparation;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import edu.cmu.cs.lti.ark.util.ds.Pair;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectDoubleHashMap;
import java.io.BufferedReader; | {
BufferedReader inParses = new BufferedReader(new FileReader(options.testParseFile.get()));
BufferedReader inOrgSentences = new BufferedReader(new FileReader(options.testTokenizedFile.get()));
String line = null;
int dummy = 0;
while((line=inParses.readLine())!=null)
{
String line2 = inOrgSentences.readLine().trim();
if(count<start) // skip sentences prior to the specified range
{
count++;
continue;
}
parses.add(line.trim());
orgSentenceLines.add(line2);
tokenNums.add(""+dummy); // ?? I think 'dummy' is just the offset of the sentence relative to options.startIndex
originalIndices.add(""+count);
if(count==(end-1)) // skip sentences after the specified range
break;
count++;
dummy++;
}
inParses.close();
inOrgSentences.close();
}
catch(Exception e)
{
e.printStackTrace();
} | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
// Path: src/main/java/edu/cmu/cs/lti/ark/fn/identification/FrameIdentificationGoldTargets.java
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import edu.cmu.cs.lti.ark.fn.data.prep.ParsePreparation;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import edu.cmu.cs.lti.ark.util.ds.Pair;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import gnu.trove.TObjectDoubleHashMap;
import java.io.BufferedReader;
{
BufferedReader inParses = new BufferedReader(new FileReader(options.testParseFile.get()));
BufferedReader inOrgSentences = new BufferedReader(new FileReader(options.testTokenizedFile.get()));
String line = null;
int dummy = 0;
while((line=inParses.readLine())!=null)
{
String line2 = inOrgSentences.readLine().trim();
if(count<start) // skip sentences prior to the specified range
{
count++;
continue;
}
parses.add(line.trim());
orgSentenceLines.add(line2);
tokenNums.add(""+dummy); // ?? I think 'dummy' is just the offset of the sentence relative to options.startIndex
originalIndices.add(""+count);
if(count==(end-1)) // skip sentences after the specified range
break;
count++;
dummy++;
}
inParses.close();
inOrgSentences.close();
}
catch(Exception e)
{
e.printStackTrace();
} | RequiredDataForFrameIdentification r = SerializedObjects.readObject(options.fnIdReqDataFile.get()); |
Noahs-ARK/semafor | src/main/java/edu/cmu/cs/lti/ark/fn/identification/training/TrainBatch.java | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
| import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.primitives.Ints;
import edu.cmu.cs.lti.ark.fn.optimization.Lbfgs;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.fn.utils.ThreadPool;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import edu.cmu.cs.lti.ark.util.ds.Pair;
import gnu.trove.TIntDoubleHashMap;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import static edu.cmu.cs.lti.ark.util.IntRanges.xrange;
import static edu.cmu.cs.lti.ark.util.Math2.sum; | }
/** Adds the sparse vector rhs to the dense vector lhs **/
private static void plusEquals(double[] lhs, TIntDoubleHashMap rhs) {
for (int i : rhs.keys()) {
lhs[i] += rhs.get(i);
}
}
/** Adds the dense vector rhs to the dense vector lhs **/
private static void plusEquals(double[] lhs, double[] rhs) {
for (int i = 0; i < lhs.length; i++) {
lhs[i] += rhs[i];
}
}
/** Multiplies the dense vector <code>vector</code> by the scalar <code>scalar</code> **/
private static void timesEquals(double[] vector, double scalar) {
for (int i = 0; i < vector.length; i++) {
vector[i] *= scalar;
}
}
/**
* Get features for every frame for given target
*
* @param targetIdx the target to get features for
* @return map from feature index to feature value (for each frame)
*/
private FeaturesAndCost[] getFeaturesForTarget(int targetIdx) throws Exception { | // Path: src/main/java/edu/cmu/cs/lti/ark/util/SerializedObjects.java
// public class SerializedObjects {
// public static void writeSerializedObject(Object object, String outFile) {
// ObjectOutputStream output = null;
// try {
// output = getObjectOutputStream(outFile);
// output.writeObject(object);
// } catch(IOException ex){
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(output);
// }
// }
//
// public static Object readSerializedObject(String inputFile) {
// ObjectInputStream input = null;
// Object recoveredObject = null;
// try{
// input = getObjectInputStream(inputFile);
// recoveredObject = input.readObject();
// } catch(Exception ex) {
// // TODO: NONONONONO! stop swallowing errors!
// ex.printStackTrace();
// } finally{
// closeQuietly(input);
// }
// return recoveredObject;
// }
//
// public static <T> T readObject(final String inputFile) throws IOException, ClassNotFoundException {
// return SerializedObjects.<T>readObject(new InputSupplier<ObjectInputStream>() {
// @Override public ObjectInputStream getInput() throws IOException {
// return getObjectInputStream(inputFile);
// } });
// }
//
// @SuppressWarnings("unchecked")
// public static <T> T readObject(InputSupplier<ObjectInputStream> inputSupplier)
// throws IOException, ClassNotFoundException {
// final ObjectInputStream input = inputSupplier.getInput();
// try{
// return (T) input.readObject();
// } finally{
// closeQuietly(input);
// }
// }
//
// private static ObjectInputStream getObjectInputStream(String inputFile) throws IOException {
// return new ObjectInputStream(new BufferedInputStream(getInputStream(inputFile)));
// }
//
// public static InputStream getInputStream(String inputFile) throws IOException {
// if(inputFile.endsWith(".gz")) {
// return new GZIPInputStream(new FileInputStream(inputFile));
// } else {
// return new FileInputStream(inputFile);
// }
// }
//
// private static ObjectOutputStream getObjectOutputStream(String outFile) throws IOException {
// OutputStream file = getOutputStream(outFile);
// return new ObjectOutputStream(new BufferedOutputStream(file));
// }
//
// public static OutputStream getOutputStream(String outFile) throws IOException {
// if(outFile.endsWith(".gz")) {
// return new GZIPOutputStream(new FileOutputStream(outFile));
// } else {
// return new FileOutputStream(outFile);
// }
// }
// }
// Path: src/main/java/edu/cmu/cs/lti/ark/fn/identification/training/TrainBatch.java
import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.google.common.primitives.Ints;
import edu.cmu.cs.lti.ark.fn.optimization.Lbfgs;
import edu.cmu.cs.lti.ark.fn.utils.FNModelOptions;
import edu.cmu.cs.lti.ark.fn.utils.ThreadPool;
import edu.cmu.cs.lti.ark.util.SerializedObjects;
import edu.cmu.cs.lti.ark.util.ds.Pair;
import gnu.trove.TIntDoubleHashMap;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import static edu.cmu.cs.lti.ark.util.IntRanges.xrange;
import static edu.cmu.cs.lti.ark.util.Math2.sum;
}
/** Adds the sparse vector rhs to the dense vector lhs **/
private static void plusEquals(double[] lhs, TIntDoubleHashMap rhs) {
for (int i : rhs.keys()) {
lhs[i] += rhs.get(i);
}
}
/** Adds the dense vector rhs to the dense vector lhs **/
private static void plusEquals(double[] lhs, double[] rhs) {
for (int i = 0; i < lhs.length; i++) {
lhs[i] += rhs[i];
}
}
/** Multiplies the dense vector <code>vector</code> by the scalar <code>scalar</code> **/
private static void timesEquals(double[] vector, double scalar) {
for (int i = 0; i < vector.length; i++) {
vector[i] *= scalar;
}
}
/**
* Get features for every frame for given target
*
* @param targetIdx the target to get features for
* @return map from feature index to feature value (for each frame)
*/
private FeaturesAndCost[] getFeaturesForTarget(int targetIdx) throws Exception { | return SerializedObjects.readObject(eventFiles.get(targetIdx)); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
| import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date; | package com.acmeair.morphia.services;
@Service
class CustomerServiceImpl extends CustomerServiceSupport {
// private final static Logger logger = Logger.getLogger(CustomerService.class.getName());
@Autowired | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java
import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
package com.acmeair.morphia.services;
@Service
class CustomerServiceImpl extends CustomerServiceSupport {
// private final static Logger logger = Logger.getLogger(CustomerService.class.getName());
@Autowired | private CustomerRepository customerRepository; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
| import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date; | package com.acmeair.morphia.services;
@Service
class CustomerServiceImpl extends CustomerServiceSupport {
// private final static Logger logger = Logger.getLogger(CustomerService.class.getName());
@Autowired
private CustomerRepository customerRepository;
@Autowired | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java
import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
package com.acmeair.morphia.services;
@Service
class CustomerServiceImpl extends CustomerServiceSupport {
// private final static Logger logger = Logger.getLogger(CustomerService.class.getName());
@Autowired
private CustomerRepository customerRepository;
@Autowired | private CustomerSessionRepository sessionRepository; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
| import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date; | }
public Customer createCustomer(String username, String password,
MemberShipStatus status, int total_miles, int miles_ytd,
String phoneNumber, PhoneType phoneNumberType,
CustomerAddressImpl address) {
CustomerImpl customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType);
customerRepository.save(customer);
return customer;
}
public CustomerAddressImpl createAddress (String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode){
return new CustomerAddressImpl(streetAddress1, streetAddress2,
city, stateProvince, country, postalCode);
}
@Override
public Customer updateCustomer(Customer customer) {
customerRepository.save((CustomerImpl) customer);
return customer;
}
@Override
protected Customer getCustomer(String username) {
return customerRepository.findOne(username);
}
@Override | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CustomerServiceImpl.java
import com.acmeair.entities.Customer;
import com.acmeair.entities.Customer.MemberShipStatus;
import com.acmeair.entities.Customer.PhoneType;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.CustomerServiceSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
}
public Customer createCustomer(String username, String password,
MemberShipStatus status, int total_miles, int miles_ytd,
String phoneNumber, PhoneType phoneNumberType,
CustomerAddressImpl address) {
CustomerImpl customer = new CustomerImpl(username, password, status, total_miles, miles_ytd, address, phoneNumber, phoneNumberType);
customerRepository.save(customer);
return customer;
}
public CustomerAddressImpl createAddress (String streetAddress1, String streetAddress2,
String city, String stateProvince, String country, String postalCode){
return new CustomerAddressImpl(streetAddress1, streetAddress2,
city, stateProvince, country, postalCode);
}
@Override
public Customer updateCustomer(Customer customer) {
customerRepository.save((CustomerImpl) customer);
return customer;
}
@Override
protected Customer getCustomer(String username) {
return customerRepository.findOne(username);
}
@Override | protected CustomerSession getSession(String sessionid){ |
WillemJiang/acmeair | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
| import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date; | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.morphia.entities;
@Document(collection = "flight")
@Entity(name = "flight") | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
// Path: acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.morphia.entities;
@Document(collection = "flight")
@Entity(name = "flight") | public class FlightImpl implements Flight, Serializable{ |
WillemJiang/acmeair | acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
| import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date; | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.morphia.entities;
@Document(collection = "flight")
@Entity(name = "flight")
public class FlightImpl implements Flight, Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
private String _id;
private String flightSegmentId;
private Date scheduledDepartureTime;
private Date scheduledArrivalTime;
private BigDecimal firstClassBaseCost;
private BigDecimal economyClassBaseCost;
private int numFirstClassSeats;
private int numEconomyClassSeats;
private String airplaneTypeId;
@ManyToOne(targetEntity = FlightSegmentImpl.class, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_flight_segment_id") | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
// Path: acmeair-services-morphia/src/main/java/com/acmeair/morphia/entities/FlightImpl.java
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.morphia.entities;
@Document(collection = "flight")
@Entity(name = "flight")
public class FlightImpl implements Flight, Serializable{
private static final long serialVersionUID = 1L;
@Id
@Column(name = "id")
private String _id;
private String flightSegmentId;
private Date scheduledDepartureTime;
private Date scheduledArrivalTime;
private BigDecimal firstClassBaseCost;
private BigDecimal economyClassBaseCost;
private int numFirstClassSeats;
private int numEconomyClassSeats;
private String airplaneTypeId;
@ManyToOne(targetEntity = FlightSegmentImpl.class, cascade = CascadeType.ALL)
@JoinColumn(name = "fk_flight_segment_id") | private FlightSegment flightSegment; |
WillemJiang/acmeair | acmeair-booking-service/src/test/java/com/acmeair/booking/templates/BookingDtoTemplateLoader.java | // Path: acmeair-booking-service/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
// public class BookingReceiptInfo {
//
// private String departBookingId;
//
// private String returnBookingId;
//
// private boolean oneWay;
//
// public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) {
// this.departBookingId = departBookingId;
// this.returnBookingId = returnBookingId;
// this.oneWay = oneWay;
// }
//
// public BookingReceiptInfo() {
// }
//
// public String getDepartBookingId() {
// return departBookingId;
// }
//
// public void setDepartBookingId(String departBookingId) {
// this.departBookingId = departBookingId;
// }
//
// public String getReturnBookingId() {
// return returnBookingId;
// }
//
// public void setReturnBookingId(String returnBookingId) {
// this.returnBookingId = returnBookingId;
// }
//
// public boolean isOneWay() {
// return oneWay;
// }
//
// public void setOneWay(boolean oneWay) {
// this.oneWay = oneWay;
// }
//
// @Override
// public String toString() {
// return "BookingInfo [departBookingId=" + departBookingId
// + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay
// + "]";
// }
// }
| import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.Rule;
import br.com.six2six.fixturefactory.loader.TemplateLoader;
import com.acmeair.web.dto.BookingReceiptInfo;
import static com.seanyinx.github.unit.scaffolding.Randomness.nextId;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify; | package com.acmeair.booking.templates;
public class BookingDtoTemplateLoader implements TemplateLoader {
@Override
public void load() { | // Path: acmeair-booking-service/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
// public class BookingReceiptInfo {
//
// private String departBookingId;
//
// private String returnBookingId;
//
// private boolean oneWay;
//
// public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) {
// this.departBookingId = departBookingId;
// this.returnBookingId = returnBookingId;
// this.oneWay = oneWay;
// }
//
// public BookingReceiptInfo() {
// }
//
// public String getDepartBookingId() {
// return departBookingId;
// }
//
// public void setDepartBookingId(String departBookingId) {
// this.departBookingId = departBookingId;
// }
//
// public String getReturnBookingId() {
// return returnBookingId;
// }
//
// public void setReturnBookingId(String returnBookingId) {
// this.returnBookingId = returnBookingId;
// }
//
// public boolean isOneWay() {
// return oneWay;
// }
//
// public void setOneWay(boolean oneWay) {
// this.oneWay = oneWay;
// }
//
// @Override
// public String toString() {
// return "BookingInfo [departBookingId=" + departBookingId
// + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay
// + "]";
// }
// }
// Path: acmeair-booking-service/src/test/java/com/acmeair/booking/templates/BookingDtoTemplateLoader.java
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.Rule;
import br.com.six2six.fixturefactory.loader.TemplateLoader;
import com.acmeair.web.dto.BookingReceiptInfo;
import static com.seanyinx.github.unit.scaffolding.Randomness.nextId;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
package com.acmeair.booking.templates;
public class BookingDtoTemplateLoader implements TemplateLoader {
@Override
public void load() { | Fixture.of(BookingReceiptInfo.class).addTemplate("valid", new Rule() {{ |
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/web/BookingsREST.java | // Path: acmeair-booking-service/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
// public class BookingReceiptInfo {
//
// private String departBookingId;
//
// private String returnBookingId;
//
// private boolean oneWay;
//
// public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) {
// this.departBookingId = departBookingId;
// this.returnBookingId = returnBookingId;
// this.oneWay = oneWay;
// }
//
// public BookingReceiptInfo() {
// }
//
// public String getDepartBookingId() {
// return departBookingId;
// }
//
// public void setDepartBookingId(String departBookingId) {
// this.departBookingId = departBookingId;
// }
//
// public String getReturnBookingId() {
// return returnBookingId;
// }
//
// public void setReturnBookingId(String returnBookingId) {
// this.returnBookingId = returnBookingId;
// }
//
// public boolean isOneWay() {
// return oneWay;
// }
//
// public void setOneWay(boolean oneWay) {
// this.oneWay = oneWay;
// }
//
// @Override
// public String toString() {
// return "BookingInfo [departBookingId=" + departBookingId
// + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay
// + "]";
// }
// }
| import java.util.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import com.acmeair.entities.Booking;
import com.acmeair.service.BookingService;
import com.acmeair.web.dto.BookingInfo;
import com.acmeair.web.dto.BookingReceiptInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired; | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "bookings")
@Path("/api/bookings")
@Api(value = "Booking Service ", produces = MediaType.APPLICATION_JSON)
public class BookingsREST {
@Autowired
private BookingService bs;
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Path("/bookflights")
@Produces(MediaType.APPLICATION_JSON) | // Path: acmeair-booking-service/src/main/java/com/acmeair/web/dto/BookingReceiptInfo.java
// public class BookingReceiptInfo {
//
// private String departBookingId;
//
// private String returnBookingId;
//
// private boolean oneWay;
//
// public BookingReceiptInfo(String departBookingId, String returnBookingId, boolean oneWay) {
// this.departBookingId = departBookingId;
// this.returnBookingId = returnBookingId;
// this.oneWay = oneWay;
// }
//
// public BookingReceiptInfo() {
// }
//
// public String getDepartBookingId() {
// return departBookingId;
// }
//
// public void setDepartBookingId(String departBookingId) {
// this.departBookingId = departBookingId;
// }
//
// public String getReturnBookingId() {
// return returnBookingId;
// }
//
// public void setReturnBookingId(String returnBookingId) {
// this.returnBookingId = returnBookingId;
// }
//
// public boolean isOneWay() {
// return oneWay;
// }
//
// public void setOneWay(boolean oneWay) {
// this.oneWay = oneWay;
// }
//
// @Override
// public String toString() {
// return "BookingInfo [departBookingId=" + departBookingId
// + ", returnBookingId=" + returnBookingId + ", oneWay=" + oneWay
// + "]";
// }
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/web/BookingsREST.java
import java.util.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import com.acmeair.entities.Booking;
import com.acmeair.service.BookingService;
import com.acmeair.web.dto.BookingInfo;
import com.acmeair.web.dto.BookingReceiptInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "bookings")
@Path("/api/bookings")
@Api(value = "Booking Service ", produces = MediaType.APPLICATION_JSON)
public class BookingsREST {
@Autowired
private BookingService bs;
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Path("/bookflights")
@Produces(MediaType.APPLICATION_JSON) | public BookingReceiptInfo bookFlights( |
WillemJiang/acmeair | acmeair-booking-service/src/test/java/com/acmeair/hystrix/UserCommandFetchingCustomerFailedTest.java | // Path: acmeair-services/src/main/java/com/acmeair/service/UserService.java
// public interface UserService {
// CustomerInfo getCustomerInfo(String customerId);
// }
| import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.service.UserService;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.NoSuchElementException;
import static com.seanyinx.github.unit.scaffolding.AssertUtils.expectFailing;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; | package com.acmeair.hystrix;
public class UserCommandFetchingCustomerFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
| // Path: acmeair-services/src/main/java/com/acmeair/service/UserService.java
// public interface UserService {
// CustomerInfo getCustomerInfo(String customerId);
// }
// Path: acmeair-booking-service/src/test/java/com/acmeair/hystrix/UserCommandFetchingCustomerFailedTest.java
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.service.UserService;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import java.io.IOException;
import java.util.NoSuchElementException;
import static com.seanyinx.github.unit.scaffolding.AssertUtils.expectFailing;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
package com.acmeair.hystrix;
public class UserCommandFetchingCustomerFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
| private final UserService userService = new TestUserCommand(providerRule.getConfig().url()); |
WillemJiang/acmeair | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java | // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
| import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
| /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class JmeterSummariserParser extends ResultParser {
private static boolean SKIP_JMETER_DROPOUTS = false;
static {
SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null;
}
private String jmeterFileName = "AcmeAir[1-9].log";
private String testDate = "";
@Override
protected void processFile(File file) {
| // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class JmeterSummariserParser extends ResultParser {
private static boolean SKIP_JMETER_DROPOUTS = false;
static {
SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null;
}
private String jmeterFileName = "AcmeAir[1-9].log";
private String testDate = "";
@Override
protected void processFile(File file) {
| IndividualChartResults result= getData(file.getPath());
|
WillemJiang/acmeair | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java | // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
| import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
| /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class JmeterSummariserParser extends ResultParser {
private static boolean SKIP_JMETER_DROPOUTS = false;
static {
SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null;
}
private String jmeterFileName = "AcmeAir[1-9].log";
private String testDate = "";
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
| // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/JmeterSummariserParser.java
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class JmeterSummariserParser extends ResultParser {
private static boolean SKIP_JMETER_DROPOUTS = false;
static {
SKIP_JMETER_DROPOUTS = System.getProperty("SKIP_JMETER_DROPOUTS") != null;
}
private String jmeterFileName = "AcmeAir[1-9].log";
private String testDate = "";
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
| super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false);
|
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java | // Path: acmeair-services/src/main/java/com/acmeair/service/FlightService.java
// public abstract class FlightService {
// protected Logger logger = Logger.getLogger(FlightService.class.getName());
//
// //TODO:need to find a way to invalidate these maps
// protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache =
// new ConcurrentHashMap<String, FlightSegment>();
//
// protected static ConcurrentHashMap<String, List<Flight>> flightSegmentAndDataToFlightCache =
// new ConcurrentHashMap<String, List<Flight>>();
//
// protected static ConcurrentHashMap<String, Flight> flightPKtoFlightCache =
// new ConcurrentHashMap<String, Flight>();
//
// public Flight getFlightByFlightId(String flightId, String flightSegment) {
// try {
// Flight flight = flightPKtoFlightCache.get(flightId);
// if (flight == null) {
// flight = getFlight(flightId, flightSegment);
// if (flightId != null && flight != null) {
// flightPKtoFlightCache.putIfAbsent(flightId, flight);
// }
// }
// return flight;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// protected abstract Flight getFlight(String flightId, String flightSegment);
//
// public List<Flight> getFlightByAirportsAndDepartureDate(String fromAirport, String toAirport, Date deptDate) {
// if (logger.isLoggable(Level.FINE))
// logger.fine("Search for flights from " + fromAirport + " to " + toAirport + " on " + deptDate.toString());
//
// String originPortAndDestPortQueryString = fromAirport + toAirport;
// FlightSegment segment = originAndDestPortToSegmentCache.get(originPortAndDestPortQueryString);
//
// if (segment == null) {
// segment = getFlightSegment(fromAirport, toAirport);
// originAndDestPortToSegmentCache.putIfAbsent(originPortAndDestPortQueryString, segment);
// }
// // cache flights that not available (checks against sentinel value above indirectly)
// if (segment.getFlightName() == null) {
// return new ArrayList<Flight>();
// }
//
// String segId = segment.getFlightName();
// String flightSegmentIdAndScheduledDepartureTimeQueryString = segId + deptDate.toString();
// List<Flight> flights =
// flightSegmentAndDataToFlightCache.get(flightSegmentIdAndScheduledDepartureTimeQueryString);
//
// if (flights == null) {
// flights = getFlightBySegment(segment, deptDate);
// flightSegmentAndDataToFlightCache.putIfAbsent(flightSegmentIdAndScheduledDepartureTimeQueryString,
// flights);
// }
// if (logger.isLoggable(Level.FINEST))
// logger.finest("Returning " + flights);
// return flights;
//
// }
// public List<Flight> getFlightByAirportsAndDate(String fromAirport, String toAirport, Date deptDate) {
// if (logger.isLoggable(Level.FINE))
// logger.fine("Search for flights from " + fromAirport + " to " + toAirport + " on " + deptDate.toString());
//
// List<Flight> flights = getFlightByAirports(fromAirport, toAirport);
// List<Flight> results = new ArrayList<>();
// for (Flight flight : flights) {
// if (inOneDay(flight.getScheduledDepartureTime(), deptDate)) {
// results.add(flight);
// }
// }
//
// return results;
// }
//
// @SuppressWarnings("deprecation")
// protected boolean inOneDay(Date date1, Date date2) {
// return (date1.getYear() == date2.getYear()) && (date1.getMonth() == date2.getMonth())
// && (date1.getDate() == date2.getDate());
// }
//
// // NOTE: This is not cached
// public List<Flight> getFlightByAirports(String fromAirport, String toAirport) {
// FlightSegment segment = getFlightSegment(fromAirport, toAirport);
// if (segment == null) {
// return new ArrayList<Flight>();
// }
// return getFlightBySegment(segment, null);
// }
//
// protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport);
//
// protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate);
//
// public abstract void storeAirportMapping(AirportCodeMapping mapping);
//
// public abstract AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName);
//
// public abstract Flight createNewFlight(String flightSegmentId,
// Date scheduledDepartureTime, Date scheduledArrivalTime,
// BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
// int numFirstClassSeats, int numEconomyClassSeats,
// String airplaneTypeId);
//
// public abstract void storeFlightSegment(FlightSegment flightSeg);
//
// public abstract void storeFlightSegment(String flightName, String origPort, String destPort, int miles);
//
// public abstract Long countFlightSegments();
//
// public abstract Long countFlights();
//
// public abstract Long countAirports();
//
// }
| import java.util.ArrayList;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.acmeair.service.BookingService;
import com.acmeair.service.FlightService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired; | package com.acmeair.config;
@RestSchema(schemaId = "config")
@Path("/info/config")
@Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
public class AcmeAirConfiguration {
Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
@Autowired
private BookingService bs;
@Autowired | // Path: acmeair-services/src/main/java/com/acmeair/service/FlightService.java
// public abstract class FlightService {
// protected Logger logger = Logger.getLogger(FlightService.class.getName());
//
// //TODO:need to find a way to invalidate these maps
// protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache =
// new ConcurrentHashMap<String, FlightSegment>();
//
// protected static ConcurrentHashMap<String, List<Flight>> flightSegmentAndDataToFlightCache =
// new ConcurrentHashMap<String, List<Flight>>();
//
// protected static ConcurrentHashMap<String, Flight> flightPKtoFlightCache =
// new ConcurrentHashMap<String, Flight>();
//
// public Flight getFlightByFlightId(String flightId, String flightSegment) {
// try {
// Flight flight = flightPKtoFlightCache.get(flightId);
// if (flight == null) {
// flight = getFlight(flightId, flightSegment);
// if (flightId != null && flight != null) {
// flightPKtoFlightCache.putIfAbsent(flightId, flight);
// }
// }
// return flight;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
//
// protected abstract Flight getFlight(String flightId, String flightSegment);
//
// public List<Flight> getFlightByAirportsAndDepartureDate(String fromAirport, String toAirport, Date deptDate) {
// if (logger.isLoggable(Level.FINE))
// logger.fine("Search for flights from " + fromAirport + " to " + toAirport + " on " + deptDate.toString());
//
// String originPortAndDestPortQueryString = fromAirport + toAirport;
// FlightSegment segment = originAndDestPortToSegmentCache.get(originPortAndDestPortQueryString);
//
// if (segment == null) {
// segment = getFlightSegment(fromAirport, toAirport);
// originAndDestPortToSegmentCache.putIfAbsent(originPortAndDestPortQueryString, segment);
// }
// // cache flights that not available (checks against sentinel value above indirectly)
// if (segment.getFlightName() == null) {
// return new ArrayList<Flight>();
// }
//
// String segId = segment.getFlightName();
// String flightSegmentIdAndScheduledDepartureTimeQueryString = segId + deptDate.toString();
// List<Flight> flights =
// flightSegmentAndDataToFlightCache.get(flightSegmentIdAndScheduledDepartureTimeQueryString);
//
// if (flights == null) {
// flights = getFlightBySegment(segment, deptDate);
// flightSegmentAndDataToFlightCache.putIfAbsent(flightSegmentIdAndScheduledDepartureTimeQueryString,
// flights);
// }
// if (logger.isLoggable(Level.FINEST))
// logger.finest("Returning " + flights);
// return flights;
//
// }
// public List<Flight> getFlightByAirportsAndDate(String fromAirport, String toAirport, Date deptDate) {
// if (logger.isLoggable(Level.FINE))
// logger.fine("Search for flights from " + fromAirport + " to " + toAirport + " on " + deptDate.toString());
//
// List<Flight> flights = getFlightByAirports(fromAirport, toAirport);
// List<Flight> results = new ArrayList<>();
// for (Flight flight : flights) {
// if (inOneDay(flight.getScheduledDepartureTime(), deptDate)) {
// results.add(flight);
// }
// }
//
// return results;
// }
//
// @SuppressWarnings("deprecation")
// protected boolean inOneDay(Date date1, Date date2) {
// return (date1.getYear() == date2.getYear()) && (date1.getMonth() == date2.getMonth())
// && (date1.getDate() == date2.getDate());
// }
//
// // NOTE: This is not cached
// public List<Flight> getFlightByAirports(String fromAirport, String toAirport) {
// FlightSegment segment = getFlightSegment(fromAirport, toAirport);
// if (segment == null) {
// return new ArrayList<Flight>();
// }
// return getFlightBySegment(segment, null);
// }
//
// protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport);
//
// protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate);
//
// public abstract void storeAirportMapping(AirportCodeMapping mapping);
//
// public abstract AirportCodeMapping createAirportCodeMapping(String airportCode, String airportName);
//
// public abstract Flight createNewFlight(String flightSegmentId,
// Date scheduledDepartureTime, Date scheduledArrivalTime,
// BigDecimal firstClassBaseCost, BigDecimal economyClassBaseCost,
// int numFirstClassSeats, int numEconomyClassSeats,
// String airplaneTypeId);
//
// public abstract void storeFlightSegment(FlightSegment flightSeg);
//
// public abstract void storeFlightSegment(String flightName, String origPort, String destPort, int miles);
//
// public abstract Long countFlightSegments();
//
// public abstract Long countFlights();
//
// public abstract Long countAirports();
//
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
import java.util.ArrayList;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.acmeair.service.BookingService;
import com.acmeair.service.FlightService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
package com.acmeair.config;
@RestSchema(schemaId = "config")
@Path("/info/config")
@Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
public class AcmeAirConfiguration {
Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
@Autowired
private BookingService bs;
@Autowired | private FlightService flightService; |
WillemJiang/acmeair | acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
| import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@Component
@Profile({"!test"})
public class RESTCookieSessionFilter extends ZuulFilter {
private static final Logger logger = LoggerFactory.getLogger(RESTCookieSessionFilter.class);
private static final String LOGIN_USER = "acmeair.login_user";
private static final String LOGIN_PATH = "/rest/api/login";
private static final String LOGOUT_PATH = "/rest/api/login/logout";
private static final String LOADDB_PATH = "/rest/api/loaddb";
private static final String CONFIG_PATH = "/info/config/";
private static final String LOADER_PATH = "/info/loader/";
@Autowired | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
// Path: acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@Component
@Profile({"!test"})
public class RESTCookieSessionFilter extends ZuulFilter {
private static final Logger logger = LoggerFactory.getLogger(RESTCookieSessionFilter.class);
private static final String LOGIN_USER = "acmeair.login_user";
private static final String LOGIN_PATH = "/rest/api/login";
private static final String LOGOUT_PATH = "/rest/api/login/logout";
private static final String LOADDB_PATH = "/rest/api/loaddb";
private static final String CONFIG_PATH = "/info/config/";
private static final String LOADER_PATH = "/info/loader/";
@Autowired | private AuthenticationService authenticationService; |
WillemJiang/acmeair | acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
| import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component; | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@Component
@Profile({"!test"})
public class RESTCookieSessionFilter extends ZuulFilter {
private static final Logger logger = LoggerFactory.getLogger(RESTCookieSessionFilter.class);
private static final String LOGIN_USER = "acmeair.login_user";
private static final String LOGIN_PATH = "/rest/api/login";
private static final String LOGOUT_PATH = "/rest/api/login/logout";
private static final String LOADDB_PATH = "/rest/api/loaddb";
private static final String CONFIG_PATH = "/info/config/";
private static final String LOADER_PATH = "/info/loader/";
@Autowired
private AuthenticationService authenticationService;
private void doFilter(RequestContext context) throws IOException, ServletException {
HttpServletRequest request = context.getRequest();
String path = request.getContextPath() + request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
logger.debug("Get the request path {}", path);
if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH) ||
path.contains(CONFIG_PATH) || path.contains(LOADER_PATH)) {
// if logging in, logging out, lookup configuration, or loading the database , let the request flow
return;
}
Cookie cookies[] = request.getCookies();
Cookie sessionCookie = null;
if (cookies != null) {
for (Cookie c : cookies) { | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
// Path: acmeair-webapp/src/main/java/com/acmeair/web/RESTCookieSessionFilter.java
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import java.io.IOException;
import java.util.Arrays;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@Component
@Profile({"!test"})
public class RESTCookieSessionFilter extends ZuulFilter {
private static final Logger logger = LoggerFactory.getLogger(RESTCookieSessionFilter.class);
private static final String LOGIN_USER = "acmeair.login_user";
private static final String LOGIN_PATH = "/rest/api/login";
private static final String LOGOUT_PATH = "/rest/api/login/logout";
private static final String LOADDB_PATH = "/rest/api/loaddb";
private static final String CONFIG_PATH = "/info/config/";
private static final String LOADER_PATH = "/info/loader/";
@Autowired
private AuthenticationService authenticationService;
private void doFilter(RequestContext context) throws IOException, ServletException {
HttpServletRequest request = context.getRequest();
String path = request.getContextPath() + request.getServletPath();
if (request.getPathInfo() != null) {
path = path + request.getPathInfo();
}
logger.debug("Get the request path {}", path);
if (path.endsWith(LOGIN_PATH) || path.endsWith(LOGOUT_PATH) || path.endsWith(LOADDB_PATH) ||
path.contains(CONFIG_PATH) || path.contains(LOADER_PATH)) {
// if logging in, logging out, lookup configuration, or loading the database , let the request flow
return;
}
Cookie cookies[] = request.getCookies();
Cookie sessionCookie = null;
if (cookies != null) {
for (Cookie c : cookies) { | if (c.getName().equals(CustomerSession.SESSIONID_COOKIE_NAME)) { |
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
| import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct; | package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class); | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java
import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class); | registerClasses(LoaderREST.class, AcmeAirConfiguration.class); |
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
| import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct; | package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class); | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java
import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class); | registerClasses(LoaderREST.class, AcmeAirConfiguration.class); |
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
| import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct; | package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class);
registerClasses(LoaderREST.class, AcmeAirConfiguration.class);
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
@PostConstruct
public void init() {
// The init method is called | // Path: acmeair-booking-service/src/main/java/com/acmeair/config/AcmeAirConfiguration.java
// @RestSchema(schemaId = "config")
// @Path("/info/config")
// @Api(value = "Booking Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class AcmeAirConfiguration {
//
// Logger logger = Logger.getLogger(AcmeAirConfiguration.class.getName());
//
// @Autowired
// private BookingService bs;
//
// @Autowired
// private FlightService flightService;
//
// public AcmeAirConfiguration() {
// super();
// }
//
// @GET
// @Path("/dataServices")
// @Produces(MediaType.APPLICATION_JSON)
// public ArrayList<ServiceData> getDataServiceInfo() {
// // We don't use the ServiceLocator to lookup the DataService
// ArrayList<ServiceData> list = new ArrayList<>();
// return list;
// }
//
// @GET
// @Path("/activeDataService")
// @Produces(MediaType.APPLICATION_JSON)
// public String getActiveDataServiceInfo() {
// logger.fine("Get active Data Service info");
// // We just have one implementation here
// return "Morphia";
// }
//
// @GET
// @Path("/runtime")
// @Produces("application/json")
// public ArrayList<ServiceData> getRuntimeInfo() {
// try {
// logger.fine("Getting Runtime info");
// ArrayList<ServiceData> list = new ArrayList<ServiceData>();
// ServiceData data = new ServiceData();
// data.name = "Runtime";
// data.description = "Java";
// list.add(data);
//
// data = new ServiceData();
// data.name = "Version";
// data.description = System.getProperty("java.version");
// list.add(data);
//
// data = new ServiceData();
// data.name = "Vendor";
// data.description = System.getProperty("java.vendor");
// list.add(data);
//
// return list;
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// class ServiceData {
// public String name = "";
//
// public String description = "";
// }
//
// @GET
// @Path("/countBookings")
// @Produces("application/json")
// public Long countBookings() {
// try {
// Long count = bs.count();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlights")
// @Produces("application/json")
// public Long countFlights() {
// try {
// Long count = flightService.countFlights();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countFlightSegments")
// @Produces("application/json")
// public Long countFlightSegments() {
// try {
// Long count = flightService.countFlightSegments();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// @GET
// @Path("/countAirports")
// @Produces("application/json")
// public Long countAirports() {
// try {
// Long count = flightService.countAirports();
// return count;
// } catch (Exception e) {
// e.printStackTrace();
// return -1L;
// }
// }
//
// }
//
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/LoaderREST.java
// @RestSchema(schemaId = "loader")
// @Path("/info/loader")
// @Api(value = "Customer Service User Information Loading Service", produces = MediaType.TEXT_PLAIN)
// public class LoaderREST {
//
// @Autowired
// private Loader loader;
//
// @GET
// @Path("/query")
// @Produces(MediaType.TEXT_PLAIN)
// public String queryLoader() {
// String response = loader.queryLoader();
// return response;
// }
//
// @GET
// @Path("/load")
// @Produces(MediaType.TEXT_PLAIN)
// public String loadDB(@DefaultValue("-1") @QueryParam("numCustomers") long numCustomers) {
// String response = loader.loadDB(numCustomers);
// return response;
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/web/AcmeAirApp.java
import com.acmeair.config.AcmeAirConfiguration;
import com.acmeair.config.LoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;
package com.acmeair.web;
@Configuration
@Primary
public class AcmeAirApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
public AcmeAirApp() {
registerClasses(BookingsREST.class, FlightsREST.class);
registerClasses(LoaderREST.class, AcmeAirConfiguration.class);
property(ServletProperties.FILTER_FORWARD_ON_404, true);
}
@PostConstruct
public void init() {
// The init method is called | register(ProblemInjectFilter.class); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
| import java.util.Calendar;
import java.util.Date;
import javax.inject.Inject;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerSession; | @Override
public Customer getCustomerByUsername(String username) {
Customer c = getCustomer(username);
if (c != null) {
c.setPassword(null);
}
return c;
}
@Override
public boolean validateCustomer(String username, String password) {
boolean validatedCustomer = false;
Customer customerToValidate = getCustomer(username);
if (customerToValidate != null) {
validatedCustomer = password.equals(customerToValidate.getPassword());
}
return validatedCustomer;
}
@Override
public Customer getCustomerByUsernameAndPassword(String username, String password) {
Customer c = getCustomer(username);
if (c != null && !c.getPassword().equals(password)) {
return null;
}
// Should we also set the password to null?
return c;
}
@Override | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
import java.util.Calendar;
import java.util.Date;
import javax.inject.Inject;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerSession;
@Override
public Customer getCustomerByUsername(String username) {
Customer c = getCustomer(username);
if (c != null) {
c.setPassword(null);
}
return c;
}
@Override
public boolean validateCustomer(String username, String password) {
boolean validatedCustomer = false;
Customer customerToValidate = getCustomer(username);
if (customerToValidate != null) {
validatedCustomer = password.equals(customerToValidate.getPassword());
}
return validatedCustomer;
}
@Override
public Customer getCustomerByUsernameAndPassword(String username, String password) {
Customer c = getCustomer(username);
if (c != null && !c.getPassword().equals(password)) {
return null;
}
// Should we also set the password to null?
return c;
}
@Override | public CustomerSession validateSession(String sessionid) { |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
| import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl; | package com.acmeair.service;
public interface CustomerService {
Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
Customer.PhoneType phoneNumberType, CustomerAddressImpl address
);
CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
Customer updateCustomer(Customer customer);
Customer getCustomerByUsername(String username);
boolean validateCustomer(String username, String password);
Customer getCustomerByUsernameAndPassword(String username, String password);
| // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
package com.acmeair.service;
public interface CustomerService {
Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
Customer.PhoneType phoneNumberType, CustomerAddressImpl address
);
CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
Customer updateCustomer(Customer customer);
Customer getCustomerByUsername(String username);
boolean validateCustomer(String username, String password);
Customer getCustomerByUsernameAndPassword(String username, String password);
| CustomerSession validateSession(String sessionid); |
WillemJiang/acmeair | acmeair-services/src/main/java/com/acmeair/service/FlightService.java | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
| import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping; | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.service;
public abstract class FlightService {
protected Logger logger = Logger.getLogger(FlightService.class.getName());
//TODO:need to find a way to invalidate these maps | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
// Path: acmeair-services/src/main/java/com/acmeair/service/FlightService.java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping;
/*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.service;
public abstract class FlightService {
protected Logger logger = Logger.getLogger(FlightService.class.getName());
//TODO:need to find a way to invalidate these maps | protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache = |
WillemJiang/acmeair | acmeair-services/src/main/java/com/acmeair/service/FlightService.java | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
| import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping; | /*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.service;
public abstract class FlightService {
protected Logger logger = Logger.getLogger(FlightService.class.getName());
//TODO:need to find a way to invalidate these maps
protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache =
new ConcurrentHashMap<String, FlightSegment>();
| // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
// Path: acmeair-services/src/main/java/com/acmeair/service/FlightService.java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping;
/*******************************************************************************
* Copyright (c) 2013-2015 IBM Corp.
*
* 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.acmeair.service;
public abstract class FlightService {
protected Logger logger = Logger.getLogger(FlightService.class.getName());
//TODO:need to find a way to invalidate these maps
protected static ConcurrentHashMap<String, FlightSegment> originAndDestPortToSegmentCache =
new ConcurrentHashMap<String, FlightSegment>();
| protected static ConcurrentHashMap<String, List<Flight>> flightSegmentAndDataToFlightCache = |
WillemJiang/acmeair | acmeair-services/src/main/java/com/acmeair/service/FlightService.java | // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
| import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping; | List<Flight> flights = getFlightByAirports(fromAirport, toAirport);
List<Flight> results = new ArrayList<>();
for (Flight flight : flights) {
if (inOneDay(flight.getScheduledDepartureTime(), deptDate)) {
results.add(flight);
}
}
return results;
}
@SuppressWarnings("deprecation")
protected boolean inOneDay(Date date1, Date date2) {
return (date1.getYear() == date2.getYear()) && (date1.getMonth() == date2.getMonth())
&& (date1.getDate() == date2.getDate());
}
// NOTE: This is not cached
public List<Flight> getFlightByAirports(String fromAirport, String toAirport) {
FlightSegment segment = getFlightSegment(fromAirport, toAirport);
if (segment == null) {
return new ArrayList<Flight>();
}
return getFlightBySegment(segment, null);
}
protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport);
protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate);
| // Path: acmeair-common/src/main/java/com/acmeair/entities/Flight.java
// public interface Flight{
//
//
// String getFlightId();
//
// void setFlightId(String id);
//
// String getFlightSegmentId();
//
// FlightSegment getFlightSegment();
//
// void setFlightSegment(FlightSegment flightSegment);
//
// Date getScheduledDepartureTime();
//
// Date getScheduledArrivalTime();
//
// BigDecimal getFirstClassBaseCost();
//
//
// BigDecimal getEconomyClassBaseCost();
//
//
// int getNumFirstClassSeats();
//
//
// int getNumEconomyClassSeats();
//
//
// String getAirplaneTypeId();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/FlightSegment.java
// public interface FlightSegment {
//
// String getFlightName();
//
// String getOriginPort();
//
// String getDestPort();
//
// int getMiles();
//
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/entities/AirportCodeMapping.java
// public interface AirportCodeMapping{
//
//
// String getAirportCode();
//
// void setAirportCode(String airportCode);
//
// String getAirportName();
//
// void setAirportName(String airportName);
//
// }
// Path: acmeair-services/src/main/java/com/acmeair/service/FlightService.java
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.acmeair.entities.Flight;
import com.acmeair.entities.FlightSegment;
import com.acmeair.entities.AirportCodeMapping;
List<Flight> flights = getFlightByAirports(fromAirport, toAirport);
List<Flight> results = new ArrayList<>();
for (Flight flight : flights) {
if (inOneDay(flight.getScheduledDepartureTime(), deptDate)) {
results.add(flight);
}
}
return results;
}
@SuppressWarnings("deprecation")
protected boolean inOneDay(Date date1, Date date2) {
return (date1.getYear() == date2.getYear()) && (date1.getMonth() == date2.getMonth())
&& (date1.getDate() == date2.getDate());
}
// NOTE: This is not cached
public List<Flight> getFlightByAirports(String fromAirport, String toAirport) {
FlightSegment segment = getFlightSegment(fromAirport, toAirport);
if (segment == null) {
return new ArrayList<Flight>();
}
return getFlightBySegment(segment, null);
}
protected abstract FlightSegment getFlightSegment(String fromAirport, String toAirport);
protected abstract List<Flight> getFlightBySegment(FlightSegment segment, Date deptDate);
| public abstract void storeAirportMapping(AirportCodeMapping mapping); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/web/CustomerServiceApp.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java
// @RestSchema(schemaId = "customer_configuration")
// @Path("/info/config")
// @Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class CustomerConfiguration {
// @Autowired
// private CustomerService customerService;
//
// @GET
// @Path("/countCustomers")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerCount Resource cannot be found")
//
// })
// public long countCustomer() {
// try {
// return customerService.count();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
//
// @GET
// @Path("/countSessions")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer SessionCount Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerSessionCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerSessionCount Resource cannot be found")
//
// })
// public long countCustomerSessions() {
// try {
//
// return customerService.countSessions();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
| import com.acmeair.config.CustomerConfiguration;
import com.acmeair.loader.CustomerLoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; | package com.acmeair.web;
@Configuration
public class CustomerServiceApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
@PostConstruct
@Profile("!SpringCloud")
public void init() {
// Add the problem inject | // Path: acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java
// @RestSchema(schemaId = "customer_configuration")
// @Path("/info/config")
// @Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class CustomerConfiguration {
// @Autowired
// private CustomerService customerService;
//
// @GET
// @Path("/countCustomers")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerCount Resource cannot be found")
//
// })
// public long countCustomer() {
// try {
// return customerService.count();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
//
// @GET
// @Path("/countSessions")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer SessionCount Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerSessionCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerSessionCount Resource cannot be found")
//
// })
// public long countCustomerSessions() {
// try {
//
// return customerService.countSessions();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/web/CustomerServiceApp.java
import com.acmeair.config.CustomerConfiguration;
import com.acmeair.loader.CustomerLoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
package com.acmeair.web;
@Configuration
public class CustomerServiceApp extends ResourceConfig {
@Value("${spring.jersey.application-path:/}")
private String apiPath;
@PostConstruct
@Profile("!SpringCloud")
public void init() {
// Add the problem inject | register(ProblemInjectFilter.class); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/web/CustomerServiceApp.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java
// @RestSchema(schemaId = "customer_configuration")
// @Path("/info/config")
// @Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class CustomerConfiguration {
// @Autowired
// private CustomerService customerService;
//
// @GET
// @Path("/countCustomers")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerCount Resource cannot be found")
//
// })
// public long countCustomer() {
// try {
// return customerService.count();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
//
// @GET
// @Path("/countSessions")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer SessionCount Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerSessionCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerSessionCount Resource cannot be found")
//
// })
// public long countCustomerSessions() {
// try {
//
// return customerService.countSessions();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
| import com.acmeair.config.CustomerConfiguration;
import com.acmeair.loader.CustomerLoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider; |
@PostConstruct
@Profile("SpringCloud")
public void initWithSpringCloud() {
// Add the problem inject
register(ProblemInjectFilter.class);
register(CustomerExceptionHandler.class);
register(LoginResponseFilter.class);
// The init method is called
configureSwagger();
}
private void configureSwagger() {
register(ApiListingResource.class);
register(SwaggerSerializers.class);
// Just setup the configuration of the swagger API
BeanConfig config = new BeanConfig();
config.setConfigId("AcmeAire-CustomerService");
config.setTitle("AcmeAire + CustomerService ");
config.setVersion("v1");
config.setSchemes(new String[]{"http"});
config.setBasePath(apiPath);
config.setResourcePackage("com.acmeair");
config.setPrettyPrint(true);
config.setScan(true);
}
public CustomerServiceApp() { | // Path: acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java
// @RestSchema(schemaId = "customer_configuration")
// @Path("/info/config")
// @Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
// public class CustomerConfiguration {
// @Autowired
// private CustomerService customerService;
//
// @GET
// @Path("/countCustomers")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerCount Resource cannot be found")
//
// })
// public long countCustomer() {
// try {
// return customerService.count();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
//
// @GET
// @Path("/countSessions")
// @Produces(MediaType.APPLICATION_JSON)
// @ApiOperation(value = "Get the Customer SessionCount Resource.",produces=MediaType.APPLICATION_JSON, response = Long.class)
// @ApiResponses(value = {
// @ApiResponse(code = 200, message = "CustomerSessionCount Resource is found"),
// @ApiResponse(code = 404, message = "CustomerSessionCount Resource cannot be found")
//
// })
// public long countCustomerSessions() {
// try {
//
// return customerService.countSessions();
// } catch (Exception e) {
// e.printStackTrace();
// return -1;
// }
// }
// }
//
// Path: acmeair-common/src/main/java/com/acmeair/problems/ProblemInjectFilter.java
// public class ProblemInjectFilter implements ContainerRequestFilter {
// private ProblemInjector problemInjector = new ProblemInjector();
//
// @Override
// public void filter(ContainerRequestContext requestContext) throws IOException {
// problemInjector.handleRequest(new ContainerRequest(requestContext));
// }
//
// class ContainerRequest implements Request {
// private ContainerRequestContext requestContext;
//
// ContainerRequest(ContainerRequestContext requestContext) {
// this.requestContext = requestContext;
// }
//
//
// @Override
// public String getHeader(String header) {
// return requestContext.getHeaderString(header);
// }
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/web/CustomerServiceApp.java
import com.acmeair.config.CustomerConfiguration;
import com.acmeair.loader.CustomerLoaderREST;
import com.acmeair.problems.ProblemInjectFilter;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@PostConstruct
@Profile("SpringCloud")
public void initWithSpringCloud() {
// Add the problem inject
register(ProblemInjectFilter.class);
register(CustomerExceptionHandler.class);
register(LoginResponseFilter.class);
// The init method is called
configureSwagger();
}
private void configureSwagger() {
register(ApiListingResource.class);
register(SwaggerSerializers.class);
// Just setup the configuration of the swagger API
BeanConfig config = new BeanConfig();
config.setConfigId("AcmeAire-CustomerService");
config.setTitle("AcmeAire + CustomerService ");
config.setVersion("v1");
config.setSchemes(new String[]{"http"});
config.setBasePath(apiPath);
config.setResourcePackage("com.acmeair");
config.setPrettyPrint(true);
config.setScan(true);
}
public CustomerServiceApp() { | registerClasses(CustomerREST.class, LoginREST.class, CouponREST.class, CustomerConfiguration.class, CustomerLoaderREST.class); |
WillemJiang/acmeair | acmeair-booking-service/src/main/java/com/acmeair/config/FlightLoaderConfig.java | // Path: acmeair-loader/src/main/java/com/acmeair/loader/FlightLoader.java
// @Component
// public class FlightLoader {
//
// @Value("${flights.max.per.segment:30}")
// private int maxFlightsPerSegment;
//
// @Autowired
// private FlightService flightService;
//
// public void loadFlights() throws Exception {
// InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv");
//
// LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
// String line1 = lnr.readLine();
// StringTokenizer st = new StringTokenizer(line1, ",");
// ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();
//
// // read the first line which are airport names
// while (st.hasMoreTokens()) {
// AirportCodeMapping acm = flightService.createAirportCodeMapping(null, st.nextToken());
// // acm.setAirportName(st.nextToken());
// airports.add(acm);
// }
// // read the second line which contains matching airport codes for the first line
// String line2 = lnr.readLine();
// st = new StringTokenizer(line2, ",");
// int ii = 0;
// while (st.hasMoreTokens()) {
// String airportCode = st.nextToken();
// airports.get(ii).setAirportCode(airportCode);
// ii++;
// }
// // read the other lines which are of format:
// // airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two
// String line;
// int flightNumber = 0;
// while (true) {
// line = lnr.readLine();
// if (line == null || line.trim().equals("")) {
// break;
// }
// st = new StringTokenizer(line, ",");
// String airportName = st.nextToken();
// String airportCode = st.nextToken();
// if (!alreadyInCollection(airportCode, airports)) {
// AirportCodeMapping acm = flightService.createAirportCodeMapping(airportCode, airportName);
// airports.add(acm);
// }
// int indexIntoTopLine = 0;
// while (st.hasMoreTokens()) {
// String milesString = st.nextToken();
// if (milesString.equals("NA")) {
// indexIntoTopLine++;
// continue;
// }
// int miles = Integer.parseInt(milesString);
// String toAirport = airports.get(indexIntoTopLine).getAirportCode();
// String flightId = "AA" + flightNumber;
// flightService.storeFlightSegment(flightId, airportCode, toAirport, miles);
// for (int daysFromNow = 0; daysFromNow < maxFlightsPerSegment; daysFromNow++) {
// Date departureTime = Date.from(OffsetDateTime.now(ZoneId.of("Asia/Shanghai"))
// .truncatedTo(ChronoUnit.DAYS)
// .plusDays(daysFromNow)
// .toInstant());
// Date arrivalTime = getArrivalTime(departureTime, miles);
// flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500), new BigDecimal(200), 10, 200, "B747");
//
// }
// flightNumber++;
// indexIntoTopLine++;
// }
// }
//
// for (int jj = 0; jj < airports.size(); jj++) {
// flightService.storeAirportMapping(airports.get(jj));
// }
// lnr.close();
// }
//
// private static Date getArrivalTime(Date departureTime, int mileage) {
// double averageSpeed = 600.0; // 600 miles/hours
// double hours = (double) mileage / averageSpeed; // miles / miles/hour = hours
// double partsOfHour = hours % 1.0;
// int minutes = (int)(60.0 * partsOfHour);
// Calendar c = Calendar.getInstance();
// c.setTime(departureTime);
// c.add(Calendar.HOUR, (int)hours);
// c.add(Calendar.MINUTE, minutes);
// return c.getTime();
// }
//
// static private boolean alreadyInCollection(String airportCode, ArrayList<AirportCodeMapping> airports) {
// for (int ii = 0; ii < airports.size(); ii++) {
// if (airports.get(ii).getAirportCode().equals(airportCode)) {
// return true;
// }
// }
// return false;
// }
// }
| import com.acmeair.loader.FlightLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct; | package com.acmeair.config;
@Profile("perf")
@Configuration
class FlightLoaderConfig {
private static final Logger logger = LoggerFactory.getLogger(FlightLoaderConfig.class);
@Autowired | // Path: acmeair-loader/src/main/java/com/acmeair/loader/FlightLoader.java
// @Component
// public class FlightLoader {
//
// @Value("${flights.max.per.segment:30}")
// private int maxFlightsPerSegment;
//
// @Autowired
// private FlightService flightService;
//
// public void loadFlights() throws Exception {
// InputStream csvInputStream = FlightLoader.class.getResourceAsStream("/mileage.csv");
//
// LineNumberReader lnr = new LineNumberReader(new InputStreamReader(csvInputStream));
// String line1 = lnr.readLine();
// StringTokenizer st = new StringTokenizer(line1, ",");
// ArrayList<AirportCodeMapping> airports = new ArrayList<AirportCodeMapping>();
//
// // read the first line which are airport names
// while (st.hasMoreTokens()) {
// AirportCodeMapping acm = flightService.createAirportCodeMapping(null, st.nextToken());
// // acm.setAirportName(st.nextToken());
// airports.add(acm);
// }
// // read the second line which contains matching airport codes for the first line
// String line2 = lnr.readLine();
// st = new StringTokenizer(line2, ",");
// int ii = 0;
// while (st.hasMoreTokens()) {
// String airportCode = st.nextToken();
// airports.get(ii).setAirportCode(airportCode);
// ii++;
// }
// // read the other lines which are of format:
// // airport name, aiport code, distance from this airport to whatever airport is in the column from lines one and two
// String line;
// int flightNumber = 0;
// while (true) {
// line = lnr.readLine();
// if (line == null || line.trim().equals("")) {
// break;
// }
// st = new StringTokenizer(line, ",");
// String airportName = st.nextToken();
// String airportCode = st.nextToken();
// if (!alreadyInCollection(airportCode, airports)) {
// AirportCodeMapping acm = flightService.createAirportCodeMapping(airportCode, airportName);
// airports.add(acm);
// }
// int indexIntoTopLine = 0;
// while (st.hasMoreTokens()) {
// String milesString = st.nextToken();
// if (milesString.equals("NA")) {
// indexIntoTopLine++;
// continue;
// }
// int miles = Integer.parseInt(milesString);
// String toAirport = airports.get(indexIntoTopLine).getAirportCode();
// String flightId = "AA" + flightNumber;
// flightService.storeFlightSegment(flightId, airportCode, toAirport, miles);
// for (int daysFromNow = 0; daysFromNow < maxFlightsPerSegment; daysFromNow++) {
// Date departureTime = Date.from(OffsetDateTime.now(ZoneId.of("Asia/Shanghai"))
// .truncatedTo(ChronoUnit.DAYS)
// .plusDays(daysFromNow)
// .toInstant());
// Date arrivalTime = getArrivalTime(departureTime, miles);
// flightService.createNewFlight(flightId, departureTime, arrivalTime, new BigDecimal(500), new BigDecimal(200), 10, 200, "B747");
//
// }
// flightNumber++;
// indexIntoTopLine++;
// }
// }
//
// for (int jj = 0; jj < airports.size(); jj++) {
// flightService.storeAirportMapping(airports.get(jj));
// }
// lnr.close();
// }
//
// private static Date getArrivalTime(Date departureTime, int mileage) {
// double averageSpeed = 600.0; // 600 miles/hours
// double hours = (double) mileage / averageSpeed; // miles / miles/hour = hours
// double partsOfHour = hours % 1.0;
// int minutes = (int)(60.0 * partsOfHour);
// Calendar c = Calendar.getInstance();
// c.setTime(departureTime);
// c.add(Calendar.HOUR, (int)hours);
// c.add(Calendar.MINUTE, minutes);
// return c.getTime();
// }
//
// static private boolean alreadyInCollection(String airportCode, ArrayList<AirportCodeMapping> airports) {
// for (int ii = 0; ii < airports.size(); ii++) {
// if (airports.get(ii).getAirportCode().equals(airportCode)) {
// return true;
// }
// }
// return false;
// }
// }
// Path: acmeair-booking-service/src/main/java/com/acmeair/config/FlightLoaderConfig.java
import com.acmeair.loader.FlightLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import javax.annotation.PostConstruct;
package com.acmeair.config;
@Profile("perf")
@Configuration
class FlightLoaderConfig {
private static final Logger logger = LoggerFactory.getLogger(FlightLoaderConfig.class);
@Autowired | private FlightLoader flightLoader; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/web/CouponREST.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
| import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.service.CouponService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.web;
@RestSchema(schemaId = "coupon_REST")
@Path("/api/coupon")
@Api(value = "Coupon Information Query and Update Service", produces = MediaType.APPLICATION_JSON)
public class CouponREST {
private static final Logger logger = LoggerFactory.getLogger(CouponREST.class);
private final CouponService couponService;
@Autowired
CouponREST(CouponService couponService) {
this.couponService = couponService;
}
@GET
@Path("/{customername}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "query all available coupon.", notes = "query all available coupon.", produces = MediaType.APPLICATION_JSON)
@ApiResponses(value = {@ApiResponse(code = 403, message = "Invalid user information"),
@ApiResponse(code = 500, message = "CustomerService Internal Server Error")}) | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/web/CouponREST.java
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.service.CouponService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.web;
@RestSchema(schemaId = "coupon_REST")
@Path("/api/coupon")
@Api(value = "Coupon Information Query and Update Service", produces = MediaType.APPLICATION_JSON)
public class CouponREST {
private static final Logger logger = LoggerFactory.getLogger(CouponREST.class);
private final CouponService couponService;
@Autowired
CouponREST(CouponService couponService) {
this.couponService = couponService;
}
@GET
@Path("/{customername}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "query all available coupon.", notes = "query all available coupon.", produces = MediaType.APPLICATION_JSON)
@ApiResponses(value = {@ApiResponse(code = 403, message = "Invalid user information"),
@ApiResponse(code = 500, message = "CustomerService Internal Server Error")}) | public List<CouponImpl> query( |
WillemJiang/acmeair | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java | // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
| import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
| /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class NmonParser extends ResultParser{
private String nmonFileName = "output.nmon";
public NmonParser(){
super.setMultipleYAxisLabel("usr%+sys%"); //default label
}
@Override
protected void processFile(File file) {
| // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class NmonParser extends ResultParser{
private String nmonFileName = "output.nmon";
public NmonParser(){
super.setMultipleYAxisLabel("usr%+sys%"); //default label
}
@Override
protected void processFile(File file) {
| IndividualChartResults result= getData(file.getPath());
|
WillemJiang/acmeair | acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java | // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
| import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
| /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class NmonParser extends ResultParser{
private String nmonFileName = "output.nmon";
public NmonParser(){
super.setMultipleYAxisLabel("usr%+sys%"); //default label
}
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
| // Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/IndividualChartResults.java
// public class IndividualChartResults {
// private ArrayList<Double> inputList = new ArrayList<Double>();
// private String title;
// private ArrayList<String> timeList = new ArrayList<String>();
// private int files = 0;
//
// public void setTitle(String title) {
// this.title = title;
// }
// public ArrayList<Double> getInputList() {
// return inputList;
// }
// public void setInputList(ArrayList<Double> inputList) {
// this.inputList = inputList;
// }
// public ArrayList<String> getTimeList() {
// return timeList;
// }
// public void setTimeList(ArrayList<String> timeList) {
// this.timeList = timeList;
// }
//
// public String getTitle() {
// return title;
// }
//
// public void incrementFiles(){
// files++;
// }
//
// public int getFilesCount(){
// return files;
// }
//
// }
//
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/ResultParserHelper.java
// public class ResultParserHelper {
//
// public static Color getColor(int i) {
// Color[] colors = { Color.RED, Color.BLACK, Color.BLUE, Color.YELLOW,
// Color.GREEN, Color.ORANGE, Color.PINK, Color.SILVER,
// Color.GOLD, Color.WHITE, Color.BROWN, Color.CYAN,Color.GRAY,Color.HONEYDEW,Color.IVORY };
// return colors[i % 15];
// }
//
// public static <E> ArrayList<E> scaleDown(ArrayList<E> testList, int scaleDownFactor) {
//
// if (testList==null) {
// return null;
// }
// if (testList.size() <= 7)
// return testList;
// if (scaleDownFactor > 10 || scaleDownFactor < 0) {
// throw new RuntimeException(
// "currently only support factor from 0-10");
// }
// int listLastItemIndex = testList.size() - 1;
// int a = (int) java.lang.Math.pow(2, scaleDownFactor);
// if (a > listLastItemIndex) {
// return testList;
// }
// ArrayList<E> newList = new ArrayList<E>();
// newList.add(testList.get(0));
//
// if (scaleDownFactor == 0) {
// newList.add(testList.get(listLastItemIndex));
//
// } else {
//
// for (int m = 1; m <= a; m++) {
// newList.add(testList.get(listLastItemIndex * m / a));
// }
// }
// return newList;
// }
//
// public static double[] scaleInputsData(ArrayList<Double> inputList,
// double scale_factor) {
// double[] inputs = new double[inputList.size()];
// for (int i = 0; i <= inputList.size() - 1; i++) {
// inputs[i] = inputList.get(i) * scale_factor;
// }
// return inputs;
// }
// }
// Path: acmeair-reporter/src/main/java/com/acmeair/reporter/parser/component/NmonParser.java
import java.io.File;
import com.acmeair.reporter.parser.IndividualChartResults;
import com.acmeair.reporter.parser.ResultParser;
import com.acmeair.reporter.parser.ResultParserHelper;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.reporter.parser.component;
public class NmonParser extends ResultParser{
private String nmonFileName = "output.nmon";
public NmonParser(){
super.setMultipleYAxisLabel("usr%+sys%"); //default label
}
@Override
protected void processFile(File file) {
IndividualChartResults result= getData(file.getPath());
| super.processData(ResultParserHelper.scaleDown(result.getInputList(),8),false);
|
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/Coupon.java
// public interface Coupon {
//
// int getId();
//
// void setId(int id);
//
// String getPromotionId();
//
// void setPromotionId(String promotionId);
//
// Date getTime();
//
// void setTime(Date time);
//
// float getDiscount();
//
// void setDiscount(float discount);
//
// String getCustomerId();
//
// void setCustomerId(String customerId);
//
// boolean isUsed();
//
// void setUsed(boolean used);
// }
| import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.acmeair.entities.Coupon; | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.entities;
@Document(collection = "coupon")
@Entity(name = "coupon") | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/Coupon.java
// public interface Coupon {
//
// int getId();
//
// void setId(int id);
//
// String getPromotionId();
//
// void setPromotionId(String promotionId);
//
// Date getTime();
//
// void setTime(Date time);
//
// float getDiscount();
//
// void setDiscount(float discount);
//
// String getCustomerId();
//
// void setCustomerId(String customerId);
//
// boolean isUsed();
//
// void setUsed(boolean used);
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.acmeair.entities.Coupon;
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.entities;
@Document(collection = "coupon")
@Entity(name = "coupon") | public class CouponImpl implements Coupon, Serializable { |
WillemJiang/acmeair | acmeair-customer-service/src/test/java/com/acmeair/web/CustomerServiceContractTest.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
| import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.service.CustomerService;
import com.acmeair.service.CustomerServiceSupport;
import com.acmeair.web.dto.CustomerSessionInfo;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import test.com.acmeair.service.CustomerRestApplication;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when; | package com.acmeair.web;
@RunWith(PactRunner.class)
@PactFolder("../target/pacts") | // Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerServiceSupport.java
// public abstract class CustomerServiceSupport implements CustomerService {
// protected static final int DAYS_TO_ALLOW_SESSION = 1;
//
// @Inject
// protected KeyGenerator keyGenerator;
//
//
// protected abstract Customer getCustomer(String username);
//
// @Override
// public Customer getCustomerByUsername(String username) {
// Customer c = getCustomer(username);
// if (c != null) {
// c.setPassword(null);
// }
// return c;
// }
//
// @Override
// public boolean validateCustomer(String username, String password) {
// boolean validatedCustomer = false;
// Customer customerToValidate = getCustomer(username);
// if (customerToValidate != null) {
// validatedCustomer = password.equals(customerToValidate.getPassword());
// }
// return validatedCustomer;
// }
//
// @Override
// public Customer getCustomerByUsernameAndPassword(String username, String password) {
// Customer c = getCustomer(username);
// if (c != null && !c.getPassword().equals(password)) {
// return null;
// }
// // Should we also set the password to null?
// return c;
// }
//
// @Override
// public CustomerSession validateSession(String sessionid) {
// CustomerSession cSession = getSession(sessionid);
// if (cSession == null) {
// return null;
// }
//
// Date now = new Date();
//
// if (cSession.getTimeoutTime().before(now)) {
// removeSession(cSession);
// return null;
// }
// return cSession;
// }
//
// protected abstract CustomerSession getSession(String sessionid);
//
// protected abstract void removeSession(CustomerSession session);
//
// @Override
// public CustomerSession createSession(String customerId) {
// String sessionId = keyGenerator.generate().toString();
// Date now = new Date();
// Calendar c = Calendar.getInstance();
// c.setTime(now);
// c.add(Calendar.DAY_OF_YEAR, DAYS_TO_ALLOW_SESSION);
// Date expiration = c.getTime();
//
// return createSession(sessionId, customerId, now, expiration);
// }
//
// protected abstract CustomerSession createSession(String sessionId, String customerId, Date creation, Date expiration);
//
// }
// Path: acmeair-customer-service/src/test/java/com/acmeair/web/CustomerServiceContractTest.java
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactFolder;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.service.CustomerService;
import com.acmeair.service.CustomerServiceSupport;
import com.acmeair.web.dto.CustomerSessionInfo;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import test.com.acmeair.service.CustomerRestApplication;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
package com.acmeair.web;
@RunWith(PactRunner.class)
@PactFolder("../target/pacts") | @Provider("CustomerService") |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/web/LoginREST.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
| import com.acmeair.entities.CustomerSession;
import com.acmeair.entities.TokenInfo;
import com.acmeair.service.CustomerService;
import com.acmeair.web.dto.CustomerSessionInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "login")
@Path("/api/login")
public class LoginREST {
public static final Logger logger = LoggerFactory.getLogger("LoginREST");
@Autowired | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/web/LoginREST.java
import com.acmeair.entities.CustomerSession;
import com.acmeair.entities.TokenInfo;
import com.acmeair.service.CustomerService;
import com.acmeair.web.dto.CustomerSessionInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "login")
@Path("/api/login")
public class LoginREST {
public static final Logger logger = LoggerFactory.getLogger("LoginREST");
@Autowired | private CustomerService customerService; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/web/LoginREST.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
| import com.acmeair.entities.CustomerSession;
import com.acmeair.entities.TokenInfo;
import com.acmeair.service.CustomerService;
import com.acmeair.web.dto.CustomerSessionInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; | /*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "login")
@Path("/api/login")
public class LoginREST {
public static final Logger logger = LoggerFactory.getLogger("LoginREST");
@Autowired
private CustomerService customerService;
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = 403, message = "Invalid user information"),@ApiResponse(code = 500, message = "CustomerService Internal Server Error") })
public TokenInfo login(@FormParam("login") String login, @FormParam("password") String password) {
logger.info("Received login request of username [{}]", login);
try {
boolean validCustomer = customerService.validateCustomer(login, password);
if (!validCustomer) {
logger.info("No such user exists with username [{}]", login);
throw new InvocationException(Status.FORBIDDEN, "username or password is wrong!");
}
logger.info("Validated user [{}] successfully", login); | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/web/LoginREST.java
import com.acmeair.entities.CustomerSession;
import com.acmeair.entities.TokenInfo;
import com.acmeair.service.CustomerService;
import com.acmeair.web.dto.CustomerSessionInfo;
import io.servicecomb.provider.rest.common.RestSchema;
import io.servicecomb.swagger.invocation.exception.InvocationException;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
/*******************************************************************************
* Copyright (c) 2013 IBM Corp.
*
* 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.acmeair.web;
@RestSchema(schemaId = "login")
@Path("/api/login")
public class LoginREST {
public static final Logger logger = LoggerFactory.getLogger("LoginREST");
@Autowired
private CustomerService customerService;
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = { @ApiResponse(code = 403, message = "Invalid user information"),@ApiResponse(code = 500, message = "CustomerService Internal Server Error") })
public TokenInfo login(@FormParam("login") String login, @FormParam("password") String password) {
logger.info("Received login request of username [{}]", login);
try {
boolean validCustomer = customerService.validateCustomer(login, password);
if (!validCustomer) {
logger.info("No such user exists with username [{}]", login);
throw new InvocationException(Status.FORBIDDEN, "username or password is wrong!");
}
logger.info("Validated user [{}] successfully", login); | CustomerSession session = customerService.createSession(login); |
WillemJiang/acmeair | acmeair-webapp/src/test/java/com/acmeair/hystrix/AuthenticationCommandValidationFailedTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
| import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; | package com.acmeair.hystrix;
public class AuthenticationCommandValidationFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
| // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
// Path: acmeair-webapp/src/test/java/com/acmeair/hystrix/AuthenticationCommandValidationFailedTest.java
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
package com.acmeair.hystrix;
public class AuthenticationCommandValidationFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
| private final AuthenticationService userService = new TestAuthenticationCommand(providerRule.getConfig().url()); |
WillemJiang/acmeair | acmeair-webapp/src/test/java/com/acmeair/hystrix/AuthenticationCommandValidationFailedTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
| import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is; | package com.acmeair.hystrix;
public class AuthenticationCommandValidationFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
private final AuthenticationService userService = new TestAuthenticationCommand(providerRule.getConfig().url());
private final String sessionId = "session-mike-123";
@Pact(consumer = "AuthenticationService")
public PactFragment createFragment(PactDslWithProvider pactDslWithProvider) throws JsonProcessingException {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
return pactDslWithProvider
.given("No customer Mike found")
.uponReceiving("a request to validate Mike")
.path("/rest/api/login/validate")
.method("POST")
.query("sessionId=" + sessionId)
.headers(headers)
.willRespondWith()
.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
.toFragment();
}
@Test
@PactVerification
public void getsNullWhenNoCustomerFound() throws IOException { | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-services/src/main/java/com/acmeair/service/AuthenticationService.java
// public interface AuthenticationService {
// CustomerSession validateCustomerSession(String sessionId);
// }
// Path: acmeair-webapp/src/test/java/com/acmeair/hystrix/AuthenticationCommandValidationFailedTest.java
import au.com.dius.pact.consumer.Pact;
import au.com.dius.pact.consumer.PactProviderRule;
import au.com.dius.pact.consumer.PactVerification;
import au.com.dius.pact.consumer.dsl.PactDslWithProvider;
import au.com.dius.pact.model.PactFragment;
import com.acmeair.entities.CustomerSession;
import com.acmeair.service.AuthenticationService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.http.HttpStatus;
import org.junit.Rule;
import org.junit.Test;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
package com.acmeair.hystrix;
public class AuthenticationCommandValidationFailedTest {
@Rule
public final PactProviderRule providerRule = new PactProviderRule("CustomerService", this);
private final AuthenticationService userService = new TestAuthenticationCommand(providerRule.getConfig().url());
private final String sessionId = "session-mike-123";
@Pact(consumer = "AuthenticationService")
public PactFragment createFragment(PactDslWithProvider pactDslWithProvider) throws JsonProcessingException {
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
return pactDslWithProvider
.given("No customer Mike found")
.uponReceiving("a request to validate Mike")
.path("/rest/api/login/validate")
.method("POST")
.query("sessionId=" + sessionId)
.headers(headers)
.willRespondWith()
.status(HttpStatus.SC_INTERNAL_SERVER_ERROR)
.toFragment();
}
@Test
@PactVerification
public void getsNullWhenNoCustomerFound() throws IOException { | CustomerSession customerSession = userService.validateCustomerSession(sessionId); |
WillemJiang/acmeair | acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
| import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest { | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
// Path: acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest { | private CustomerAddress address; |
WillemJiang/acmeair | acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
| import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest {
private CustomerAddress address;
private CustomerImpl customer;
private CustomerSessionImpl customerSession;
@InjectMocks
private final CustomerServiceImpl customerService = new CustomerServiceImpl();
@Mock | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
// Path: acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest {
private CustomerAddress address;
private CustomerImpl customer;
private CustomerSessionImpl customerSession;
@InjectMocks
private final CustomerServiceImpl customerService = new CustomerServiceImpl();
@Mock | private CustomerRepository customerRepository; |
WillemJiang/acmeair | acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
| import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest {
private CustomerAddress address;
private CustomerImpl customer;
private CustomerSessionImpl customerSession;
@InjectMocks
private final CustomerServiceImpl customerService = new CustomerServiceImpl();
@Mock
private CustomerRepository customerRepository;
@Mock | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
// Path: acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package com.acmeair.morphia.services;
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceImplTest {
private CustomerAddress address;
private CustomerImpl customer;
private CustomerSessionImpl customerSession;
@InjectMocks
private final CustomerServiceImpl customerService = new CustomerServiceImpl();
@Mock
private CustomerRepository customerRepository;
@Mock | private CustomerSessionRepository sessionRepository; |
WillemJiang/acmeair | acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
| import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | assertThat(c, is(nullValue()));
}
@Test
public void validCustomerIfUsernameAndPasswordMatches() {
when(customerRepository.findOne(customer.getCustomerId())).thenReturn(this.customer);
boolean isValid = customerService.validateCustomer(customer.getUsername(), customer.getPassword());
assertThat(isValid, is(true));
}
@Test
public void inValidCustomerIfUsernameAndPasswordDoesNotMatch() {
when(customerRepository.findOne(customer.getCustomerId())).thenReturn(this.customer);
boolean isValid = customerService.validateCustomer(customer.getUsername(), uniquify("wrong password"));
assertThat(isValid, is(false));
}
@Test
public void inValidCustomerIfUserDoesNotExist() {
boolean isValid = customerService.validateCustomer(uniquify("unknown user"), uniquify("wrong password"));
assertThat(isValid, is(false));
}
@Test
public void savesSessionIntoDatabase() { | // Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerAddress.java
// public interface CustomerAddress {
//
//
// String getStreetAddress1();
// void setStreetAddress1(String streetAddress1);
// String getStreetAddress2();
// void setStreetAddress2(String streetAddress2);
// String getCity();
// void setCity(String city);
// String getStateProvince();
// void setStateProvince(String stateProvince);
// String getCountry();
// void setCountry(String country);
// String getPostalCode();
// void setPostalCode(String postalCode);
//
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/entities/CustomerSession.java
// public interface CustomerSession {
//
// String SESSIONID_COOKIE_NAME = "sessionid";
//
// String getId();
//
//
// String getCustomerid();
//
//
// Date getLastAccessedTime();
//
//
// Date getTimeoutTime();
//
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerRepository.java
// public interface CustomerRepository extends CrudRepository<CustomerImpl, String> {
//
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CustomerSessionRepository.java
// public interface CustomerSessionRepository extends CrudRepository<CustomerSessionImpl, String> {
//
// }
// Path: acmeair-customer-service/src/test/java/com/acmeair/morphia/services/CustomerServiceImplTest.java
import br.com.six2six.fixturefactory.Fixture;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import com.acmeair.entities.Customer;
import com.acmeair.entities.CustomerAddress;
import com.acmeair.entities.CustomerSession;
import com.acmeair.morphia.entities.CustomerAddressImpl;
import com.acmeair.morphia.entities.CustomerImpl;
import com.acmeair.morphia.entities.CustomerSessionImpl;
import com.acmeair.morphia.repositories.CustomerRepository;
import com.acmeair.morphia.repositories.CustomerSessionRepository;
import com.acmeair.service.KeyGenerator;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Date;
import static com.seanyinx.github.unit.scaffolding.Randomness.uniquify;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
assertThat(c, is(nullValue()));
}
@Test
public void validCustomerIfUsernameAndPasswordMatches() {
when(customerRepository.findOne(customer.getCustomerId())).thenReturn(this.customer);
boolean isValid = customerService.validateCustomer(customer.getUsername(), customer.getPassword());
assertThat(isValid, is(true));
}
@Test
public void inValidCustomerIfUsernameAndPasswordDoesNotMatch() {
when(customerRepository.findOne(customer.getCustomerId())).thenReturn(this.customer);
boolean isValid = customerService.validateCustomer(customer.getUsername(), uniquify("wrong password"));
assertThat(isValid, is(false));
}
@Test
public void inValidCustomerIfUserDoesNotExist() {
boolean isValid = customerService.validateCustomer(uniquify("unknown user"), uniquify("wrong password"));
assertThat(isValid, is(false));
}
@Test
public void savesSessionIntoDatabase() { | CustomerSession session = customerService.createSession(customer.getCustomerId()); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
| import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import com.acmeair.service.CustomerService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses; | package com.acmeair.config;
@RestSchema(schemaId = "customer_configuration")
@Path("/info/config")
@Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
public class CustomerConfiguration {
@Autowired | // Path: acmeair-customer-service/src/main/java/com/acmeair/service/CustomerService.java
// public interface CustomerService {
// Customer createCustomer(String username, String password, Customer.MemberShipStatus status, int total_miles, int miles_ytd, String phoneNumber,
// Customer.PhoneType phoneNumberType, CustomerAddressImpl address
// );
//
// CustomerAddressImpl createAddress(String streetAddress1, String streetAddress2, String city, String stateProvince, String country, String postalCode);
//
// Customer updateCustomer(Customer customer);
//
// Customer getCustomerByUsername(String username);
//
// boolean validateCustomer(String username, String password);
//
// Customer getCustomerByUsernameAndPassword(String username, String password);
//
// CustomerSession validateSession(String sessionid);
//
// CustomerSession createSession(String customerId);
//
// void invalidateSession(String sessionid);
//
// Long count();
//
// Long countSessions();
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/config/CustomerConfiguration.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import com.acmeair.service.CustomerService;
import io.servicecomb.provider.rest.common.RestSchema;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
package com.acmeair.config;
@RestSchema(schemaId = "customer_configuration")
@Path("/info/config")
@Api(value = "Customer Service Configuration Information Service", produces = MediaType.APPLICATION_JSON)
public class CustomerConfiguration {
@Autowired | private CustomerService customerService; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
| import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo; | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
| // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo;
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
| private final CouponRepository couponRepository; |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
| import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo; | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
private final CouponRepository couponRepository;
private final SeckillService seckillService;
@Autowired
public CouponServiceImpl(CouponRepository couponRepository, SeckillService seckillService) {
this.couponRepository = couponRepository;
this.seckillService = seckillService;
final Runnable executor = () -> { | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo;
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
private final CouponRepository couponRepository;
private final SeckillService seckillService;
@Autowired
public CouponServiceImpl(CouponRepository couponRepository, SeckillService seckillService) {
this.couponRepository = couponRepository;
this.seckillService = seckillService;
final Runnable executor = () -> { | CouponImpl latestCoupon = this.couponRepository.findTopByOrderByIdDesc(); |
WillemJiang/acmeair | acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
| import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo; | /*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
private final CouponRepository couponRepository;
private final SeckillService seckillService;
@Autowired
public CouponServiceImpl(CouponRepository couponRepository, SeckillService seckillService) {
this.couponRepository = couponRepository;
this.seckillService = seckillService;
final Runnable executor = () -> {
CouponImpl latestCoupon = this.couponRepository.findTopByOrderByIdDesc();
int latestId = latestCoupon == null ? 0 : latestCoupon.getId(); | // Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/entities/CouponImpl.java
// @Document(collection = "coupon")
// @Entity(name = "coupon")
// public class CouponImpl implements Coupon, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// @Id
// @Column(name = "id")
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// private boolean isUsed;
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
//
// public boolean isUsed() {
// return isUsed;
// }
//
// public void setUsed(boolean used) {
// isUsed = used;
// }
//
// public CouponImpl() {
// }
//
// public CouponImpl(int id, String promotionId, Date time, float discount, String customerId, boolean isUsed) {
// this.id = id;
// this.promotionId = promotionId;
// this.time = time;
// this.discount = discount;
// this.customerId = customerId;
// this.isUsed = isUsed;
// }
// }
//
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/repositories/CouponRepository.java
// public interface CouponRepository extends CrudRepository<CouponImpl, Integer> {
// List<CouponImpl> findByCustomerIdAndIsUsed(String customerId, boolean isUsed);
//
// CouponImpl findTopByOrderByIdDesc();
// }
//
// Path: acmeair-customer-common/src/main/java/com/acmeair/web/dto/CouponInfo.java
// public class CouponInfo implements Serializable {
// private static final long serialVersionUID = 1L;
//
// private int id;
//
// private String promotionId;
//
// private Date time;
//
// private float discount;
//
// private String customerId;
//
// public CouponInfo() {
// }
//
// public static long getSerialVersionUID() {
// return serialVersionUID;
// }
//
// public int getId() {
// return id;
// }
//
// public void setId(int id) {
// this.id = id;
// }
//
// public String getPromotionId() {
// return promotionId;
// }
//
// public void setPromotionId(String promotionId) {
// this.promotionId = promotionId;
// }
//
// public Date getTime() {
// return time;
// }
//
// public void setTime(Date time) {
// this.time = time;
// }
//
// public float getDiscount() {
// return discount;
// }
//
// public void setDiscount(float discount) {
// this.discount = discount;
// }
//
// public String getCustomerId() {
// return customerId;
// }
//
// public void setCustomerId(String customerId) {
// this.customerId = customerId;
// }
// }
// Path: acmeair-customer-service/src/main/java/com/acmeair/morphia/services/CouponServiceImpl.java
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.acmeair.morphia.entities.CouponImpl;
import com.acmeair.morphia.repositories.CouponRepository;
import com.acmeair.service.CouponService;
import com.acmeair.service.SeckillService;
import com.acmeair.web.dto.CouponInfo;
/*
* Copyright 2017 Huawei Technologies Co., Ltd
*
* 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.acmeair.morphia.services;
@Service
public class CouponServiceImpl implements CouponService {
private final CouponRepository couponRepository;
private final SeckillService seckillService;
@Autowired
public CouponServiceImpl(CouponRepository couponRepository, SeckillService seckillService) {
this.couponRepository = couponRepository;
this.seckillService = seckillService;
final Runnable executor = () -> {
CouponImpl latestCoupon = this.couponRepository.findTopByOrderByIdDesc();
int latestId = latestCoupon == null ? 0 : latestCoupon.getId(); | List<CouponInfo> seckillCoupons = this.seckillService.syncCoupons(latestId); |
yandex-qatools/matchers-java | webdriver-matchers/src/test/java/ru/yandex/qatools/matchers/webdriver/RefreshPageMatcherDecoratorTest.java | // Path: matcher-decorators/src/main/java/ru/yandex/qatools/matchers/decorators/MatcherDecoratorsBuilder.java
// @Factory
// public static <T> MatcherDecoratorsBuilder<T> should(final Matcher<? super T> matcher) {
// return new MatcherDecoratorsBuilder<T>(matcher);
// }
//
// Path: webdriver-matchers/src/main/java/ru/yandex/qatools/matchers/webdriver/RefreshPageAction.java
// public static RefreshPageAction pageRefresh(final WebDriver driver) {
// return new RefreshPageAction(driver);
// }
| import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.openqa.selenium.WebDriver;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.openqa.selenium.WebDriver.Navigation;
import static ru.yandex.qatools.matchers.decorators.MatcherDecoratorsBuilder.should;
import static ru.yandex.qatools.matchers.webdriver.RefreshPageAction.pageRefresh; | package ru.yandex.qatools.matchers.webdriver;
/**
* Created with IntelliJ IDEA.
* User: lanwen
* Date: 12.02.13
* Time: 0:08
*/
@RunWith(MockitoJUnitRunner.class)
public class RefreshPageMatcherDecoratorTest {
public static final boolean THE_OBJECT = true;
public static final boolean NOT_SAME_OBJECT = false;
@Mock
private WebDriver driver;
@Mock
private Navigation navigation;
@Mock
private Matcher<Object> matcher;
@Test(expected = AssertionError.class)
public void decoratedMatcherShouldNotMatchDifferentObjects() {
when(driver.navigate()).thenReturn(navigation);
| // Path: matcher-decorators/src/main/java/ru/yandex/qatools/matchers/decorators/MatcherDecoratorsBuilder.java
// @Factory
// public static <T> MatcherDecoratorsBuilder<T> should(final Matcher<? super T> matcher) {
// return new MatcherDecoratorsBuilder<T>(matcher);
// }
//
// Path: webdriver-matchers/src/main/java/ru/yandex/qatools/matchers/webdriver/RefreshPageAction.java
// public static RefreshPageAction pageRefresh(final WebDriver driver) {
// return new RefreshPageAction(driver);
// }
// Path: webdriver-matchers/src/test/java/ru/yandex/qatools/matchers/webdriver/RefreshPageMatcherDecoratorTest.java
import org.hamcrest.Matcher;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.openqa.selenium.WebDriver;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.openqa.selenium.WebDriver.Navigation;
import static ru.yandex.qatools.matchers.decorators.MatcherDecoratorsBuilder.should;
import static ru.yandex.qatools.matchers.webdriver.RefreshPageAction.pageRefresh;
package ru.yandex.qatools.matchers.webdriver;
/**
* Created with IntelliJ IDEA.
* User: lanwen
* Date: 12.02.13
* Time: 0:08
*/
@RunWith(MockitoJUnitRunner.class)
public class RefreshPageMatcherDecoratorTest {
public static final boolean THE_OBJECT = true;
public static final boolean NOT_SAME_OBJECT = false;
@Mock
private WebDriver driver;
@Mock
private Navigation navigation;
@Mock
private Matcher<Object> matcher;
@Test(expected = AssertionError.class)
public void decoratedMatcherShouldNotMatchDifferentObjects() {
when(driver.navigate()).thenReturn(navigation);
| assertThat(THE_OBJECT, should(is(NOT_SAME_OBJECT)).after(pageRefresh(driver))); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.